winhttp: Reverse the order of arguments passed to Invoke.
[wine] / dlls / urlmon / uri.c
1 /*
2  * Copyright 2010 Jacek Caban for CodeWeavers
3  * Copyright 2010 Thomas Mullaly
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Lesser General Public
7  * License as published by the Free Software Foundation; either
8  * version 2.1 of the License, or (at your option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * Lesser General Public License for more details.
14  *
15  * You should have received a copy of the GNU Lesser General Public
16  * License along with this library; if not, write to the Free Software
17  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
18  */
19
20 #include "urlmon_main.h"
21 #include "wine/debug.h"
22
23 #define NO_SHLWAPI_REG
24 #include "shlwapi.h"
25
26 #include "strsafe.h"
27
28 #define UINT_MAX 0xffffffff
29 #define USHORT_MAX 0xffff
30
31 #define URI_DISPLAY_NO_ABSOLUTE_URI         0x1
32 #define URI_DISPLAY_NO_DEFAULT_PORT_AUTH    0x2
33
34 #define ALLOW_NULL_TERM_SCHEME          0x01
35 #define ALLOW_NULL_TERM_USER_NAME       0x02
36 #define ALLOW_NULL_TERM_PASSWORD        0x04
37 #define ALLOW_BRACKETLESS_IP_LITERAL    0x08
38 #define SKIP_IP_FUTURE_CHECK            0x10
39 #define IGNORE_PORT_DELIMITER           0x20
40
41 #define RAW_URI_FORCE_PORT_DISP     0x1
42 #define RAW_URI_CONVERT_TO_DOS_PATH 0x2
43
44 #define COMBINE_URI_FORCE_FLAG_USE  0x1
45
46 WINE_DEFAULT_DEBUG_CHANNEL(urlmon);
47
48 static const IID IID_IUriObj = {0x4b364760,0x9f51,0x11df,{0x98,0x1c,0x08,0x00,0x20,0x0c,0x9a,0x66}};
49
50 typedef struct {
51     IUri                IUri_iface;
52     IUriBuilderFactory  IUriBuilderFactory_iface;
53
54     LONG ref;
55
56     BSTR            raw_uri;
57
58     /* Information about the canonicalized URI's buffer. */
59     WCHAR           *canon_uri;
60     DWORD           canon_size;
61     DWORD           canon_len;
62     BOOL            display_modifiers;
63     DWORD           create_flags;
64
65     INT             scheme_start;
66     DWORD           scheme_len;
67     URL_SCHEME      scheme_type;
68
69     INT             userinfo_start;
70     DWORD           userinfo_len;
71     INT             userinfo_split;
72
73     INT             host_start;
74     DWORD           host_len;
75     Uri_HOST_TYPE   host_type;
76
77     INT             port_offset;
78     DWORD           port;
79     BOOL            has_port;
80
81     INT             authority_start;
82     DWORD           authority_len;
83
84     INT             domain_offset;
85
86     INT             path_start;
87     DWORD           path_len;
88     INT             extension_offset;
89
90     INT             query_start;
91     DWORD           query_len;
92
93     INT             fragment_start;
94     DWORD           fragment_len;
95 } Uri;
96
97 typedef struct {
98     IUriBuilder IUriBuilder_iface;
99     LONG ref;
100
101     Uri *uri;
102     DWORD modified_props;
103
104     WCHAR   *fragment;
105     DWORD   fragment_len;
106
107     WCHAR   *host;
108     DWORD   host_len;
109
110     WCHAR   *password;
111     DWORD   password_len;
112
113     WCHAR   *path;
114     DWORD   path_len;
115
116     BOOL    has_port;
117     DWORD   port;
118
119     WCHAR   *query;
120     DWORD   query_len;
121
122     WCHAR   *scheme;
123     DWORD   scheme_len;
124
125     WCHAR   *username;
126     DWORD   username_len;
127 } UriBuilder;
128
129 typedef struct {
130     const WCHAR *str;
131     DWORD       len;
132 } h16;
133
134 typedef struct {
135     /* IPv6 addresses can hold up to 8 h16 components. */
136     h16         components[8];
137     DWORD       h16_count;
138
139     /* An IPv6 can have 1 elision ("::"). */
140     const WCHAR *elision;
141
142     /* An IPv6 can contain 1 IPv4 address as the last 32bits of the address. */
143     const WCHAR *ipv4;
144     DWORD       ipv4_len;
145
146     INT         components_size;
147     INT         elision_size;
148 } ipv6_address;
149
150 typedef struct {
151     BSTR            uri;
152
153     BOOL            is_relative;
154     BOOL            is_opaque;
155     BOOL            has_implicit_scheme;
156     BOOL            has_implicit_ip;
157     UINT            implicit_ipv4;
158     BOOL            must_have_path;
159
160     const WCHAR     *scheme;
161     DWORD           scheme_len;
162     URL_SCHEME      scheme_type;
163
164     const WCHAR     *username;
165     DWORD           username_len;
166
167     const WCHAR     *password;
168     DWORD           password_len;
169
170     const WCHAR     *host;
171     DWORD           host_len;
172     Uri_HOST_TYPE   host_type;
173
174     BOOL            has_ipv6;
175     ipv6_address    ipv6_address;
176
177     BOOL            has_port;
178     const WCHAR     *port;
179     DWORD           port_len;
180     DWORD           port_value;
181
182     const WCHAR     *path;
183     DWORD           path_len;
184
185     const WCHAR     *query;
186     DWORD           query_len;
187
188     const WCHAR     *fragment;
189     DWORD           fragment_len;
190 } parse_data;
191
192 static const CHAR hexDigits[] = "0123456789ABCDEF";
193
194 /* List of scheme types/scheme names that are recognized by the IUri interface as of IE 7. */
195 static const struct {
196     URL_SCHEME  scheme;
197     WCHAR       scheme_name[16];
198 } recognized_schemes[] = {
199     {URL_SCHEME_FTP,            {'f','t','p',0}},
200     {URL_SCHEME_HTTP,           {'h','t','t','p',0}},
201     {URL_SCHEME_GOPHER,         {'g','o','p','h','e','r',0}},
202     {URL_SCHEME_MAILTO,         {'m','a','i','l','t','o',0}},
203     {URL_SCHEME_NEWS,           {'n','e','w','s',0}},
204     {URL_SCHEME_NNTP,           {'n','n','t','p',0}},
205     {URL_SCHEME_TELNET,         {'t','e','l','n','e','t',0}},
206     {URL_SCHEME_WAIS,           {'w','a','i','s',0}},
207     {URL_SCHEME_FILE,           {'f','i','l','e',0}},
208     {URL_SCHEME_MK,             {'m','k',0}},
209     {URL_SCHEME_HTTPS,          {'h','t','t','p','s',0}},
210     {URL_SCHEME_SHELL,          {'s','h','e','l','l',0}},
211     {URL_SCHEME_SNEWS,          {'s','n','e','w','s',0}},
212     {URL_SCHEME_LOCAL,          {'l','o','c','a','l',0}},
213     {URL_SCHEME_JAVASCRIPT,     {'j','a','v','a','s','c','r','i','p','t',0}},
214     {URL_SCHEME_VBSCRIPT,       {'v','b','s','c','r','i','p','t',0}},
215     {URL_SCHEME_ABOUT,          {'a','b','o','u','t',0}},
216     {URL_SCHEME_RES,            {'r','e','s',0}},
217     {URL_SCHEME_MSSHELLROOTED,  {'m','s','-','s','h','e','l','l','-','r','o','o','t','e','d',0}},
218     {URL_SCHEME_MSSHELLIDLIST,  {'m','s','-','s','h','e','l','l','-','i','d','l','i','s','t',0}},
219     {URL_SCHEME_MSHELP,         {'h','c','p',0}},
220     {URL_SCHEME_WILDCARD,       {'*',0}}
221 };
222
223 /* List of default ports Windows recognizes. */
224 static const struct {
225     URL_SCHEME  scheme;
226     USHORT      port;
227 } default_ports[] = {
228     {URL_SCHEME_FTP,    21},
229     {URL_SCHEME_HTTP,   80},
230     {URL_SCHEME_GOPHER, 70},
231     {URL_SCHEME_NNTP,   119},
232     {URL_SCHEME_TELNET, 23},
233     {URL_SCHEME_WAIS,   210},
234     {URL_SCHEME_HTTPS,  443},
235 };
236
237 /* List of 3-character top level domain names Windows seems to recognize.
238  * There might be more, but, these are the only ones I've found so far.
239  */
240 static const struct {
241     WCHAR tld_name[4];
242 } recognized_tlds[] = {
243     {{'c','o','m',0}},
244     {{'e','d','u',0}},
245     {{'g','o','v',0}},
246     {{'i','n','t',0}},
247     {{'m','i','l',0}},
248     {{'n','e','t',0}},
249     {{'o','r','g',0}}
250 };
251
252 static Uri *get_uri_obj(IUri *uri)
253 {
254     Uri *ret;
255     HRESULT hres;
256
257     hres = IUri_QueryInterface(uri, &IID_IUriObj, (void**)&ret);
258     return SUCCEEDED(hres) ? ret : NULL;
259 }
260
261 static inline BOOL is_alpha(WCHAR val) {
262     return ((val >= 'a' && val <= 'z') || (val >= 'A' && val <= 'Z'));
263 }
264
265 static inline BOOL is_num(WCHAR val) {
266     return (val >= '0' && val <= '9');
267 }
268
269 static inline BOOL is_drive_path(const WCHAR *str) {
270     return (is_alpha(str[0]) && (str[1] == ':' || str[1] == '|'));
271 }
272
273 static inline BOOL is_unc_path(const WCHAR *str) {
274     return (str[0] == '\\' && str[0] == '\\');
275 }
276
277 static inline BOOL is_forbidden_dos_path_char(WCHAR val) {
278     return (val == '>' || val == '<' || val == '\"');
279 }
280
281 /* A URI is implicitly a file path if it begins with
282  * a drive letter (e.g. X:) or starts with "\\" (UNC path).
283  */
284 static inline BOOL is_implicit_file_path(const WCHAR *str) {
285     return (is_unc_path(str) || (is_alpha(str[0]) && str[1] == ':'));
286 }
287
288 /* Checks if the URI is a hierarchical URI. A hierarchical
289  * URI is one that has "//" after the scheme.
290  */
291 static BOOL check_hierarchical(const WCHAR **ptr) {
292     const WCHAR *start = *ptr;
293
294     if(**ptr != '/')
295         return FALSE;
296
297     ++(*ptr);
298     if(**ptr != '/') {
299         *ptr = start;
300         return FALSE;
301     }
302
303     ++(*ptr);
304     return TRUE;
305 }
306
307 /* unreserved    = ALPHA / DIGIT / "-" / "." / "_" / "~" */
308 static inline BOOL is_unreserved(WCHAR val) {
309     return (is_alpha(val) || is_num(val) || val == '-' || val == '.' ||
310             val == '_' || val == '~');
311 }
312
313 /* sub-delims    = "!" / "$" / "&" / "'" / "(" / ")"
314  *               / "*" / "+" / "," / ";" / "="
315  */
316 static inline BOOL is_subdelim(WCHAR val) {
317     return (val == '!' || val == '$' || val == '&' ||
318             val == '\'' || val == '(' || val == ')' ||
319             val == '*' || val == '+' || val == ',' ||
320             val == ';' || val == '=');
321 }
322
323 /* gen-delims  = ":" / "/" / "?" / "#" / "[" / "]" / "@" */
324 static inline BOOL is_gendelim(WCHAR val) {
325     return (val == ':' || val == '/' || val == '?' ||
326             val == '#' || val == '[' || val == ']' ||
327             val == '@');
328 }
329
330 /* Characters that delimit the end of the authority
331  * section of a URI. Sometimes a '\\' is considered
332  * an authority delimiter.
333  */
334 static inline BOOL is_auth_delim(WCHAR val, BOOL acceptSlash) {
335     return (val == '#' || val == '/' || val == '?' ||
336             val == '\0' || (acceptSlash && val == '\\'));
337 }
338
339 /* reserved = gen-delims / sub-delims */
340 static inline BOOL is_reserved(WCHAR val) {
341     return (is_subdelim(val) || is_gendelim(val));
342 }
343
344 static inline BOOL is_hexdigit(WCHAR val) {
345     return ((val >= 'a' && val <= 'f') ||
346             (val >= 'A' && val <= 'F') ||
347             (val >= '0' && val <= '9'));
348 }
349
350 static inline BOOL is_path_delim(WCHAR val) {
351     return (!val || val == '#' || val == '?');
352 }
353
354 static inline BOOL is_slash(WCHAR c)
355 {
356     return c == '/' || c == '\\';
357 }
358
359 static BOOL is_default_port(URL_SCHEME scheme, DWORD port) {
360     DWORD i;
361
362     for(i = 0; i < sizeof(default_ports)/sizeof(default_ports[0]); ++i) {
363         if(default_ports[i].scheme == scheme && default_ports[i].port)
364             return TRUE;
365     }
366
367     return FALSE;
368 }
369
370 /* List of schemes types Windows seems to expect to be hierarchical. */
371 static inline BOOL is_hierarchical_scheme(URL_SCHEME type) {
372     return(type == URL_SCHEME_HTTP || type == URL_SCHEME_FTP ||
373            type == URL_SCHEME_GOPHER || type == URL_SCHEME_NNTP ||
374            type == URL_SCHEME_TELNET || type == URL_SCHEME_WAIS ||
375            type == URL_SCHEME_FILE || type == URL_SCHEME_HTTPS ||
376            type == URL_SCHEME_RES);
377 }
378
379 /* Checks if 'flags' contains an invalid combination of Uri_CREATE flags. */
380 static inline BOOL has_invalid_flag_combination(DWORD flags) {
381     return((flags & Uri_CREATE_DECODE_EXTRA_INFO && flags & Uri_CREATE_NO_DECODE_EXTRA_INFO) ||
382            (flags & Uri_CREATE_CANONICALIZE && flags & Uri_CREATE_NO_CANONICALIZE) ||
383            (flags & Uri_CREATE_CRACK_UNKNOWN_SCHEMES && flags & Uri_CREATE_NO_CRACK_UNKNOWN_SCHEMES) ||
384            (flags & Uri_CREATE_PRE_PROCESS_HTML_URI && flags & Uri_CREATE_NO_PRE_PROCESS_HTML_URI) ||
385            (flags & Uri_CREATE_IE_SETTINGS && flags & Uri_CREATE_NO_IE_SETTINGS));
386 }
387
388 /* Applies each default Uri_CREATE flags to 'flags' if it
389  * doesn't cause a flag conflict.
390  */
391 static void apply_default_flags(DWORD *flags) {
392     if(!(*flags & Uri_CREATE_NO_CANONICALIZE))
393         *flags |= Uri_CREATE_CANONICALIZE;
394     if(!(*flags & Uri_CREATE_NO_DECODE_EXTRA_INFO))
395         *flags |= Uri_CREATE_DECODE_EXTRA_INFO;
396     if(!(*flags & Uri_CREATE_NO_CRACK_UNKNOWN_SCHEMES))
397         *flags |= Uri_CREATE_CRACK_UNKNOWN_SCHEMES;
398     if(!(*flags & Uri_CREATE_NO_PRE_PROCESS_HTML_URI))
399         *flags |= Uri_CREATE_PRE_PROCESS_HTML_URI;
400     if(!(*flags & Uri_CREATE_IE_SETTINGS))
401         *flags |= Uri_CREATE_NO_IE_SETTINGS;
402 }
403
404 /* Determines if the URI is hierarchical using the information already parsed into
405  * data and using the current location of parsing in the URI string.
406  *
407  * Windows considers a URI hierarchical if one of the following is true:
408  *  A.) It's a wildcard scheme.
409  *  B.) It's an implicit file scheme.
410  *  C.) It's a known hierarchical scheme and it has two '\\' after the scheme name.
411  *      (the '\\' will be converted into "//" during canonicalization).
412  *  D.) It's not a relative URI and "//" appears after the scheme name.
413  */
414 static inline BOOL is_hierarchical_uri(const WCHAR **ptr, const parse_data *data) {
415     const WCHAR *start = *ptr;
416
417     if(data->scheme_type == URL_SCHEME_WILDCARD)
418         return TRUE;
419     else if(data->scheme_type == URL_SCHEME_FILE && data->has_implicit_scheme)
420         return TRUE;
421     else if(is_hierarchical_scheme(data->scheme_type) && (*ptr)[0] == '\\' && (*ptr)[1] == '\\') {
422         *ptr += 2;
423         return TRUE;
424     } else if(!data->is_relative && check_hierarchical(ptr))
425         return TRUE;
426
427     *ptr = start;
428     return FALSE;
429 }
430
431 /* Checks if the two Uri's are logically equivalent. It's a simple
432  * comparison, since they are both of type Uri, and it can access
433  * the properties of each Uri directly without the need to go
434  * through the "IUri_Get*" interface calls.
435  */
436 static BOOL are_equal_simple(const Uri *a, const Uri *b) {
437     if(a->scheme_type == b->scheme_type) {
438         const BOOL known_scheme = a->scheme_type != URL_SCHEME_UNKNOWN;
439         const BOOL are_hierarchical =
440                 (a->authority_start > -1 && b->authority_start > -1);
441
442         if(a->scheme_type == URL_SCHEME_FILE) {
443             if(a->canon_len == b->canon_len)
444                 return !StrCmpIW(a->canon_uri, b->canon_uri);
445         }
446
447         /* Only compare the scheme names (if any) if their unknown scheme types. */
448         if(!known_scheme) {
449             if((a->scheme_start > -1 && b->scheme_start > -1) &&
450                (a->scheme_len == b->scheme_len)) {
451                 /* Make sure the schemes are the same. */
452                 if(StrCmpNW(a->canon_uri+a->scheme_start, b->canon_uri+b->scheme_start, a->scheme_len))
453                     return FALSE;
454             } else if(a->scheme_len != b->scheme_len)
455                 /* One of the Uri's has a scheme name, while the other doesn't. */
456                 return FALSE;
457         }
458
459         /* If they have a userinfo component, perform case sensitive compare. */
460         if((a->userinfo_start > -1 && b->userinfo_start > -1) &&
461            (a->userinfo_len == b->userinfo_len)) {
462             if(StrCmpNW(a->canon_uri+a->userinfo_start, b->canon_uri+b->userinfo_start, a->userinfo_len))
463                 return FALSE;
464         } else if(a->userinfo_len != b->userinfo_len)
465             /* One of the Uri's had a userinfo, while the other one doesn't. */
466             return FALSE;
467
468         /* Check if they have a host name. */
469         if((a->host_start > -1 && b->host_start > -1) &&
470            (a->host_len == b->host_len)) {
471             /* Perform a case insensitive compare if they are a known scheme type. */
472             if(known_scheme) {
473                 if(StrCmpNIW(a->canon_uri+a->host_start, b->canon_uri+b->host_start, a->host_len))
474                     return FALSE;
475             } else if(StrCmpNW(a->canon_uri+a->host_start, b->canon_uri+b->host_start, a->host_len))
476                 return FALSE;
477         } else if(a->host_len != b->host_len)
478             /* One of the Uri's had a host, while the other one didn't. */
479             return FALSE;
480
481         if(a->has_port && b->has_port) {
482             if(a->port != b->port)
483                 return FALSE;
484         } else if(a->has_port || b->has_port)
485             /* One had a port, while the other one didn't. */
486             return FALSE;
487
488         /* Windows is weird with how it handles paths. For example
489          * One URI could be "http://google.com" (after canonicalization)
490          * and one could be "http://google.com/" and the IsEqual function
491          * would still evaluate to TRUE, but, only if they are both hierarchical
492          * URIs.
493          */
494         if((a->path_start > -1 && b->path_start > -1) &&
495            (a->path_len == b->path_len)) {
496             if(StrCmpNW(a->canon_uri+a->path_start, b->canon_uri+b->path_start, a->path_len))
497                 return FALSE;
498         } else if(are_hierarchical && a->path_len == -1 && b->path_len == 0) {
499             if(*(a->canon_uri+a->path_start) != '/')
500                 return FALSE;
501         } else if(are_hierarchical && b->path_len == 1 && a->path_len == 0) {
502             if(*(b->canon_uri+b->path_start) != '/')
503                 return FALSE;
504         } else if(a->path_len != b->path_len)
505             return FALSE;
506
507         /* Compare the query strings of the two URIs. */
508         if((a->query_start > -1 && b->query_start > -1) &&
509            (a->query_len == b->query_len)) {
510             if(StrCmpNW(a->canon_uri+a->query_start, b->canon_uri+b->query_start, a->query_len))
511                 return FALSE;
512         } else if(a->query_len != b->query_len)
513             return FALSE;
514
515         if((a->fragment_start > -1 && b->fragment_start > -1) &&
516            (a->fragment_len == b->fragment_len)) {
517             if(StrCmpNW(a->canon_uri+a->fragment_start, b->canon_uri+b->fragment_start, a->fragment_len))
518                 return FALSE;
519         } else if(a->fragment_len != b->fragment_len)
520             return FALSE;
521
522         /* If we get here, the two URIs are equivalent. */
523         return TRUE;
524     }
525
526     return FALSE;
527 }
528
529 /* Computes the size of the given IPv6 address.
530  * Each h16 component is 16 bits. If there is an IPv4 address, it's
531  * 32 bits. If there's an elision it can be 16 to 128 bits, depending
532  * on the number of other components.
533  *
534  * Modeled after google-url's CheckIPv6ComponentsSize function
535  */
536 static void compute_ipv6_comps_size(ipv6_address *address) {
537     address->components_size = address->h16_count * 2;
538
539     if(address->ipv4)
540         /* IPv4 address is 4 bytes. */
541         address->components_size += 4;
542
543     if(address->elision) {
544         /* An elision can be anywhere from 2 bytes up to 16 bytes.
545          * Its size depends on the size of the h16 and IPv4 components.
546          */
547         address->elision_size = 16 - address->components_size;
548         if(address->elision_size < 2)
549             address->elision_size = 2;
550     } else
551         address->elision_size = 0;
552 }
553
554 /* Taken from dlls/jscript/lex.c */
555 static int hex_to_int(WCHAR val) {
556     if(val >= '0' && val <= '9')
557         return val - '0';
558     else if(val >= 'a' && val <= 'f')
559         return val - 'a' + 10;
560     else if(val >= 'A' && val <= 'F')
561         return val - 'A' + 10;
562
563     return -1;
564 }
565
566 /* Helper function for converting a percent encoded string
567  * representation of a WCHAR value into its actual WCHAR value. If
568  * the two characters following the '%' aren't valid hex values then
569  * this function returns the NULL character.
570  *
571  * E.g.
572  *  "%2E" will result in '.' being returned by this function.
573  */
574 static WCHAR decode_pct_val(const WCHAR *ptr) {
575     WCHAR ret = '\0';
576
577     if(*ptr == '%' && is_hexdigit(*(ptr + 1)) && is_hexdigit(*(ptr + 2))) {
578         INT a = hex_to_int(*(ptr + 1));
579         INT b = hex_to_int(*(ptr + 2));
580
581         ret = a << 4;
582         ret += b;
583     }
584
585     return ret;
586 }
587
588 /* Helper function for percent encoding a given character
589  * and storing the encoded value into a given buffer (dest).
590  *
591  * It's up to the calling function to ensure that there is
592  * at least enough space in 'dest' for the percent encoded
593  * value to be stored (so dest + 3 spaces available).
594  */
595 static inline void pct_encode_val(WCHAR val, WCHAR *dest) {
596     dest[0] = '%';
597     dest[1] = hexDigits[(val >> 4) & 0xf];
598     dest[2] = hexDigits[val & 0xf];
599 }
600
601 /* Attempts to parse the domain name from the host.
602  *
603  * This function also includes the Top-level Domain (TLD) name
604  * of the host when it tries to find the domain name. If it finds
605  * a valid domain name it will assign 'domain_start' the offset
606  * into 'host' where the domain name starts.
607  *
608  * It's implied that if there is a domain name its range is:
609  * [host+domain_start, host+host_len).
610  */
611 void find_domain_name(const WCHAR *host, DWORD host_len,
612                              INT *domain_start) {
613     const WCHAR *last_tld, *sec_last_tld, *end;
614
615     end = host+host_len-1;
616
617     *domain_start = -1;
618
619     /* There has to be at least enough room for a '.' followed by a
620      * 3-character TLD for a domain to even exist in the host name.
621      */
622     if(host_len < 4)
623         return;
624
625     last_tld = memrchrW(host, '.', host_len);
626     if(!last_tld)
627         /* http://hostname -> has no domain name. */
628         return;
629
630     sec_last_tld = memrchrW(host, '.', last_tld-host);
631     if(!sec_last_tld) {
632         /* If the '.' is at the beginning of the host there
633          * has to be at least 3 characters in the TLD for it
634          * to be valid.
635          *  Ex: .com -> .com as the domain name.
636          *      .co  -> has no domain name.
637          */
638         if(last_tld-host == 0) {
639             if(end-(last_tld-1) < 3)
640                 return;
641         } else if(last_tld-host == 3) {
642             DWORD i;
643
644             /* If there are three characters in front of last_tld and
645              * they are on the list of recognized TLDs, then this
646              * host doesn't have a domain (since the host only contains
647              * a TLD name.
648              *  Ex: edu.uk -> has no domain name.
649              *      foo.uk -> foo.uk as the domain name.
650              */
651             for(i = 0; i < sizeof(recognized_tlds)/sizeof(recognized_tlds[0]); ++i) {
652                 if(!StrCmpNIW(host, recognized_tlds[i].tld_name, 3))
653                     return;
654             }
655         } else if(last_tld-host < 3)
656             /* Anything less than 3 characters is considered part
657              * of the TLD name.
658              *  Ex: ak.uk -> Has no domain name.
659              */
660             return;
661
662         /* Otherwise the domain name is the whole host name. */
663         *domain_start = 0;
664     } else if(end+1-last_tld > 3) {
665         /* If the last_tld has more than 3 characters, then it's automatically
666          * considered the TLD of the domain name.
667          *  Ex: www.winehq.org.uk.test -> uk.test as the domain name.
668          */
669         *domain_start = (sec_last_tld+1)-host;
670     } else if(last_tld - (sec_last_tld+1) < 4) {
671         DWORD i;
672         /* If the sec_last_tld is 3 characters long it HAS to be on the list of
673          * recognized to still be considered part of the TLD name, otherwise
674          * its considered the domain name.
675          *  Ex: www.google.com.uk -> google.com.uk as the domain name.
676          *      www.google.foo.uk -> foo.uk as the domain name.
677          */
678         if(last_tld - (sec_last_tld+1) == 3) {
679             for(i = 0; i < sizeof(recognized_tlds)/sizeof(recognized_tlds[0]); ++i) {
680                 if(!StrCmpNIW(sec_last_tld+1, recognized_tlds[i].tld_name, 3)) {
681                     const WCHAR *domain = memrchrW(host, '.', sec_last_tld-host);
682
683                     if(!domain)
684                         *domain_start = 0;
685                     else
686                         *domain_start = (domain+1) - host;
687                     TRACE("Found domain name %s\n", debugstr_wn(host+*domain_start,
688                                                         (host+host_len)-(host+*domain_start)));
689                     return;
690                 }
691             }
692
693             *domain_start = (sec_last_tld+1)-host;
694         } else {
695             /* Since the sec_last_tld is less than 3 characters it's considered
696              * part of the TLD.
697              *  Ex: www.google.fo.uk -> google.fo.uk as the domain name.
698              */
699             const WCHAR *domain = memrchrW(host, '.', sec_last_tld-host);
700
701             if(!domain)
702                 *domain_start = 0;
703             else
704                 *domain_start = (domain+1) - host;
705         }
706     } else {
707         /* The second to last TLD has more than 3 characters making it
708          * the domain name.
709          *  Ex: www.google.test.us -> test.us as the domain name.
710          */
711         *domain_start = (sec_last_tld+1)-host;
712     }
713
714     TRACE("Found domain name %s\n", debugstr_wn(host+*domain_start,
715                                         (host+host_len)-(host+*domain_start)));
716 }
717
718 /* Removes the dot segments from a hierarchical URIs path component. This
719  * function performs the removal in place.
720  *
721  * This function returns the new length of the path string.
722  */
723 static DWORD remove_dot_segments(WCHAR *path, DWORD path_len) {
724     WCHAR *out = path;
725     const WCHAR *in = out;
726     const WCHAR *end = out + path_len;
727     DWORD len;
728
729     while(in < end) {
730         /* Move the first path segment in the input buffer to the end of
731          * the output buffer, and any subsequent characters up to, including
732          * the next "/" character (if any) or the end of the input buffer.
733          */
734         while(in < end && !is_slash(*in))
735             *out++ = *in++;
736         if(in == end)
737             break;
738         *out++ = *in++;
739
740         while(in < end) {
741             if(*in != '.')
742                 break;
743
744             /* Handle ending "/." */
745             if(in + 1 == end) {
746                 ++in;
747                 break;
748             }
749
750             /* Handle "/./" */
751             if(is_slash(in[1])) {
752                 in += 2;
753                 continue;
754             }
755
756             /* If we don't have "/../" or ending "/.." */
757             if(in[1] != '.' || (in + 2 != end && !is_slash(in[2])))
758                 break;
759
760             /* Find the slash preceding out pointer and move out pointer to it */
761             if(out > path+1 && is_slash(*--out))
762                 --out;
763             while(out > path && !is_slash(*(--out)));
764             if(is_slash(*out))
765                 ++out;
766             in += 2;
767             if(in != end)
768                 ++in;
769         }
770     }
771
772     len = out - path;
773     TRACE("(%p %d): Path after dot segments removed %s len=%d\n", path, path_len,
774         debugstr_wn(path, len), len);
775     return len;
776 }
777
778 /* Attempts to find the file extension in a given path. */
779 static INT find_file_extension(const WCHAR *path, DWORD path_len) {
780     const WCHAR *end;
781
782     for(end = path+path_len-1; end >= path && *end != '/' && *end != '\\'; --end) {
783         if(*end == '.')
784             return end-path;
785     }
786
787     return -1;
788 }
789
790 /* Computes the location where the elision should occur in the IPv6
791  * address using the numerical values of each component stored in
792  * 'values'. If the address shouldn't contain an elision then 'index'
793  * is assigned -1 as its value. Otherwise 'index' will contain the
794  * starting index (into values) where the elision should be, and 'count'
795  * will contain the number of cells the elision covers.
796  *
797  * NOTES:
798  *  Windows will expand an elision if the elision only represents one h16
799  *  component of the address.
800  *
801  *  Ex: [1::2:3:4:5:6:7] -> [1:0:2:3:4:5:6:7]
802  *
803  *  If the IPv6 address contains an IPv4 address, the IPv4 address is also
804  *  considered for being included as part of an elision if all its components
805  *  are zeros.
806  *
807  *  Ex: [1:2:3:4:5:6:0.0.0.0] -> [1:2:3:4:5:6::]
808  */
809 static void compute_elision_location(const ipv6_address *address, const USHORT values[8],
810                                      INT *index, DWORD *count) {
811     DWORD i, max_len, cur_len;
812     INT max_index, cur_index;
813
814     max_len = cur_len = 0;
815     max_index = cur_index = -1;
816     for(i = 0; i < 8; ++i) {
817         BOOL check_ipv4 = (address->ipv4 && i == 6);
818         BOOL is_end = (check_ipv4 || i == 7);
819
820         if(check_ipv4) {
821             /* Check if the IPv4 address contains only zeros. */
822             if(values[i] == 0 && values[i+1] == 0) {
823                 if(cur_index == -1)
824                     cur_index = i;
825
826                 cur_len += 2;
827                 ++i;
828             }
829         } else if(values[i] == 0) {
830             if(cur_index == -1)
831                 cur_index = i;
832
833             ++cur_len;
834         }
835
836         if(is_end || values[i] != 0) {
837             /* We only consider it for an elision if it's
838              * more than 1 component long.
839              */
840             if(cur_len > 1 && cur_len > max_len) {
841                 /* Found the new elision location. */
842                 max_len = cur_len;
843                 max_index = cur_index;
844             }
845
846             /* Reset the current range for the next range of zeros. */
847             cur_index = -1;
848             cur_len = 0;
849         }
850     }
851
852     *index = max_index;
853     *count = max_len;
854 }
855
856 /* Removes all the leading and trailing white spaces or
857  * control characters from the URI and removes all control
858  * characters inside of the URI string.
859  */
860 static BSTR pre_process_uri(LPCWSTR uri) {
861     const WCHAR *start, *end, *ptr;
862     WCHAR *ptr2;
863     DWORD len;
864     BSTR ret;
865
866     start = uri;
867     /* Skip leading controls and whitespace. */
868     while(*start && (iscntrlW(*start) || isspaceW(*start))) ++start;
869
870     /* URI consisted only of control/whitespace. */
871     if(!*start)
872         return SysAllocStringLen(NULL, 0);
873
874     end = start + strlenW(start);
875     while(--end > start && (iscntrlW(*end) || isspaceW(*end)));
876
877     len = ++end - start;
878     for(ptr = start; ptr < end; ptr++) {
879         if(iscntrlW(*ptr))
880             len--;
881     }
882
883     ret = SysAllocStringLen(NULL, len);
884     if(!ret)
885         return NULL;
886
887     for(ptr = start, ptr2=ret; ptr < end; ptr++) {
888         if(!iscntrlW(*ptr))
889             *ptr2++ = *ptr;
890     }
891
892     return ret;
893 }
894
895 /* Converts the specified IPv4 address into an uint value.
896  *
897  * This function assumes that the IPv4 address has already been validated.
898  */
899 static UINT ipv4toui(const WCHAR *ip, DWORD len) {
900     UINT ret = 0;
901     DWORD comp_value = 0;
902     const WCHAR *ptr;
903
904     for(ptr = ip; ptr < ip+len; ++ptr) {
905         if(*ptr == '.') {
906             ret <<= 8;
907             ret += comp_value;
908             comp_value = 0;
909         } else
910             comp_value = comp_value*10 + (*ptr-'0');
911     }
912
913     ret <<= 8;
914     ret += comp_value;
915
916     return ret;
917 }
918
919 /* Converts an IPv4 address in numerical form into its fully qualified
920  * string form. This function returns the number of characters written
921  * to 'dest'. If 'dest' is NULL this function will return the number of
922  * characters that would have been written.
923  *
924  * It's up to the caller to ensure there's enough space in 'dest' for the
925  * address.
926  */
927 static DWORD ui2ipv4(WCHAR *dest, UINT address) {
928     static const WCHAR formatW[] =
929         {'%','u','.','%','u','.','%','u','.','%','u',0};
930     DWORD ret = 0;
931     UCHAR digits[4];
932
933     digits[0] = (address >> 24) & 0xff;
934     digits[1] = (address >> 16) & 0xff;
935     digits[2] = (address >> 8) & 0xff;
936     digits[3] = address & 0xff;
937
938     if(!dest) {
939         WCHAR tmp[16];
940         ret = sprintfW(tmp, formatW, digits[0], digits[1], digits[2], digits[3]);
941     } else
942         ret = sprintfW(dest, formatW, digits[0], digits[1], digits[2], digits[3]);
943
944     return ret;
945 }
946
947 static DWORD ui2str(WCHAR *dest, UINT value) {
948     static const WCHAR formatW[] = {'%','u',0};
949     DWORD ret = 0;
950
951     if(!dest) {
952         WCHAR tmp[11];
953         ret = sprintfW(tmp, formatW, value);
954     } else
955         ret = sprintfW(dest, formatW, value);
956
957     return ret;
958 }
959
960 /* Converts a h16 component (from an IPv6 address) into its
961  * numerical value.
962  *
963  * This function assumes that the h16 component has already been validated.
964  */
965 static USHORT h16tous(h16 component) {
966     DWORD i;
967     USHORT ret = 0;
968
969     for(i = 0; i < component.len; ++i) {
970         ret <<= 4;
971         ret += hex_to_int(component.str[i]);
972     }
973
974     return ret;
975 }
976
977 /* Converts an IPv6 address into its 128 bits (16 bytes) numerical value.
978  *
979  * This function assumes that the ipv6_address has already been validated.
980  */
981 static BOOL ipv6_to_number(const ipv6_address *address, USHORT number[8]) {
982     DWORD i, cur_component = 0;
983     BOOL already_passed_elision = FALSE;
984
985     for(i = 0; i < address->h16_count; ++i) {
986         if(address->elision) {
987             if(address->components[i].str > address->elision && !already_passed_elision) {
988                 /* Means we just passed the elision and need to add its values to
989                  * 'number' before we do anything else.
990                  */
991                 DWORD j = 0;
992                 for(j = 0; j < address->elision_size; j+=2)
993                     number[cur_component++] = 0;
994
995                 already_passed_elision = TRUE;
996             }
997         }
998
999         number[cur_component++] = h16tous(address->components[i]);
1000     }
1001
1002     /* Case when the elision appears after the h16 components. */
1003     if(!already_passed_elision && address->elision) {
1004         for(i = 0; i < address->elision_size; i+=2)
1005             number[cur_component++] = 0;
1006     }
1007
1008     if(address->ipv4) {
1009         UINT value = ipv4toui(address->ipv4, address->ipv4_len);
1010
1011         if(cur_component != 6) {
1012             ERR("(%p %p): Failed sanity check with %d\n", address, number, cur_component);
1013             return FALSE;
1014         }
1015
1016         number[cur_component++] = (value >> 16) & 0xffff;
1017         number[cur_component] = value & 0xffff;
1018     }
1019
1020     return TRUE;
1021 }
1022
1023 /* Checks if the characters pointed to by 'ptr' are
1024  * a percent encoded data octet.
1025  *
1026  * pct-encoded = "%" HEXDIG HEXDIG
1027  */
1028 static BOOL check_pct_encoded(const WCHAR **ptr) {
1029     const WCHAR *start = *ptr;
1030
1031     if(**ptr != '%')
1032         return FALSE;
1033
1034     ++(*ptr);
1035     if(!is_hexdigit(**ptr)) {
1036         *ptr = start;
1037         return FALSE;
1038     }
1039
1040     ++(*ptr);
1041     if(!is_hexdigit(**ptr)) {
1042         *ptr = start;
1043         return FALSE;
1044     }
1045
1046     ++(*ptr);
1047     return TRUE;
1048 }
1049
1050 /* dec-octet   = DIGIT                 ; 0-9
1051  *             / %x31-39 DIGIT         ; 10-99
1052  *             / "1" 2DIGIT            ; 100-199
1053  *             / "2" %x30-34 DIGIT     ; 200-249
1054  *             / "25" %x30-35          ; 250-255
1055  */
1056 static BOOL check_dec_octet(const WCHAR **ptr) {
1057     const WCHAR *c1, *c2, *c3;
1058
1059     c1 = *ptr;
1060     /* A dec-octet must be at least 1 digit long. */
1061     if(*c1 < '0' || *c1 > '9')
1062         return FALSE;
1063
1064     ++(*ptr);
1065
1066     c2 = *ptr;
1067     /* Since the 1-digit requirement was met, it doesn't
1068      * matter if this is a DIGIT value, it's considered a
1069      * dec-octet.
1070      */
1071     if(*c2 < '0' || *c2 > '9')
1072         return TRUE;
1073
1074     ++(*ptr);
1075
1076     c3 = *ptr;
1077     /* Same explanation as above. */
1078     if(*c3 < '0' || *c3 > '9')
1079         return TRUE;
1080
1081     /* Anything > 255 isn't a valid IP dec-octet. */
1082     if(*c1 >= '2' && *c2 >= '5' && *c3 >= '5') {
1083         *ptr = c1;
1084         return FALSE;
1085     }
1086
1087     ++(*ptr);
1088     return TRUE;
1089 }
1090
1091 /* Checks if there is an implicit IPv4 address in the host component of the URI.
1092  * The max value of an implicit IPv4 address is UINT_MAX.
1093  *
1094  *  Ex:
1095  *      "234567" would be considered an implicit IPv4 address.
1096  */
1097 static BOOL check_implicit_ipv4(const WCHAR **ptr, UINT *val) {
1098     const WCHAR *start = *ptr;
1099     ULONGLONG ret = 0;
1100     *val = 0;
1101
1102     while(is_num(**ptr)) {
1103         ret = ret*10 + (**ptr - '0');
1104
1105         if(ret > UINT_MAX) {
1106             *ptr = start;
1107             return FALSE;
1108         }
1109         ++(*ptr);
1110     }
1111
1112     if(*ptr == start)
1113         return FALSE;
1114
1115     *val = ret;
1116     return TRUE;
1117 }
1118
1119 /* Checks if the string contains an IPv4 address.
1120  *
1121  * This function has a strict mode or a non-strict mode of operation
1122  * When 'strict' is set to FALSE this function will return TRUE if
1123  * the string contains at least 'dec-octet "." dec-octet' since partial
1124  * IPv4 addresses will be normalized out into full IPv4 addresses. When
1125  * 'strict' is set this function expects there to be a full IPv4 address.
1126  *
1127  * IPv4address = dec-octet "." dec-octet "." dec-octet "." dec-octet
1128  */
1129 static BOOL check_ipv4address(const WCHAR **ptr, BOOL strict) {
1130     const WCHAR *start = *ptr;
1131
1132     if(!check_dec_octet(ptr)) {
1133         *ptr = start;
1134         return FALSE;
1135     }
1136
1137     if(**ptr != '.') {
1138         *ptr = start;
1139         return FALSE;
1140     }
1141
1142     ++(*ptr);
1143     if(!check_dec_octet(ptr)) {
1144         *ptr = start;
1145         return FALSE;
1146     }
1147
1148     if(**ptr != '.') {
1149         if(strict) {
1150             *ptr = start;
1151             return FALSE;
1152         } else
1153             return TRUE;
1154     }
1155
1156     ++(*ptr);
1157     if(!check_dec_octet(ptr)) {
1158         *ptr = start;
1159         return FALSE;
1160     }
1161
1162     if(**ptr != '.') {
1163         if(strict) {
1164             *ptr = start;
1165             return FALSE;
1166         } else
1167             return TRUE;
1168     }
1169
1170     ++(*ptr);
1171     if(!check_dec_octet(ptr)) {
1172         *ptr = start;
1173         return FALSE;
1174     }
1175
1176     /* Found a four digit ip address. */
1177     return TRUE;
1178 }
1179 /* Tries to parse the scheme name of the URI.
1180  *
1181  * scheme = ALPHA *(ALPHA | NUM | '+' | '-' | '.') as defined by RFC 3896.
1182  * NOTE: Windows accepts a number as the first character of a scheme.
1183  */
1184 static BOOL parse_scheme_name(const WCHAR **ptr, parse_data *data, DWORD extras) {
1185     const WCHAR *start = *ptr;
1186
1187     data->scheme = NULL;
1188     data->scheme_len = 0;
1189
1190     while(**ptr) {
1191         if(**ptr == '*' && *ptr == start) {
1192             /* Might have found a wildcard scheme. If it is the next
1193              * char has to be a ':' for it to be a valid URI
1194              */
1195             ++(*ptr);
1196             break;
1197         } else if(!is_num(**ptr) && !is_alpha(**ptr) && **ptr != '+' &&
1198            **ptr != '-' && **ptr != '.')
1199             break;
1200
1201         (*ptr)++;
1202     }
1203
1204     if(*ptr == start)
1205         return FALSE;
1206
1207     /* Schemes must end with a ':' */
1208     if(**ptr != ':' && !((extras & ALLOW_NULL_TERM_SCHEME) && !**ptr)) {
1209         *ptr = start;
1210         return FALSE;
1211     }
1212
1213     data->scheme = start;
1214     data->scheme_len = *ptr - start;
1215
1216     ++(*ptr);
1217     return TRUE;
1218 }
1219
1220 /* Tries to deduce the corresponding URL_SCHEME for the given URI. Stores
1221  * the deduced URL_SCHEME in data->scheme_type.
1222  */
1223 static BOOL parse_scheme_type(parse_data *data) {
1224     /* If there's scheme data then see if it's a recognized scheme. */
1225     if(data->scheme && data->scheme_len) {
1226         DWORD i;
1227
1228         for(i = 0; i < sizeof(recognized_schemes)/sizeof(recognized_schemes[0]); ++i) {
1229             if(lstrlenW(recognized_schemes[i].scheme_name) == data->scheme_len) {
1230                 /* Has to be a case insensitive compare. */
1231                 if(!StrCmpNIW(recognized_schemes[i].scheme_name, data->scheme, data->scheme_len)) {
1232                     data->scheme_type = recognized_schemes[i].scheme;
1233                     return TRUE;
1234                 }
1235             }
1236         }
1237
1238         /* If we get here it means it's not a recognized scheme. */
1239         data->scheme_type = URL_SCHEME_UNKNOWN;
1240         return TRUE;
1241     } else if(data->is_relative) {
1242         /* Relative URI's have no scheme. */
1243         data->scheme_type = URL_SCHEME_UNKNOWN;
1244         return TRUE;
1245     } else {
1246         /* Should never reach here! what happened... */
1247         FIXME("(%p): Unable to determine scheme type for URI %s\n", data, debugstr_w(data->uri));
1248         return FALSE;
1249     }
1250 }
1251
1252 /* Tries to parse (or deduce) the scheme_name of a URI. If it can't
1253  * parse a scheme from the URI it will try to deduce the scheme_name and scheme_type
1254  * using the flags specified in 'flags' (if any). Flags that affect how this function
1255  * operates are the Uri_CREATE_ALLOW_* flags.
1256  *
1257  * All parsed/deduced information will be stored in 'data' when the function returns.
1258  *
1259  * Returns TRUE if it was able to successfully parse the information.
1260  */
1261 static BOOL parse_scheme(const WCHAR **ptr, parse_data *data, DWORD flags, DWORD extras) {
1262     static const WCHAR fileW[] = {'f','i','l','e',0};
1263     static const WCHAR wildcardW[] = {'*',0};
1264
1265     /* First check to see if the uri could implicitly be a file path. */
1266     if(is_implicit_file_path(*ptr)) {
1267         if(flags & Uri_CREATE_ALLOW_IMPLICIT_FILE_SCHEME) {
1268             data->scheme = fileW;
1269             data->scheme_len = lstrlenW(fileW);
1270             data->has_implicit_scheme = TRUE;
1271
1272             TRACE("(%p %p %x): URI is an implicit file path.\n", ptr, data, flags);
1273         } else {
1274             /* Windows does not consider anything that can implicitly be a file
1275              * path to be a valid URI if the ALLOW_IMPLICIT_FILE_SCHEME flag is not set...
1276              */
1277             TRACE("(%p %p %x): URI is implicitly a file path, but, the ALLOW_IMPLICIT_FILE_SCHEME flag wasn't set.\n",
1278                     ptr, data, flags);
1279             return FALSE;
1280         }
1281     } else if(!parse_scheme_name(ptr, data, extras)) {
1282         /* No scheme was found, this means it could be:
1283          *      a) an implicit Wildcard scheme
1284          *      b) a relative URI
1285          *      c) an invalid URI.
1286          */
1287         if(flags & Uri_CREATE_ALLOW_IMPLICIT_WILDCARD_SCHEME) {
1288             data->scheme = wildcardW;
1289             data->scheme_len = lstrlenW(wildcardW);
1290             data->has_implicit_scheme = TRUE;
1291
1292             TRACE("(%p %p %x): URI is an implicit wildcard scheme.\n", ptr, data, flags);
1293         } else if (flags & Uri_CREATE_ALLOW_RELATIVE) {
1294             data->is_relative = TRUE;
1295             TRACE("(%p %p %x): URI is relative.\n", ptr, data, flags);
1296         } else {
1297             TRACE("(%p %p %x): Malformed URI found. Unable to deduce scheme name.\n", ptr, data, flags);
1298             return FALSE;
1299         }
1300     }
1301
1302     if(!data->is_relative)
1303         TRACE("(%p %p %x): Found scheme=%s scheme_len=%d\n", ptr, data, flags,
1304                 debugstr_wn(data->scheme, data->scheme_len), data->scheme_len);
1305
1306     if(!parse_scheme_type(data))
1307         return FALSE;
1308
1309     TRACE("(%p %p %x): Assigned %d as the URL_SCHEME.\n", ptr, data, flags, data->scheme_type);
1310     return TRUE;
1311 }
1312
1313 static BOOL parse_username(const WCHAR **ptr, parse_data *data, DWORD flags, DWORD extras) {
1314     data->username = *ptr;
1315
1316     while(**ptr != ':' && **ptr != '@') {
1317         if(**ptr == '%') {
1318             if(!check_pct_encoded(ptr)) {
1319                 if(data->scheme_type != URL_SCHEME_UNKNOWN) {
1320                     *ptr = data->username;
1321                     data->username = NULL;
1322                     return FALSE;
1323                 }
1324             } else
1325                 continue;
1326         } else if(extras & ALLOW_NULL_TERM_USER_NAME && !**ptr)
1327             break;
1328         else if(is_auth_delim(**ptr, data->scheme_type != URL_SCHEME_UNKNOWN)) {
1329             *ptr = data->username;
1330             data->username = NULL;
1331             return FALSE;
1332         }
1333
1334         ++(*ptr);
1335     }
1336
1337     data->username_len = *ptr - data->username;
1338     return TRUE;
1339 }
1340
1341 static BOOL parse_password(const WCHAR **ptr, parse_data *data, DWORD flags, DWORD extras) {
1342     data->password = *ptr;
1343
1344     while(**ptr != '@') {
1345         if(**ptr == '%') {
1346             if(!check_pct_encoded(ptr)) {
1347                 if(data->scheme_type != URL_SCHEME_UNKNOWN) {
1348                     *ptr = data->password;
1349                     data->password = NULL;
1350                     return FALSE;
1351                 }
1352             } else
1353                 continue;
1354         } else if(extras & ALLOW_NULL_TERM_PASSWORD && !**ptr)
1355             break;
1356         else if(is_auth_delim(**ptr, data->scheme_type != URL_SCHEME_UNKNOWN)) {
1357             *ptr = data->password;
1358             data->password = NULL;
1359             return FALSE;
1360         }
1361
1362         ++(*ptr);
1363     }
1364
1365     data->password_len = *ptr - data->password;
1366     return TRUE;
1367 }
1368
1369 /* Parses the userinfo part of the URI (if it exists). The userinfo field of
1370  * a URI can consist of "username:password@", or just "username@".
1371  *
1372  * RFC def:
1373  * userinfo    = *( unreserved / pct-encoded / sub-delims / ":" )
1374  *
1375  * NOTES:
1376  *  1)  If there is more than one ':' in the userinfo part of the URI Windows
1377  *      uses the first occurrence of ':' to delimit the username and password
1378  *      components.
1379  *
1380  *      ex:
1381  *          ftp://user:pass:word@winehq.org
1382  *
1383  *      would yield "user" as the username and "pass:word" as the password.
1384  *
1385  *  2)  Windows allows any character to appear in the "userinfo" part of
1386  *      a URI, as long as it's not an authority delimiter character set.
1387  */
1388 static void parse_userinfo(const WCHAR **ptr, parse_data *data, DWORD flags) {
1389     const WCHAR *start = *ptr;
1390
1391     if(!parse_username(ptr, data, flags, 0)) {
1392         TRACE("(%p %p %x): URI contained no userinfo.\n", ptr, data, flags);
1393         return;
1394     }
1395
1396     if(**ptr == ':') {
1397         ++(*ptr);
1398         if(!parse_password(ptr, data, flags, 0)) {
1399             *ptr = start;
1400             data->username = NULL;
1401             data->username_len = 0;
1402             TRACE("(%p %p %x): URI contained no userinfo.\n", ptr, data, flags);
1403             return;
1404         }
1405     }
1406
1407     if(**ptr != '@') {
1408         *ptr = start;
1409         data->username = NULL;
1410         data->username_len = 0;
1411         data->password = NULL;
1412         data->password_len = 0;
1413
1414         TRACE("(%p %p %x): URI contained no userinfo.\n", ptr, data, flags);
1415         return;
1416     }
1417
1418     if(data->username)
1419         TRACE("(%p %p %x): Found username %s len=%d.\n", ptr, data, flags,
1420             debugstr_wn(data->username, data->username_len), data->username_len);
1421
1422     if(data->password)
1423         TRACE("(%p %p %x): Found password %s len=%d.\n", ptr, data, flags,
1424             debugstr_wn(data->password, data->password_len), data->password_len);
1425
1426     ++(*ptr);
1427 }
1428
1429 /* Attempts to parse a port from the URI.
1430  *
1431  * NOTES:
1432  *  Windows seems to have a cap on what the maximum value
1433  *  for a port can be. The max value is USHORT_MAX.
1434  *
1435  * port = *DIGIT
1436  */
1437 static BOOL parse_port(const WCHAR **ptr, parse_data *data, DWORD flags) {
1438     UINT port = 0;
1439     data->port = *ptr;
1440
1441     while(!is_auth_delim(**ptr, data->scheme_type != URL_SCHEME_UNKNOWN)) {
1442         if(!is_num(**ptr)) {
1443             *ptr = data->port;
1444             data->port = NULL;
1445             return FALSE;
1446         }
1447
1448         port = port*10 + (**ptr-'0');
1449
1450         if(port > USHORT_MAX) {
1451             *ptr = data->port;
1452             data->port = NULL;
1453             return FALSE;
1454         }
1455
1456         ++(*ptr);
1457     }
1458
1459     data->has_port = TRUE;
1460     data->port_value = port;
1461     data->port_len = *ptr - data->port;
1462
1463     TRACE("(%p %p %x): Found port %s len=%d value=%u\n", ptr, data, flags,
1464         debugstr_wn(data->port, data->port_len), data->port_len, data->port_value);
1465     return TRUE;
1466 }
1467
1468 /* Attempts to parse a IPv4 address from the URI.
1469  *
1470  * NOTES:
1471  *  Windows normalizes IPv4 addresses, This means there are three
1472  *  possibilities for the URI to contain an IPv4 address.
1473  *      1)  A well formed address (ex. 192.2.2.2).
1474  *      2)  A partially formed address. For example "192.0" would
1475  *          normalize to "192.0.0.0" during canonicalization.
1476  *      3)  An implicit IPv4 address. For example "256" would
1477  *          normalize to "0.0.1.0" during canonicalization. Also
1478  *          note that the maximum value for an implicit IP address
1479  *          is UINT_MAX, if the value in the URI exceeds this then
1480  *          it is not considered an IPv4 address.
1481  */
1482 static BOOL parse_ipv4address(const WCHAR **ptr, parse_data *data, DWORD flags) {
1483     const BOOL is_unknown = data->scheme_type == URL_SCHEME_UNKNOWN;
1484     data->host = *ptr;
1485
1486     if(!check_ipv4address(ptr, FALSE)) {
1487         if(!check_implicit_ipv4(ptr, &data->implicit_ipv4)) {
1488             TRACE("(%p %p %x): URI didn't contain anything looking like an IPv4 address.\n",
1489                 ptr, data, flags);
1490             *ptr = data->host;
1491             data->host = NULL;
1492             return FALSE;
1493         } else
1494             data->has_implicit_ip = TRUE;
1495     }
1496
1497     data->host_len = *ptr - data->host;
1498     data->host_type = Uri_HOST_IPV4;
1499
1500     /* Check if what we found is the only part of the host name (if it isn't
1501      * we don't have an IPv4 address).
1502      */
1503     if(**ptr == ':') {
1504         ++(*ptr);
1505         if(!parse_port(ptr, data, flags)) {
1506             *ptr = data->host;
1507             data->host = NULL;
1508             return FALSE;
1509         }
1510     } else if(!is_auth_delim(**ptr, !is_unknown)) {
1511         /* Found more data which belongs to the host, so this isn't an IPv4. */
1512         *ptr = data->host;
1513         data->host = NULL;
1514         data->has_implicit_ip = FALSE;
1515         return FALSE;
1516     }
1517
1518     TRACE("(%p %p %x): IPv4 address found. host=%s host_len=%d host_type=%d\n",
1519         ptr, data, flags, debugstr_wn(data->host, data->host_len),
1520         data->host_len, data->host_type);
1521     return TRUE;
1522 }
1523
1524 /* Attempts to parse the reg-name from the URI.
1525  *
1526  * Because of the way Windows handles ':' this function also
1527  * handles parsing the port.
1528  *
1529  * reg-name = *( unreserved / pct-encoded / sub-delims )
1530  *
1531  * NOTE:
1532  *  Windows allows everything, but, the characters in "auth_delims" and ':'
1533  *  to appear in a reg-name, unless it's an unknown scheme type then ':' is
1534  *  allowed to appear (even if a valid port isn't after it).
1535  *
1536  *  Windows doesn't like host names which start with '[' and end with ']'
1537  *  and don't contain a valid IP literal address in between them.
1538  *
1539  *  On Windows if a '[' is encountered in the host name the ':' no longer
1540  *  counts as a delimiter until you reach the next ']' or an "authority delimiter".
1541  *
1542  *  A reg-name CAN be empty.
1543  */
1544 static BOOL parse_reg_name(const WCHAR **ptr, parse_data *data, DWORD flags, DWORD extras) {
1545     const BOOL has_start_bracket = **ptr == '[';
1546     const BOOL known_scheme = data->scheme_type != URL_SCHEME_UNKNOWN;
1547     const BOOL is_res = data->scheme_type == URL_SCHEME_RES;
1548     BOOL inside_brackets = has_start_bracket;
1549
1550     /* res URIs don't have ports. */
1551     BOOL ignore_col = (extras & IGNORE_PORT_DELIMITER) || is_res;
1552
1553     /* We have to be careful with file schemes. */
1554     if(data->scheme_type == URL_SCHEME_FILE) {
1555         /* This is because an implicit file scheme could be "C:\\test" and it
1556          * would trick this function into thinking the host is "C", when after
1557          * canonicalization the host would end up being an empty string. A drive
1558          * path can also have a '|' instead of a ':' after the drive letter.
1559          */
1560         if(is_drive_path(*ptr)) {
1561             /* Regular old drive paths have no host type (or host name). */
1562             data->host_type = Uri_HOST_UNKNOWN;
1563             data->host = *ptr;
1564             data->host_len = 0;
1565             return TRUE;
1566         } else if(is_unc_path(*ptr))
1567             /* Skip past the "\\" of a UNC path. */
1568             *ptr += 2;
1569     }
1570
1571     data->host = *ptr;
1572
1573     /* For res URIs, everything before the first '/' is
1574      * considered the host.
1575      */
1576     while((!is_res && !is_auth_delim(**ptr, known_scheme)) ||
1577           (is_res && **ptr && **ptr != '/')) {
1578         if(**ptr == ':' && !ignore_col) {
1579             /* We can ignore ':' if were inside brackets.*/
1580             if(!inside_brackets) {
1581                 const WCHAR *tmp = (*ptr)++;
1582
1583                 /* Attempt to parse the port. */
1584                 if(!parse_port(ptr, data, flags)) {
1585                     /* Windows expects there to be a valid port for known scheme types. */
1586                     if(data->scheme_type != URL_SCHEME_UNKNOWN) {
1587                         *ptr = data->host;
1588                         data->host = NULL;
1589                         TRACE("(%p %p %x %x): Expected valid port\n", ptr, data, flags, extras);
1590                         return FALSE;
1591                     } else
1592                         /* Windows gives up on trying to parse a port when it
1593                          * encounters an invalid port.
1594                          */
1595                         ignore_col = TRUE;
1596                 } else {
1597                     data->host_len = tmp - data->host;
1598                     break;
1599                 }
1600             }
1601         } else if(**ptr == '%' && (known_scheme && !is_res)) {
1602             /* Has to be a legit % encoded value. */
1603             if(!check_pct_encoded(ptr)) {
1604                 *ptr = data->host;
1605                 data->host = NULL;
1606                 return FALSE;
1607             } else
1608                 continue;
1609         } else if(is_res && is_forbidden_dos_path_char(**ptr)) {
1610             *ptr = data->host;
1611             data->host = NULL;
1612             return FALSE;
1613         } else if(**ptr == ']')
1614             inside_brackets = FALSE;
1615         else if(**ptr == '[')
1616             inside_brackets = TRUE;
1617
1618         ++(*ptr);
1619     }
1620
1621     if(has_start_bracket) {
1622         /* Make sure the last character of the host wasn't a ']'. */
1623         if(*(*ptr-1) == ']') {
1624             TRACE("(%p %p %x %x): Expected an IP literal inside of the host\n",
1625                 ptr, data, flags, extras);
1626             *ptr = data->host;
1627             data->host = NULL;
1628             return FALSE;
1629         }
1630     }
1631
1632     /* Don't overwrite our length if we found a port earlier. */
1633     if(!data->port)
1634         data->host_len = *ptr - data->host;
1635
1636     /* If the host is empty, then it's an unknown host type. */
1637     if(data->host_len == 0 || is_res)
1638         data->host_type = Uri_HOST_UNKNOWN;
1639     else
1640         data->host_type = Uri_HOST_DNS;
1641
1642     TRACE("(%p %p %x %x): Parsed reg-name. host=%s len=%d\n", ptr, data, flags, extras,
1643         debugstr_wn(data->host, data->host_len), data->host_len);
1644     return TRUE;
1645 }
1646
1647 /* Attempts to parse an IPv6 address out of the URI.
1648  *
1649  * IPv6address =                               6( h16 ":" ) ls32
1650  *                /                       "::" 5( h16 ":" ) ls32
1651  *                / [               h16 ] "::" 4( h16 ":" ) ls32
1652  *                / [ *1( h16 ":" ) h16 ] "::" 3( h16 ":" ) ls32
1653  *                / [ *2( h16 ":" ) h16 ] "::" 2( h16 ":" ) ls32
1654  *                / [ *3( h16 ":" ) h16 ] "::"    h16 ":"   ls32
1655  *                / [ *4( h16 ":" ) h16 ] "::"              ls32
1656  *                / [ *5( h16 ":" ) h16 ] "::"              h16
1657  *                / [ *6( h16 ":" ) h16 ] "::"
1658  *
1659  * ls32        = ( h16 ":" h16 ) / IPv4address
1660  *             ; least-significant 32 bits of address.
1661  *
1662  * h16         = 1*4HEXDIG
1663  *             ; 16 bits of address represented in hexadecimal.
1664  *
1665  * Modeled after google-url's 'DoParseIPv6' function.
1666  */
1667 static BOOL parse_ipv6address(const WCHAR **ptr, parse_data *data, DWORD flags) {
1668     const WCHAR *start, *cur_start;
1669     ipv6_address ip;
1670
1671     start = cur_start = *ptr;
1672     memset(&ip, 0, sizeof(ipv6_address));
1673
1674     for(;; ++(*ptr)) {
1675         /* Check if we're on the last character of the host. */
1676         BOOL is_end = (is_auth_delim(**ptr, data->scheme_type != URL_SCHEME_UNKNOWN)
1677                         || **ptr == ']');
1678
1679         BOOL is_split = (**ptr == ':');
1680         BOOL is_elision = (is_split && !is_end && *(*ptr+1) == ':');
1681
1682         /* Check if we're at the end of a component, or
1683          * if we're at the end of the IPv6 address.
1684          */
1685         if(is_split || is_end) {
1686             DWORD cur_len = 0;
1687
1688             cur_len = *ptr - cur_start;
1689
1690             /* h16 can't have a length > 4. */
1691             if(cur_len > 4) {
1692                 *ptr = start;
1693
1694                 TRACE("(%p %p %x): h16 component to long.\n",
1695                     ptr, data, flags);
1696                 return FALSE;
1697             }
1698
1699             if(cur_len == 0) {
1700                 /* An h16 component can't have the length of 0 unless
1701                  * the elision is at the beginning of the address, or
1702                  * at the end of the address.
1703                  */
1704                 if(!((*ptr == start && is_elision) ||
1705                     (is_end && (*ptr-2) == ip.elision))) {
1706                     *ptr = start;
1707                     TRACE("(%p %p %x): IPv6 component cannot have a length of 0.\n",
1708                         ptr, data, flags);
1709                     return FALSE;
1710                 }
1711             }
1712
1713             if(cur_len > 0) {
1714                 /* An IPv6 address can have no more than 8 h16 components. */
1715                 if(ip.h16_count >= 8) {
1716                     *ptr = start;
1717                     TRACE("(%p %p %x): Not a IPv6 address, to many h16 components.\n",
1718                         ptr, data, flags);
1719                     return FALSE;
1720                 }
1721
1722                 ip.components[ip.h16_count].str = cur_start;
1723                 ip.components[ip.h16_count].len = cur_len;
1724
1725                 TRACE("(%p %p %x): Found h16 component %s, len=%d, h16_count=%d\n",
1726                     ptr, data, flags, debugstr_wn(cur_start, cur_len), cur_len,
1727                     ip.h16_count);
1728                 ++ip.h16_count;
1729             }
1730         }
1731
1732         if(is_end)
1733             break;
1734
1735         if(is_elision) {
1736             /* A IPv6 address can only have 1 elision ('::'). */
1737             if(ip.elision) {
1738                 *ptr = start;
1739
1740                 TRACE("(%p %p %x): IPv6 address cannot have 2 elisions.\n",
1741                     ptr, data, flags);
1742                 return FALSE;
1743             }
1744
1745             ip.elision = *ptr;
1746             ++(*ptr);
1747         }
1748
1749         if(is_split)
1750             cur_start = *ptr+1;
1751         else {
1752             if(!check_ipv4address(ptr, TRUE)) {
1753                 if(!is_hexdigit(**ptr)) {
1754                     /* Not a valid character for an IPv6 address. */
1755                     *ptr = start;
1756                     return FALSE;
1757                 }
1758             } else {
1759                 /* Found an IPv4 address. */
1760                 ip.ipv4 = cur_start;
1761                 ip.ipv4_len = *ptr - cur_start;
1762
1763                 TRACE("(%p %p %x): Found an attached IPv4 address %s len=%d.\n",
1764                     ptr, data, flags, debugstr_wn(ip.ipv4, ip.ipv4_len),
1765                     ip.ipv4_len);
1766
1767                 /* IPv4 addresses can only appear at the end of a IPv6. */
1768                 break;
1769             }
1770         }
1771     }
1772
1773     compute_ipv6_comps_size(&ip);
1774
1775     /* Make sure the IPv6 address adds up to 16 bytes. */
1776     if(ip.components_size + ip.elision_size != 16) {
1777         *ptr = start;
1778         TRACE("(%p %p %x): Invalid IPv6 address, did not add up to 16 bytes.\n",
1779             ptr, data, flags);
1780         return FALSE;
1781     }
1782
1783     if(ip.elision_size == 2) {
1784         /* For some reason on Windows if an elision that represents
1785          * only one h16 component is encountered at the very begin or
1786          * end of an IPv6 address, Windows does not consider it a
1787          * valid IPv6 address.
1788          *
1789          *  Ex: [::2:3:4:5:6:7] is not valid, even though the sum
1790          *      of all the components == 128bits.
1791          */
1792          if(ip.elision < ip.components[0].str ||
1793             ip.elision > ip.components[ip.h16_count-1].str) {
1794             *ptr = start;
1795             TRACE("(%p %p %x): Invalid IPv6 address. Detected elision of 2 bytes at the beginning or end of the address.\n",
1796                 ptr, data, flags);
1797             return FALSE;
1798         }
1799     }
1800
1801     data->host_type = Uri_HOST_IPV6;
1802     data->has_ipv6 = TRUE;
1803     data->ipv6_address = ip;
1804
1805     TRACE("(%p %p %x): Found valid IPv6 literal %s len=%d\n",
1806         ptr, data, flags, debugstr_wn(start, *ptr-start),
1807         (int)(*ptr-start));
1808     return TRUE;
1809 }
1810
1811 /*  IPvFuture  = "v" 1*HEXDIG "." 1*( unreserved / sub-delims / ":" ) */
1812 static BOOL parse_ipvfuture(const WCHAR **ptr, parse_data *data, DWORD flags) {
1813     const WCHAR *start = *ptr;
1814
1815     /* IPvFuture has to start with a 'v' or 'V'. */
1816     if(**ptr != 'v' && **ptr != 'V')
1817         return FALSE;
1818
1819     /* Following the v there must be at least 1 hex digit. */
1820     ++(*ptr);
1821     if(!is_hexdigit(**ptr)) {
1822         *ptr = start;
1823         return FALSE;
1824     }
1825
1826     ++(*ptr);
1827     while(is_hexdigit(**ptr))
1828         ++(*ptr);
1829
1830     /* End of the hexdigit sequence must be a '.' */
1831     if(**ptr != '.') {
1832         *ptr = start;
1833         return FALSE;
1834     }
1835
1836     ++(*ptr);
1837     if(!is_unreserved(**ptr) && !is_subdelim(**ptr) && **ptr != ':') {
1838         *ptr = start;
1839         return FALSE;
1840     }
1841
1842     ++(*ptr);
1843     while(is_unreserved(**ptr) || is_subdelim(**ptr) || **ptr == ':')
1844         ++(*ptr);
1845
1846     data->host_type = Uri_HOST_UNKNOWN;
1847
1848     TRACE("(%p %p %x): Parsed IPvFuture address %s len=%d\n", ptr, data, flags,
1849           debugstr_wn(start, *ptr-start), (int)(*ptr-start));
1850
1851     return TRUE;
1852 }
1853
1854 /* IP-literal = "[" ( IPv6address / IPvFuture  ) "]" */
1855 static BOOL parse_ip_literal(const WCHAR **ptr, parse_data *data, DWORD flags, DWORD extras) {
1856     data->host = *ptr;
1857
1858     if(**ptr != '[' && !(extras & ALLOW_BRACKETLESS_IP_LITERAL)) {
1859         data->host = NULL;
1860         return FALSE;
1861     } else if(**ptr == '[')
1862         ++(*ptr);
1863
1864     if(!parse_ipv6address(ptr, data, flags)) {
1865         if(extras & SKIP_IP_FUTURE_CHECK || !parse_ipvfuture(ptr, data, flags)) {
1866             *ptr = data->host;
1867             data->host = NULL;
1868             return FALSE;
1869         }
1870     }
1871
1872     if(**ptr != ']' && !(extras & ALLOW_BRACKETLESS_IP_LITERAL)) {
1873         *ptr = data->host;
1874         data->host = NULL;
1875         return FALSE;
1876     } else if(!**ptr && extras & ALLOW_BRACKETLESS_IP_LITERAL) {
1877         /* The IP literal didn't contain brackets and was followed by
1878          * a NULL terminator, so no reason to even check the port.
1879          */
1880         data->host_len = *ptr - data->host;
1881         return TRUE;
1882     }
1883
1884     ++(*ptr);
1885     if(**ptr == ':') {
1886         ++(*ptr);
1887         /* If a valid port is not found, then let it trickle down to
1888          * parse_reg_name.
1889          */
1890         if(!parse_port(ptr, data, flags)) {
1891             *ptr = data->host;
1892             data->host = NULL;
1893             return FALSE;
1894         }
1895     } else
1896         data->host_len = *ptr - data->host;
1897
1898     return TRUE;
1899 }
1900
1901 /* Parses the host information from the URI.
1902  *
1903  * host = IP-literal / IPv4address / reg-name
1904  */
1905 static BOOL parse_host(const WCHAR **ptr, parse_data *data, DWORD flags, DWORD extras) {
1906     if(!parse_ip_literal(ptr, data, flags, extras)) {
1907         if(!parse_ipv4address(ptr, data, flags)) {
1908             if(!parse_reg_name(ptr, data, flags, extras)) {
1909                 TRACE("(%p %p %x %x): Malformed URI, Unknown host type.\n",
1910                     ptr, data, flags, extras);
1911                 return FALSE;
1912             }
1913         }
1914     }
1915
1916     return TRUE;
1917 }
1918
1919 /* Parses the authority information from the URI.
1920  *
1921  * authority   = [ userinfo "@" ] host [ ":" port ]
1922  */
1923 static BOOL parse_authority(const WCHAR **ptr, parse_data *data, DWORD flags) {
1924     parse_userinfo(ptr, data, flags);
1925
1926     /* Parsing the port will happen during one of the host parsing
1927      * routines (if the URI has a port).
1928      */
1929     if(!parse_host(ptr, data, flags, 0))
1930         return FALSE;
1931
1932     return TRUE;
1933 }
1934
1935 /* Attempts to parse the path information of a hierarchical URI. */
1936 static BOOL parse_path_hierarchical(const WCHAR **ptr, parse_data *data, DWORD flags) {
1937     const WCHAR *start = *ptr;
1938     static const WCHAR slash[] = {'/',0};
1939     const BOOL is_file = data->scheme_type == URL_SCHEME_FILE;
1940
1941     if(is_path_delim(**ptr)) {
1942         if(data->scheme_type == URL_SCHEME_WILDCARD && !data->must_have_path) {
1943             data->path = NULL;
1944             data->path_len = 0;
1945         } else if(!(flags & Uri_CREATE_NO_CANONICALIZE)) {
1946             /* If the path component is empty, then a '/' is added. */
1947             data->path = slash;
1948             data->path_len = 1;
1949         }
1950     } else {
1951         while(!is_path_delim(**ptr)) {
1952             if(**ptr == '%' && data->scheme_type != URL_SCHEME_UNKNOWN && !is_file) {
1953                 if(!check_pct_encoded(ptr)) {
1954                     *ptr = start;
1955                     return FALSE;
1956                 } else
1957                     continue;
1958             } else if(is_forbidden_dos_path_char(**ptr) && is_file &&
1959                       (flags & Uri_CREATE_FILE_USE_DOS_PATH)) {
1960                 /* File schemes with USE_DOS_PATH set aren't allowed to have
1961                  * a '<' or '>' or '\"' appear in them.
1962                  */
1963                 *ptr = start;
1964                 return FALSE;
1965             } else if(**ptr == '\\') {
1966                 /* Not allowed to have a backslash if NO_CANONICALIZE is set
1967                  * and the scheme is known type (but not a file scheme).
1968                  */
1969                 if(flags & Uri_CREATE_NO_CANONICALIZE) {
1970                     if(data->scheme_type != URL_SCHEME_FILE &&
1971                        data->scheme_type != URL_SCHEME_UNKNOWN) {
1972                         *ptr = start;
1973                         return FALSE;
1974                     }
1975                 }
1976             }
1977
1978             ++(*ptr);
1979         }
1980
1981         /* The only time a URI doesn't have a path is when
1982          * the NO_CANONICALIZE flag is set and the raw URI
1983          * didn't contain one.
1984          */
1985         if(*ptr == start) {
1986             data->path = NULL;
1987             data->path_len = 0;
1988         } else {
1989             data->path = start;
1990             data->path_len = *ptr - start;
1991         }
1992     }
1993
1994     if(data->path)
1995         TRACE("(%p %p %x): Parsed path %s len=%d\n", ptr, data, flags,
1996             debugstr_wn(data->path, data->path_len), data->path_len);
1997     else
1998         TRACE("(%p %p %x): The URI contained no path\n", ptr, data, flags);
1999
2000     return TRUE;
2001 }
2002
2003 /* Parses the path of an opaque URI (much less strict then the parser
2004  * for a hierarchical URI).
2005  *
2006  * NOTE:
2007  *  Windows allows invalid % encoded data to appear in opaque URI paths
2008  *  for unknown scheme types.
2009  *
2010  *  File schemes with USE_DOS_PATH set aren't allowed to have '<', '>', or '\"'
2011  *  appear in them.
2012  */
2013 static BOOL parse_path_opaque(const WCHAR **ptr, parse_data *data, DWORD flags) {
2014     const BOOL known_scheme = data->scheme_type != URL_SCHEME_UNKNOWN;
2015     const BOOL is_file = data->scheme_type == URL_SCHEME_FILE;
2016
2017     data->path = *ptr;
2018
2019     while(!is_path_delim(**ptr)) {
2020         if(**ptr == '%' && known_scheme) {
2021             if(!check_pct_encoded(ptr)) {
2022                 *ptr = data->path;
2023                 data->path = NULL;
2024                 return FALSE;
2025             } else
2026                 continue;
2027         } else if(is_forbidden_dos_path_char(**ptr) && is_file &&
2028                   (flags & Uri_CREATE_FILE_USE_DOS_PATH)) {
2029             *ptr = data->path;
2030             data->path = NULL;
2031             return FALSE;
2032         }
2033
2034         ++(*ptr);
2035     }
2036
2037     data->path_len = *ptr - data->path;
2038     TRACE("(%p %p %x): Parsed opaque URI path %s len=%d\n", ptr, data, flags,
2039         debugstr_wn(data->path, data->path_len), data->path_len);
2040     return TRUE;
2041 }
2042
2043 /* Determines how the URI should be parsed after the scheme information.
2044  *
2045  * If the scheme is followed by "//", then it is treated as a hierarchical URI
2046  * which then the authority and path information will be parsed out. Otherwise, the
2047  * URI will be treated as an opaque URI which the authority information is not parsed
2048  * out.
2049  *
2050  * RFC 3896 definition of hier-part:
2051  *
2052  * hier-part   = "//" authority path-abempty
2053  *                 / path-absolute
2054  *                 / path-rootless
2055  *                 / path-empty
2056  *
2057  * MSDN opaque URI definition:
2058  *  scheme ":" path [ "#" fragment ]
2059  *
2060  * NOTES:
2061  *  If the URI is of an unknown scheme type and has a "//" following the scheme then it
2062  *  is treated as a hierarchical URI, but, if the CREATE_NO_CRACK_UNKNOWN_SCHEMES flag is
2063  *  set then it is considered an opaque URI regardless of what follows the scheme information
2064  *  (per MSDN documentation).
2065  */
2066 static BOOL parse_hierpart(const WCHAR **ptr, parse_data *data, DWORD flags) {
2067     const WCHAR *start = *ptr;
2068
2069     data->must_have_path = FALSE;
2070
2071     /* For javascript: URIs, simply set everything as a path */
2072     if(data->scheme_type == URL_SCHEME_JAVASCRIPT) {
2073         data->path = *ptr;
2074         data->path_len = strlenW(*ptr);
2075         data->is_opaque = TRUE;
2076         *ptr += data->path_len;
2077         return TRUE;
2078     }
2079
2080     /* Checks if the authority information needs to be parsed. */
2081     if(is_hierarchical_uri(ptr, data)) {
2082         /* Only treat it as a hierarchical URI if the scheme_type is known or
2083          * the Uri_CREATE_NO_CRACK_UNKNOWN_SCHEMES flag is not set.
2084          */
2085         if(data->scheme_type != URL_SCHEME_UNKNOWN ||
2086            !(flags & Uri_CREATE_NO_CRACK_UNKNOWN_SCHEMES)) {
2087             TRACE("(%p %p %x): Treating URI as an hierarchical URI.\n", ptr, data, flags);
2088             data->is_opaque = FALSE;
2089
2090             if(data->scheme_type == URL_SCHEME_WILDCARD && !data->has_implicit_scheme) {
2091                 if(**ptr == '/' && *(*ptr+1) == '/') {
2092                     data->must_have_path = TRUE;
2093                     *ptr += 2;
2094                 }
2095             }
2096
2097             /* TODO: Handle hierarchical URI's, parse authority then parse the path. */
2098             if(!parse_authority(ptr, data, flags))
2099                 return FALSE;
2100
2101             return parse_path_hierarchical(ptr, data, flags);
2102         } else
2103             /* Reset ptr to its starting position so opaque path parsing
2104              * begins at the correct location.
2105              */
2106             *ptr = start;
2107     }
2108
2109     /* If it reaches here, then the URI will be treated as an opaque
2110      * URI.
2111      */
2112
2113     TRACE("(%p %p %x): Treating URI as an opaque URI.\n", ptr, data, flags);
2114
2115     data->is_opaque = TRUE;
2116     if(!parse_path_opaque(ptr, data, flags))
2117         return FALSE;
2118
2119     return TRUE;
2120 }
2121
2122 /* Attempts to parse the query string from the URI.
2123  *
2124  * NOTES:
2125  *  If NO_DECODE_EXTRA_INFO flag is set, then invalid percent encoded
2126  *  data is allowed to appear in the query string. For unknown scheme types
2127  *  invalid percent encoded data is allowed to appear regardless.
2128  */
2129 static BOOL parse_query(const WCHAR **ptr, parse_data *data, DWORD flags) {
2130     const BOOL known_scheme = data->scheme_type != URL_SCHEME_UNKNOWN;
2131
2132     if(**ptr != '?') {
2133         TRACE("(%p %p %x): URI didn't contain a query string.\n", ptr, data, flags);
2134         return TRUE;
2135     }
2136
2137     data->query = *ptr;
2138
2139     ++(*ptr);
2140     while(**ptr && **ptr != '#') {
2141         if(**ptr == '%' && known_scheme &&
2142            !(flags & Uri_CREATE_NO_DECODE_EXTRA_INFO)) {
2143             if(!check_pct_encoded(ptr)) {
2144                 *ptr = data->query;
2145                 data->query = NULL;
2146                 return FALSE;
2147             } else
2148                 continue;
2149         }
2150
2151         ++(*ptr);
2152     }
2153
2154     data->query_len = *ptr - data->query;
2155
2156     TRACE("(%p %p %x): Parsed query string %s len=%d\n", ptr, data, flags,
2157         debugstr_wn(data->query, data->query_len), data->query_len);
2158     return TRUE;
2159 }
2160
2161 /* Attempts to parse the fragment from the URI.
2162  *
2163  * NOTES:
2164  *  If NO_DECODE_EXTRA_INFO flag is set, then invalid percent encoded
2165  *  data is allowed to appear in the query string. For unknown scheme types
2166  *  invalid percent encoded data is allowed to appear regardless.
2167  */
2168 static BOOL parse_fragment(const WCHAR **ptr, parse_data *data, DWORD flags) {
2169     const BOOL known_scheme = data->scheme_type != URL_SCHEME_UNKNOWN;
2170
2171     if(**ptr != '#') {
2172         TRACE("(%p %p %x): URI didn't contain a fragment.\n", ptr, data, flags);
2173         return TRUE;
2174     }
2175
2176     data->fragment = *ptr;
2177
2178     ++(*ptr);
2179     while(**ptr) {
2180         if(**ptr == '%' && known_scheme &&
2181            !(flags & Uri_CREATE_NO_DECODE_EXTRA_INFO)) {
2182             if(!check_pct_encoded(ptr)) {
2183                 *ptr = data->fragment;
2184                 data->fragment = NULL;
2185                 return FALSE;
2186             } else
2187                 continue;
2188         }
2189
2190         ++(*ptr);
2191     }
2192
2193     data->fragment_len = *ptr - data->fragment;
2194
2195     TRACE("(%p %p %x): Parsed fragment %s len=%d\n", ptr, data, flags,
2196         debugstr_wn(data->fragment, data->fragment_len), data->fragment_len);
2197     return TRUE;
2198 }
2199
2200 /* Parses and validates the components of the specified by data->uri
2201  * and stores the information it parses into 'data'.
2202  *
2203  * Returns TRUE if it successfully parsed the URI. False otherwise.
2204  */
2205 static BOOL parse_uri(parse_data *data, DWORD flags) {
2206     const WCHAR *ptr;
2207     const WCHAR **pptr;
2208
2209     ptr = data->uri;
2210     pptr = &ptr;
2211
2212     TRACE("(%p %x): BEGINNING TO PARSE URI %s.\n", data, flags, debugstr_w(data->uri));
2213
2214     if(!parse_scheme(pptr, data, flags, 0))
2215         return FALSE;
2216
2217     if(!parse_hierpart(pptr, data, flags))
2218         return FALSE;
2219
2220     if(!parse_query(pptr, data, flags))
2221         return FALSE;
2222
2223     if(!parse_fragment(pptr, data, flags))
2224         return FALSE;
2225
2226     TRACE("(%p %x): FINISHED PARSING URI.\n", data, flags);
2227     return TRUE;
2228 }
2229
2230 static BOOL canonicalize_username(const parse_data *data, Uri *uri, DWORD flags, BOOL computeOnly) {
2231     const WCHAR *ptr;
2232
2233     if(!data->username) {
2234         uri->userinfo_start = -1;
2235         return TRUE;
2236     }
2237
2238     uri->userinfo_start = uri->canon_len;
2239     for(ptr = data->username; ptr < data->username+data->username_len; ++ptr) {
2240         if(*ptr == '%') {
2241             /* Only decode % encoded values for known scheme types. */
2242             if(data->scheme_type != URL_SCHEME_UNKNOWN) {
2243                 /* See if the value really needs decoding. */
2244                 WCHAR val = decode_pct_val(ptr);
2245                 if(is_unreserved(val)) {
2246                     if(!computeOnly)
2247                         uri->canon_uri[uri->canon_len] = val;
2248
2249                     ++uri->canon_len;
2250
2251                     /* Move pass the hex characters. */
2252                     ptr += 2;
2253                     continue;
2254                 }
2255             }
2256         } else if(!is_reserved(*ptr) && !is_unreserved(*ptr) && *ptr != '\\') {
2257             /* Only percent encode forbidden characters if the NO_ENCODE_FORBIDDEN_CHARACTERS flag
2258              * is NOT set.
2259              */
2260             if(!(flags & Uri_CREATE_NO_ENCODE_FORBIDDEN_CHARACTERS)) {
2261                 if(!computeOnly)
2262                     pct_encode_val(*ptr, uri->canon_uri + uri->canon_len);
2263
2264                 uri->canon_len += 3;
2265                 continue;
2266             }
2267         }
2268
2269         if(!computeOnly)
2270             /* Nothing special, so just copy the character over. */
2271             uri->canon_uri[uri->canon_len] = *ptr;
2272         ++uri->canon_len;
2273     }
2274
2275     return TRUE;
2276 }
2277
2278 static BOOL canonicalize_password(const parse_data *data, Uri *uri, DWORD flags, BOOL computeOnly) {
2279     const WCHAR *ptr;
2280
2281     if(!data->password) {
2282         uri->userinfo_split = -1;
2283         return TRUE;
2284     }
2285
2286     if(uri->userinfo_start == -1)
2287         /* Has a password, but, doesn't have a username. */
2288         uri->userinfo_start = uri->canon_len;
2289
2290     uri->userinfo_split = uri->canon_len - uri->userinfo_start;
2291
2292     /* Add the ':' to the userinfo component. */
2293     if(!computeOnly)
2294         uri->canon_uri[uri->canon_len] = ':';
2295     ++uri->canon_len;
2296
2297     for(ptr = data->password; ptr < data->password+data->password_len; ++ptr) {
2298         if(*ptr == '%') {
2299             /* Only decode % encoded values for known scheme types. */
2300             if(data->scheme_type != URL_SCHEME_UNKNOWN) {
2301                 /* See if the value really needs decoding. */
2302                 WCHAR val = decode_pct_val(ptr);
2303                 if(is_unreserved(val)) {
2304                     if(!computeOnly)
2305                         uri->canon_uri[uri->canon_len] = val;
2306
2307                     ++uri->canon_len;
2308
2309                     /* Move pass the hex characters. */
2310                     ptr += 2;
2311                     continue;
2312                 }
2313             }
2314         } else if(!is_reserved(*ptr) && !is_unreserved(*ptr) && *ptr != '\\') {
2315             /* Only percent encode forbidden characters if the NO_ENCODE_FORBIDDEN_CHARACTERS flag
2316              * is NOT set.
2317              */
2318             if(!(flags & Uri_CREATE_NO_ENCODE_FORBIDDEN_CHARACTERS)) {
2319                 if(!computeOnly)
2320                     pct_encode_val(*ptr, uri->canon_uri + uri->canon_len);
2321
2322                 uri->canon_len += 3;
2323                 continue;
2324             }
2325         }
2326
2327         if(!computeOnly)
2328             /* Nothing special, so just copy the character over. */
2329             uri->canon_uri[uri->canon_len] = *ptr;
2330         ++uri->canon_len;
2331     }
2332
2333     return TRUE;
2334 }
2335
2336 /* Canonicalizes the userinfo of the URI represented by the parse_data.
2337  *
2338  * Canonicalization of the userinfo is a simple process. If there are any percent
2339  * encoded characters that fall in the "unreserved" character set, they are decoded
2340  * to their actual value. If a character is not in the "unreserved" or "reserved" sets
2341  * then it is percent encoded. Other than that the characters are copied over without
2342  * change.
2343  */
2344 static BOOL canonicalize_userinfo(const parse_data *data, Uri *uri, DWORD flags, BOOL computeOnly) {
2345     uri->userinfo_start = uri->userinfo_split = -1;
2346     uri->userinfo_len = 0;
2347
2348     if(!data->username && !data->password)
2349         /* URI doesn't have userinfo, so nothing to do here. */
2350         return TRUE;
2351
2352     if(!canonicalize_username(data, uri, flags, computeOnly))
2353         return FALSE;
2354
2355     if(!canonicalize_password(data, uri, flags, computeOnly))
2356         return FALSE;
2357
2358     uri->userinfo_len = uri->canon_len - uri->userinfo_start;
2359     if(!computeOnly)
2360         TRACE("(%p %p %x %d): Canonicalized userinfo, userinfo_start=%d, userinfo=%s, userinfo_split=%d userinfo_len=%d.\n",
2361                 data, uri, flags, computeOnly, uri->userinfo_start, debugstr_wn(uri->canon_uri + uri->userinfo_start, uri->userinfo_len),
2362                 uri->userinfo_split, uri->userinfo_len);
2363
2364     /* Now insert the '@' after the userinfo. */
2365     if(!computeOnly)
2366         uri->canon_uri[uri->canon_len] = '@';
2367     ++uri->canon_len;
2368
2369     return TRUE;
2370 }
2371
2372 /* Attempts to canonicalize a reg_name.
2373  *
2374  * Things that happen:
2375  *  1)  If Uri_CREATE_NO_CANONICALIZE flag is not set, then the reg_name is
2376  *      lower cased. Unless it's an unknown scheme type, which case it's
2377  *      no lower cased regardless.
2378  *
2379  *  2)  Unreserved % encoded characters are decoded for known
2380  *      scheme types.
2381  *
2382  *  3)  Forbidden characters are % encoded as long as
2383  *      Uri_CREATE_NO_ENCODE_FORBIDDEN_CHARACTERS flag is not set and
2384  *      it isn't an unknown scheme type.
2385  *
2386  *  4)  If it's a file scheme and the host is "localhost" it's removed.
2387  *
2388  *  5)  If it's a file scheme and Uri_CREATE_FILE_USE_DOS_PATH is set,
2389  *      then the UNC path characters are added before the host name.
2390  */
2391 static BOOL canonicalize_reg_name(const parse_data *data, Uri *uri,
2392                                   DWORD flags, BOOL computeOnly) {
2393     static const WCHAR localhostW[] =
2394             {'l','o','c','a','l','h','o','s','t',0};
2395     const WCHAR *ptr;
2396     const BOOL known_scheme = data->scheme_type != URL_SCHEME_UNKNOWN;
2397
2398     if(data->scheme_type == URL_SCHEME_FILE &&
2399        data->host_len == lstrlenW(localhostW)) {
2400         if(!StrCmpNIW(data->host, localhostW, data->host_len)) {
2401             uri->host_start = -1;
2402             uri->host_len = 0;
2403             uri->host_type = Uri_HOST_UNKNOWN;
2404             return TRUE;
2405         }
2406     }
2407
2408     if(data->scheme_type == URL_SCHEME_FILE && flags & Uri_CREATE_FILE_USE_DOS_PATH) {
2409         if(!computeOnly) {
2410             uri->canon_uri[uri->canon_len] = '\\';
2411             uri->canon_uri[uri->canon_len+1] = '\\';
2412         }
2413         uri->canon_len += 2;
2414         uri->authority_start = uri->canon_len;
2415     }
2416
2417     uri->host_start = uri->canon_len;
2418
2419     for(ptr = data->host; ptr < data->host+data->host_len; ++ptr) {
2420         if(*ptr == '%' && known_scheme) {
2421             WCHAR val = decode_pct_val(ptr);
2422             if(is_unreserved(val)) {
2423                 /* If NO_CANONICALIZE is not set, then windows lower cases the
2424                  * decoded value.
2425                  */
2426                 if(!(flags & Uri_CREATE_NO_CANONICALIZE) && isupperW(val)) {
2427                     if(!computeOnly)
2428                         uri->canon_uri[uri->canon_len] = tolowerW(val);
2429                 } else {
2430                     if(!computeOnly)
2431                         uri->canon_uri[uri->canon_len] = val;
2432                 }
2433                 ++uri->canon_len;
2434
2435                 /* Skip past the % encoded character. */
2436                 ptr += 2;
2437                 continue;
2438             } else {
2439                 /* Just copy the % over. */
2440                 if(!computeOnly)
2441                     uri->canon_uri[uri->canon_len] = *ptr;
2442                 ++uri->canon_len;
2443             }
2444         } else if(*ptr == '\\') {
2445             /* Only unknown scheme types could have made it here with a '\\' in the host name. */
2446             if(!computeOnly)
2447                 uri->canon_uri[uri->canon_len] = *ptr;
2448             ++uri->canon_len;
2449         } else if(!(flags & Uri_CREATE_NO_ENCODE_FORBIDDEN_CHARACTERS) &&
2450                   !is_unreserved(*ptr) && !is_reserved(*ptr) && known_scheme) {
2451             if(!computeOnly) {
2452                 pct_encode_val(*ptr, uri->canon_uri+uri->canon_len);
2453
2454                 /* The percent encoded value gets lower cased also. */
2455                 if(!(flags & Uri_CREATE_NO_CANONICALIZE)) {
2456                     uri->canon_uri[uri->canon_len+1] = tolowerW(uri->canon_uri[uri->canon_len+1]);
2457                     uri->canon_uri[uri->canon_len+2] = tolowerW(uri->canon_uri[uri->canon_len+2]);
2458                 }
2459             }
2460
2461             uri->canon_len += 3;
2462         } else {
2463             if(!computeOnly) {
2464                 if(!(flags & Uri_CREATE_NO_CANONICALIZE) && known_scheme)
2465                     uri->canon_uri[uri->canon_len] = tolowerW(*ptr);
2466                 else
2467                     uri->canon_uri[uri->canon_len] = *ptr;
2468             }
2469
2470             ++uri->canon_len;
2471         }
2472     }
2473
2474     uri->host_len = uri->canon_len - uri->host_start;
2475
2476     if(!computeOnly)
2477         TRACE("(%p %p %x %d): Canonicalize reg_name=%s len=%d\n", data, uri, flags,
2478             computeOnly, debugstr_wn(uri->canon_uri+uri->host_start, uri->host_len),
2479             uri->host_len);
2480
2481     if(!computeOnly)
2482         find_domain_name(uri->canon_uri+uri->host_start, uri->host_len,
2483             &(uri->domain_offset));
2484
2485     return TRUE;
2486 }
2487
2488 /* Attempts to canonicalize an implicit IPv4 address. */
2489 static BOOL canonicalize_implicit_ipv4address(const parse_data *data, Uri *uri, DWORD flags, BOOL computeOnly) {
2490     uri->host_start = uri->canon_len;
2491
2492     TRACE("%u\n", data->implicit_ipv4);
2493     /* For unknown scheme types Windows doesn't convert
2494      * the value into an IP address, but it still considers
2495      * it an IPv4 address.
2496      */
2497     if(data->scheme_type == URL_SCHEME_UNKNOWN) {
2498         if(!computeOnly)
2499             memcpy(uri->canon_uri+uri->canon_len, data->host, data->host_len*sizeof(WCHAR));
2500         uri->canon_len += data->host_len;
2501     } else {
2502         if(!computeOnly)
2503             uri->canon_len += ui2ipv4(uri->canon_uri+uri->canon_len, data->implicit_ipv4);
2504         else
2505             uri->canon_len += ui2ipv4(NULL, data->implicit_ipv4);
2506     }
2507
2508     uri->host_len = uri->canon_len - uri->host_start;
2509     uri->host_type = Uri_HOST_IPV4;
2510
2511     if(!computeOnly)
2512         TRACE("%p %p %x %d): Canonicalized implicit IP address=%s len=%d\n",
2513             data, uri, flags, computeOnly,
2514             debugstr_wn(uri->canon_uri+uri->host_start, uri->host_len),
2515             uri->host_len);
2516
2517     return TRUE;
2518 }
2519
2520 /* Attempts to canonicalize an IPv4 address.
2521  *
2522  * If the parse_data represents a URI that has an implicit IPv4 address
2523  * (ex. http://256/, this function will convert 256 into 0.0.1.0). If
2524  * the implicit IP address exceeds the value of UINT_MAX (maximum value
2525  * for an IPv4 address) it's canonicalized as if it were a reg-name.
2526  *
2527  * If the parse_data contains a partial or full IPv4 address it normalizes it.
2528  * A partial IPv4 address is something like "192.0" and would be normalized to
2529  * "192.0.0.0". With a full (or partial) IPv4 address like "192.002.01.003" would
2530  * be normalized to "192.2.1.3".
2531  *
2532  * NOTES:
2533  *  Windows ONLY normalizes IPv4 address for known scheme types (one that isn't
2534  *  URL_SCHEME_UNKNOWN). For unknown scheme types, it simply copies the data from
2535  *  the original URI into the canonicalized URI, but, it still recognizes URI's
2536  *  host type as HOST_IPV4.
2537  */
2538 static BOOL canonicalize_ipv4address(const parse_data *data, Uri *uri, DWORD flags, BOOL computeOnly) {
2539     if(data->has_implicit_ip)
2540         return canonicalize_implicit_ipv4address(data, uri, flags, computeOnly);
2541     else {
2542         uri->host_start = uri->canon_len;
2543
2544         /* Windows only normalizes for known scheme types. */
2545         if(data->scheme_type != URL_SCHEME_UNKNOWN) {
2546             /* parse_data contains a partial or full IPv4 address, so normalize it. */
2547             DWORD i, octetDigitCount = 0, octetCount = 0;
2548             BOOL octetHasDigit = FALSE;
2549
2550             for(i = 0; i < data->host_len; ++i) {
2551                 if(data->host[i] == '0' && !octetHasDigit) {
2552                     /* Can ignore leading zeros if:
2553                      *  1) It isn't the last digit of the octet.
2554                      *  2) i+1 != data->host_len
2555                      *  3) i+1 != '.'
2556                      */
2557                     if(octetDigitCount == 2 ||
2558                        i+1 == data->host_len ||
2559                        data->host[i+1] == '.') {
2560                         if(!computeOnly)
2561                             uri->canon_uri[uri->canon_len] = data->host[i];
2562                         ++uri->canon_len;
2563                         TRACE("Adding zero\n");
2564                     }
2565                 } else if(data->host[i] == '.') {
2566                     if(!computeOnly)
2567                         uri->canon_uri[uri->canon_len] = data->host[i];
2568                     ++uri->canon_len;
2569
2570                     octetDigitCount = 0;
2571                     octetHasDigit = FALSE;
2572                     ++octetCount;
2573                 } else {
2574                     if(!computeOnly)
2575                         uri->canon_uri[uri->canon_len] = data->host[i];
2576                     ++uri->canon_len;
2577
2578                     ++octetDigitCount;
2579                     octetHasDigit = TRUE;
2580                 }
2581             }
2582
2583             /* Make sure the canonicalized IP address has 4 dec-octets.
2584              * If doesn't add "0" ones until there is 4;
2585              */
2586             for( ; octetCount < 3; ++octetCount) {
2587                 if(!computeOnly) {
2588                     uri->canon_uri[uri->canon_len] = '.';
2589                     uri->canon_uri[uri->canon_len+1] = '0';
2590                 }
2591
2592                 uri->canon_len += 2;
2593             }
2594         } else {
2595             /* Windows doesn't normalize addresses in unknown schemes. */
2596             if(!computeOnly)
2597                 memcpy(uri->canon_uri+uri->canon_len, data->host, data->host_len*sizeof(WCHAR));
2598             uri->canon_len += data->host_len;
2599         }
2600
2601         uri->host_len = uri->canon_len - uri->host_start;
2602         if(!computeOnly)
2603             TRACE("(%p %p %x %d): Canonicalized IPv4 address, ip=%s len=%d\n",
2604                 data, uri, flags, computeOnly,
2605                 debugstr_wn(uri->canon_uri+uri->host_start, uri->host_len),
2606                 uri->host_len);
2607     }
2608
2609     return TRUE;
2610 }
2611
2612 /* Attempts to canonicalize the IPv6 address of the URI.
2613  *
2614  * Multiple things happen during the canonicalization of an IPv6 address:
2615  *  1)  Any leading zero's in a h16 component are removed.
2616  *      Ex: [0001:0022::] -> [1:22::]
2617  *
2618  *  2)  The longest sequence of zero h16 components are compressed
2619  *      into a "::" (elision). If there's a tie, the first is chosen.
2620  *
2621  *      Ex: [0:0:0:0:1:6:7:8]   -> [::1:6:7:8]
2622  *          [0:0:0:0:1:2::]     -> [::1:2:0:0]
2623  *          [0:0:1:2:0:0:7:8]   -> [::1:2:0:0:7:8]
2624  *
2625  *  3)  If an IPv4 address is attached to the IPv6 address, it's
2626  *      also normalized.
2627  *      Ex: [::001.002.022.000] -> [::1.2.22.0]
2628  *
2629  *  4)  If an elision is present, but, only represents one h16 component
2630  *      it's expanded.
2631  *
2632  *      Ex: [1::2:3:4:5:6:7] -> [1:0:2:3:4:5:6:7]
2633  *
2634  *  5)  If the IPv6 address contains an IPv4 address and there exists
2635  *      at least 1 non-zero h16 component the IPv4 address is converted
2636  *      into two h16 components, otherwise it's normalized and kept as is.
2637  *
2638  *      Ex: [::192.200.003.4]       -> [::192.200.3.4]
2639  *          [ffff::192.200.003.4]   -> [ffff::c0c8:3041]
2640  *
2641  * NOTE:
2642  *  For unknown scheme types Windows simply copies the address over without any
2643  *  changes.
2644  *
2645  *  IPv4 address can be included in an elision if all its components are 0's.
2646  */
2647 static BOOL canonicalize_ipv6address(const parse_data *data, Uri *uri,
2648                                      DWORD flags, BOOL computeOnly) {
2649     uri->host_start = uri->canon_len;
2650
2651     if(data->scheme_type == URL_SCHEME_UNKNOWN) {
2652         if(!computeOnly)
2653             memcpy(uri->canon_uri+uri->canon_len, data->host, data->host_len*sizeof(WCHAR));
2654         uri->canon_len += data->host_len;
2655     } else {
2656         USHORT values[8];
2657         INT elision_start;
2658         DWORD i, elision_len;
2659
2660         if(!ipv6_to_number(&(data->ipv6_address), values)) {
2661             TRACE("(%p %p %x %d): Failed to compute numerical value for IPv6 address.\n",
2662                 data, uri, flags, computeOnly);
2663             return FALSE;
2664         }
2665
2666         if(!computeOnly)
2667             uri->canon_uri[uri->canon_len] = '[';
2668         ++uri->canon_len;
2669
2670         /* Find where the elision should occur (if any). */
2671         compute_elision_location(&(data->ipv6_address), values, &elision_start, &elision_len);
2672
2673         TRACE("%p %p %x %d): Elision starts at %d, len=%u\n", data, uri, flags,
2674             computeOnly, elision_start, elision_len);
2675
2676         for(i = 0; i < 8; ++i) {
2677             BOOL in_elision = (elision_start > -1 && i >= elision_start &&
2678                                i < elision_start+elision_len);
2679             BOOL do_ipv4 = (i == 6 && data->ipv6_address.ipv4 && !in_elision &&
2680                             data->ipv6_address.h16_count == 0);
2681
2682             if(i == elision_start) {
2683                 if(!computeOnly) {
2684                     uri->canon_uri[uri->canon_len] = ':';
2685                     uri->canon_uri[uri->canon_len+1] = ':';
2686                 }
2687                 uri->canon_len += 2;
2688             }
2689
2690             /* We can ignore the current component if we're in the elision. */
2691             if(in_elision)
2692                 continue;
2693
2694             /* We only add a ':' if we're not at i == 0, or when we're at
2695              * the very end of elision range since the ':' colon was handled
2696              * earlier. Otherwise we would end up with ":::" after elision.
2697              */
2698             if(i != 0 && !(elision_start > -1 && i == elision_start+elision_len)) {
2699                 if(!computeOnly)
2700                     uri->canon_uri[uri->canon_len] = ':';
2701                 ++uri->canon_len;
2702             }
2703
2704             if(do_ipv4) {
2705                 UINT val;
2706                 DWORD len;
2707
2708                 /* Combine the two parts of the IPv4 address values. */
2709                 val = values[i];
2710                 val <<= 16;
2711                 val += values[i+1];
2712
2713                 if(!computeOnly)
2714                     len = ui2ipv4(uri->canon_uri+uri->canon_len, val);
2715                 else
2716                     len = ui2ipv4(NULL, val);
2717
2718                 uri->canon_len += len;
2719                 ++i;
2720             } else {
2721                 /* Write a regular h16 component to the URI. */
2722
2723                 /* Short circuit for the trivial case. */
2724                 if(values[i] == 0) {
2725                     if(!computeOnly)
2726                         uri->canon_uri[uri->canon_len] = '0';
2727                     ++uri->canon_len;
2728                 } else {
2729                     static const WCHAR formatW[] = {'%','x',0};
2730
2731                     if(!computeOnly)
2732                         uri->canon_len += sprintfW(uri->canon_uri+uri->canon_len,
2733                                             formatW, values[i]);
2734                     else {
2735                         WCHAR tmp[5];
2736                         uri->canon_len += sprintfW(tmp, formatW, values[i]);
2737                     }
2738                 }
2739             }
2740         }
2741
2742         /* Add the closing ']'. */
2743         if(!computeOnly)
2744             uri->canon_uri[uri->canon_len] = ']';
2745         ++uri->canon_len;
2746     }
2747
2748     uri->host_len = uri->canon_len - uri->host_start;
2749
2750     if(!computeOnly)
2751         TRACE("(%p %p %x %d): Canonicalized IPv6 address %s, len=%d\n", data, uri, flags,
2752             computeOnly, debugstr_wn(uri->canon_uri+uri->host_start, uri->host_len),
2753             uri->host_len);
2754
2755     return TRUE;
2756 }
2757
2758 /* Attempts to canonicalize the host of the URI (if any). */
2759 static BOOL canonicalize_host(const parse_data *data, Uri *uri, DWORD flags, BOOL computeOnly) {
2760     uri->host_start = -1;
2761     uri->host_len = 0;
2762     uri->domain_offset = -1;
2763
2764     if(data->host) {
2765         switch(data->host_type) {
2766         case Uri_HOST_DNS:
2767             uri->host_type = Uri_HOST_DNS;
2768             if(!canonicalize_reg_name(data, uri, flags, computeOnly))
2769                 return FALSE;
2770
2771             break;
2772         case Uri_HOST_IPV4:
2773             uri->host_type = Uri_HOST_IPV4;
2774             if(!canonicalize_ipv4address(data, uri, flags, computeOnly))
2775                 return FALSE;
2776
2777             break;
2778         case Uri_HOST_IPV6:
2779             if(!canonicalize_ipv6address(data, uri, flags, computeOnly))
2780                 return FALSE;
2781
2782             uri->host_type = Uri_HOST_IPV6;
2783             break;
2784         case Uri_HOST_UNKNOWN:
2785             if(data->host_len > 0 || data->scheme_type != URL_SCHEME_FILE) {
2786                 uri->host_start = uri->canon_len;
2787
2788                 /* Nothing happens to unknown host types. */
2789                 if(!computeOnly)
2790                     memcpy(uri->canon_uri+uri->canon_len, data->host, data->host_len*sizeof(WCHAR));
2791                 uri->canon_len += data->host_len;
2792                 uri->host_len = data->host_len;
2793             }
2794
2795             uri->host_type = Uri_HOST_UNKNOWN;
2796             break;
2797         default:
2798             FIXME("(%p %p %x %d): Canonicalization for host type %d not supported.\n", data,
2799                     uri, flags, computeOnly, data->host_type);
2800             return FALSE;
2801        }
2802    }
2803
2804    return TRUE;
2805 }
2806
2807 static BOOL canonicalize_port(const parse_data *data, Uri *uri, DWORD flags, BOOL computeOnly) {
2808     BOOL has_default_port = FALSE;
2809     USHORT default_port = 0;
2810     DWORD i;
2811
2812     uri->port_offset = -1;
2813
2814     /* Check if the scheme has a default port. */
2815     for(i = 0; i < sizeof(default_ports)/sizeof(default_ports[0]); ++i) {
2816         if(default_ports[i].scheme == data->scheme_type) {
2817             has_default_port = TRUE;
2818             default_port = default_ports[i].port;
2819             break;
2820         }
2821     }
2822
2823     uri->has_port = data->has_port || has_default_port;
2824
2825     /* Possible cases:
2826      *  1)  Has a port which is the default port.
2827      *  2)  Has a port (not the default).
2828      *  3)  Doesn't have a port, but, scheme has a default port.
2829      *  4)  No port.
2830      */
2831     if(has_default_port && data->has_port && data->port_value == default_port) {
2832         /* If it's the default port and this flag isn't set, don't do anything. */
2833         if(flags & Uri_CREATE_NO_CANONICALIZE) {
2834             uri->port_offset = uri->canon_len-uri->authority_start;
2835             if(!computeOnly)
2836                 uri->canon_uri[uri->canon_len] = ':';
2837             ++uri->canon_len;
2838
2839             if(data->port) {
2840                 /* Copy the original port over. */
2841                 if(!computeOnly)
2842                     memcpy(uri->canon_uri+uri->canon_len, data->port, data->port_len*sizeof(WCHAR));
2843                 uri->canon_len += data->port_len;
2844             } else {
2845                 if(!computeOnly)
2846                     uri->canon_len += ui2str(uri->canon_uri+uri->canon_len, data->port_value);
2847                 else
2848                     uri->canon_len += ui2str(NULL, data->port_value);
2849             }
2850         }
2851
2852         uri->port = default_port;
2853     } else if(data->has_port) {
2854         uri->port_offset = uri->canon_len-uri->authority_start;
2855         if(!computeOnly)
2856             uri->canon_uri[uri->canon_len] = ':';
2857         ++uri->canon_len;
2858
2859         if(flags & Uri_CREATE_NO_CANONICALIZE && data->port) {
2860             /* Copy the original over without changes. */
2861             if(!computeOnly)
2862                 memcpy(uri->canon_uri+uri->canon_len, data->port, data->port_len*sizeof(WCHAR));
2863             uri->canon_len += data->port_len;
2864         } else {
2865             if(!computeOnly)
2866                 uri->canon_len += ui2str(uri->canon_uri+uri->canon_len, data->port_value);
2867             else
2868                 uri->canon_len += ui2str(NULL, data->port_value);
2869         }
2870
2871         uri->port = data->port_value;
2872     } else if(has_default_port)
2873         uri->port = default_port;
2874
2875     return TRUE;
2876 }
2877
2878 /* Canonicalizes the authority of the URI represented by the parse_data. */
2879 static BOOL canonicalize_authority(const parse_data *data, Uri *uri, DWORD flags, BOOL computeOnly) {
2880     uri->authority_start = uri->canon_len;
2881     uri->authority_len = 0;
2882
2883     if(!canonicalize_userinfo(data, uri, flags, computeOnly))
2884         return FALSE;
2885
2886     if(!canonicalize_host(data, uri, flags, computeOnly))
2887         return FALSE;
2888
2889     if(!canonicalize_port(data, uri, flags, computeOnly))
2890         return FALSE;
2891
2892     if(uri->host_start != -1 || (data->is_relative && (data->password || data->username)))
2893         uri->authority_len = uri->canon_len - uri->authority_start;
2894     else
2895         uri->authority_start = -1;
2896
2897     return TRUE;
2898 }
2899
2900 /* Attempts to canonicalize the path of a hierarchical URI.
2901  *
2902  * Things that happen:
2903  *  1). Forbidden characters are percent encoded, unless the NO_ENCODE_FORBIDDEN
2904  *      flag is set or it's a file URI. Forbidden characters are always encoded
2905  *      for file schemes regardless and forbidden characters are never encoded
2906  *      for unknown scheme types.
2907  *
2908  *  2). For known scheme types '\\' are changed to '/'.
2909  *
2910  *  3). Percent encoded, unreserved characters are decoded to their actual values.
2911  *      Unless the scheme type is unknown. For file schemes any percent encoded
2912  *      character in the unreserved or reserved set is decoded.
2913  *
2914  *  4). For File schemes if the path is starts with a drive letter and doesn't
2915  *      start with a '/' then one is appended.
2916  *      Ex: file://c:/test.mp3 -> file:///c:/test.mp3
2917  *
2918  *  5). Dot segments are removed from the path for all scheme types
2919  *      unless NO_CANONICALIZE flag is set. Dot segments aren't removed
2920  *      for wildcard scheme types.
2921  *
2922  * NOTES:
2923  *      file://c:/test%20test   -> file:///c:/test%2520test
2924  *      file://c:/test%3Etest   -> file:///c:/test%253Etest
2925  * if Uri_CREATE_FILE_USE_DOS_PATH is not set:
2926  *      file:///c:/test%20test  -> file:///c:/test%20test
2927  *      file:///c:/test%test    -> file:///c:/test%25test
2928  */
2929 static BOOL canonicalize_path_hierarchical(const parse_data *data, Uri *uri,
2930                                            DWORD flags, BOOL computeOnly) {
2931     const WCHAR *ptr;
2932     const BOOL known_scheme = data->scheme_type != URL_SCHEME_UNKNOWN;
2933     const BOOL is_file = data->scheme_type == URL_SCHEME_FILE;
2934     const BOOL is_res = data->scheme_type == URL_SCHEME_RES;
2935
2936     BOOL escape_pct = FALSE;
2937
2938     if(!data->path) {
2939         uri->path_start = -1;
2940         uri->path_len = 0;
2941         return TRUE;
2942     }
2943
2944     uri->path_start = uri->canon_len;
2945     ptr = data->path;
2946
2947     if(is_file && uri->host_start == -1) {
2948         /* Check if a '/' needs to be appended for the file scheme. */
2949         if(data->path_len > 1 && is_drive_path(ptr) && !(flags & Uri_CREATE_FILE_USE_DOS_PATH)) {
2950             if(!computeOnly)
2951                 uri->canon_uri[uri->canon_len] = '/';
2952             uri->canon_len++;
2953             escape_pct = TRUE;
2954         } else if(*ptr == '/') {
2955             if(!(flags & Uri_CREATE_FILE_USE_DOS_PATH)) {
2956                 /* Copy the extra '/' over. */
2957                 if(!computeOnly)
2958                     uri->canon_uri[uri->canon_len] = '/';
2959                 ++uri->canon_len;
2960             }
2961             ++ptr;
2962         }
2963
2964         if(is_drive_path(ptr)) {
2965             if(!computeOnly) {
2966                 uri->canon_uri[uri->canon_len] = *ptr;
2967                 /* If there's a '|' after the drive letter, convert it to a ':'. */
2968                 uri->canon_uri[uri->canon_len+1] = ':';
2969             }
2970             ptr += 2;
2971             uri->canon_len += 2;
2972         }
2973     }
2974
2975     if(!is_file && *(data->path) && *(data->path) != '/') {
2976         /* Prepend a '/' to the path if it doesn't have one. */
2977         if(!computeOnly)
2978             uri->canon_uri[uri->canon_len] = '/';
2979         ++uri->canon_len;
2980     }
2981
2982     for(; ptr < data->path+data->path_len; ++ptr) {
2983         BOOL do_default_action = TRUE;
2984
2985         if(*ptr == '%' && !is_res) {
2986             const WCHAR *tmp = ptr;
2987             WCHAR val;
2988
2989             /* Check if the % represents a valid encoded char, or if it needs encoding. */
2990             BOOL force_encode = !check_pct_encoded(&tmp) && is_file && !(flags&Uri_CREATE_FILE_USE_DOS_PATH);
2991             val = decode_pct_val(ptr);
2992
2993             if(force_encode || escape_pct) {
2994                 /* Escape the percent sign in the file URI. */
2995                 if(!computeOnly)
2996                     pct_encode_val(*ptr, uri->canon_uri+uri->canon_len);
2997                 uri->canon_len += 3;
2998                 do_default_action = FALSE;
2999             } else if((is_unreserved(val) && known_scheme) ||
3000                       (is_file && (is_unreserved(val) || is_reserved(val) ||
3001                       (val && flags&Uri_CREATE_FILE_USE_DOS_PATH && !is_forbidden_dos_path_char(val))))) {
3002                 if(!computeOnly)
3003                     uri->canon_uri[uri->canon_len] = val;
3004                 ++uri->canon_len;
3005
3006                 ptr += 2;
3007                 continue;
3008             }
3009         } else if(*ptr == '/' && is_file && (flags & Uri_CREATE_FILE_USE_DOS_PATH)) {
3010             /* Convert the '/' back to a '\\'. */
3011             if(!computeOnly)
3012                 uri->canon_uri[uri->canon_len] = '\\';
3013             ++uri->canon_len;
3014             do_default_action = FALSE;
3015         } else if(*ptr == '\\' && known_scheme) {
3016             if(!(is_file && (flags & Uri_CREATE_FILE_USE_DOS_PATH))) {
3017                 /* Convert '\\' into a '/'. */
3018                 if(!computeOnly)
3019                     uri->canon_uri[uri->canon_len] = '/';
3020                 ++uri->canon_len;
3021                 do_default_action = FALSE;
3022             }
3023         } else if(known_scheme && !is_res && !is_unreserved(*ptr) && !is_reserved(*ptr) &&
3024                   (!(flags & Uri_CREATE_NO_ENCODE_FORBIDDEN_CHARACTERS) || is_file)) {
3025             if(!(is_file && (flags & Uri_CREATE_FILE_USE_DOS_PATH))) {
3026                 /* Escape the forbidden character. */
3027                 if(!computeOnly)
3028                     pct_encode_val(*ptr, uri->canon_uri+uri->canon_len);
3029                 uri->canon_len += 3;
3030                 do_default_action = FALSE;
3031             }
3032         }
3033
3034         if(do_default_action) {
3035             if(!computeOnly)
3036                 uri->canon_uri[uri->canon_len] = *ptr;
3037             ++uri->canon_len;
3038         }
3039     }
3040
3041     uri->path_len = uri->canon_len - uri->path_start;
3042
3043     /* Removing the dot segments only happens when it's not in
3044      * computeOnly mode and it's not a wildcard scheme. File schemes
3045      * with USE_DOS_PATH set don't get dot segments removed.
3046      */
3047     if(!(is_file && (flags & Uri_CREATE_FILE_USE_DOS_PATH)) &&
3048        data->scheme_type != URL_SCHEME_WILDCARD) {
3049         if(!(flags & Uri_CREATE_NO_CANONICALIZE) && !computeOnly) {
3050             /* Remove the dot segments (if any) and reset everything to the new
3051              * correct length.
3052              */
3053             DWORD new_len = remove_dot_segments(uri->canon_uri+uri->path_start, uri->path_len);
3054             uri->canon_len -= uri->path_len-new_len;
3055             uri->path_len = new_len;
3056         }
3057     }
3058
3059     if(!computeOnly)
3060         TRACE("Canonicalized path %s len=%d\n",
3061             debugstr_wn(uri->canon_uri+uri->path_start, uri->path_len),
3062             uri->path_len);
3063
3064     return TRUE;
3065 }
3066
3067 /* Attempts to canonicalize the path for an opaque URI.
3068  *
3069  * For known scheme types:
3070  *  1)  forbidden characters are percent encoded if
3071  *      NO_ENCODE_FORBIDDEN_CHARACTERS isn't set.
3072  *
3073  *  2)  Percent encoded, unreserved characters are decoded
3074  *      to their actual values, for known scheme types.
3075  *
3076  *  3)  '\\' are changed to '/' for known scheme types
3077  *      except for mailto schemes.
3078  *
3079  *  4)  For file schemes, if USE_DOS_PATH is set all '/'
3080  *      are converted to backslashes.
3081  *
3082  *  5)  For file schemes, if USE_DOS_PATH isn't set all '\'
3083  *      are converted to forward slashes.
3084  */
3085 static BOOL canonicalize_path_opaque(const parse_data *data, Uri *uri, DWORD flags, BOOL computeOnly) {
3086     const WCHAR *ptr;
3087     const BOOL known_scheme = data->scheme_type != URL_SCHEME_UNKNOWN;
3088     const BOOL is_file = data->scheme_type == URL_SCHEME_FILE;
3089     const BOOL is_mk = data->scheme_type == URL_SCHEME_MK;
3090
3091     if(!data->path) {
3092         uri->path_start = -1;
3093         uri->path_len = 0;
3094         return TRUE;
3095     }
3096
3097     uri->path_start = uri->canon_len;
3098
3099     if(is_mk){
3100         /* hijack this flag for SCHEME_MK to tell the function when to start
3101          * converting slashes */
3102         flags |= Uri_CREATE_FILE_USE_DOS_PATH;
3103     }
3104
3105     /* For javascript: URIs, simply copy path part without any canonicalization */
3106     if(data->scheme_type == URL_SCHEME_JAVASCRIPT) {
3107         if(!computeOnly)
3108             memcpy(uri->canon_uri+uri->canon_len, data->path, data->path_len*sizeof(WCHAR));
3109         uri->path_len = data->path_len;
3110         uri->canon_len += data->path_len;
3111         return TRUE;
3112     }
3113
3114     /* Windows doesn't allow a "//" to appear after the scheme
3115      * of a URI, if it's an opaque URI.
3116      */
3117     if(data->scheme && *(data->path) == '/' && *(data->path+1) == '/') {
3118         /* So it inserts a "/." before the "//" if it exists. */
3119         if(!computeOnly) {
3120             uri->canon_uri[uri->canon_len] = '/';
3121             uri->canon_uri[uri->canon_len+1] = '.';
3122         }
3123
3124         uri->canon_len += 2;
3125     }
3126
3127     for(ptr = data->path; ptr < data->path+data->path_len; ++ptr) {
3128         BOOL do_default_action = TRUE;
3129
3130         if(*ptr == '%' && known_scheme) {
3131             WCHAR val = decode_pct_val(ptr);
3132
3133             if(is_unreserved(val)) {
3134                 if(!computeOnly)
3135                     uri->canon_uri[uri->canon_len] = val;
3136                 ++uri->canon_len;
3137
3138                 ptr += 2;
3139                 continue;
3140             }
3141         } else if(*ptr == '/' && is_file && (flags & Uri_CREATE_FILE_USE_DOS_PATH)) {
3142             if(!computeOnly)
3143                 uri->canon_uri[uri->canon_len] = '\\';
3144             ++uri->canon_len;
3145             do_default_action = FALSE;
3146         } else if(*ptr == '\\') {
3147             if((data->is_relative || is_mk || is_file) && !(flags & Uri_CREATE_FILE_USE_DOS_PATH)) {
3148                 /* Convert to a '/'. */
3149                 if(!computeOnly)
3150                     uri->canon_uri[uri->canon_len] = '/';
3151                 ++uri->canon_len;
3152                 do_default_action = FALSE;
3153             }
3154         } else if(is_mk && *ptr == ':' && ptr + 1 < data->path + data->path_len && *(ptr + 1) == ':') {
3155             flags &= ~Uri_CREATE_FILE_USE_DOS_PATH;
3156         } else if(known_scheme && !is_unreserved(*ptr) && !is_reserved(*ptr) &&
3157                   !(flags & Uri_CREATE_NO_ENCODE_FORBIDDEN_CHARACTERS)) {
3158             if(!(is_file && (flags & Uri_CREATE_FILE_USE_DOS_PATH))) {
3159                 if(!computeOnly)
3160                     pct_encode_val(*ptr, uri->canon_uri+uri->canon_len);
3161                 uri->canon_len += 3;
3162                 do_default_action = FALSE;
3163             }
3164         }
3165
3166         if(do_default_action) {
3167             if(!computeOnly)
3168                 uri->canon_uri[uri->canon_len] = *ptr;
3169             ++uri->canon_len;
3170         }
3171     }
3172
3173     if(is_mk && !computeOnly && !(flags & Uri_CREATE_NO_CANONICALIZE)) {
3174         DWORD new_len = remove_dot_segments(uri->canon_uri + uri->path_start,
3175                                             uri->canon_len - uri->path_start);
3176         uri->canon_len = uri->path_start + new_len;
3177     }
3178
3179     uri->path_len = uri->canon_len - uri->path_start;
3180
3181     if(!computeOnly)
3182         TRACE("(%p %p %x %d): Canonicalized opaque URI path %s len=%d\n", data, uri, flags, computeOnly,
3183             debugstr_wn(uri->canon_uri+uri->path_start, uri->path_len), uri->path_len);
3184     return TRUE;
3185 }
3186
3187 /* Determines how the URI represented by the parse_data should be canonicalized.
3188  *
3189  * Essentially, if the parse_data represents an hierarchical URI then it calls
3190  * canonicalize_authority and the canonicalization functions for the path. If the
3191  * URI is opaque it canonicalizes the path of the URI.
3192  */
3193 static BOOL canonicalize_hierpart(const parse_data *data, Uri *uri, DWORD flags, BOOL computeOnly) {
3194     if(!data->is_opaque || (data->is_relative && (data->password || data->username))) {
3195         /* "//" is only added for non-wildcard scheme types.
3196          *
3197          * A "//" is only added to a relative URI if it has a
3198          * host or port component (this only happens if a IUriBuilder
3199          * is generating an IUri).
3200          */
3201         if((data->is_relative && (data->host || data->has_port)) ||
3202            (!data->is_relative && data->scheme_type != URL_SCHEME_WILDCARD)) {
3203             if(data->scheme_type == URL_SCHEME_WILDCARD)
3204                 FIXME("Here\n");
3205
3206             if(!computeOnly) {
3207                 INT pos = uri->canon_len;
3208
3209                 uri->canon_uri[pos] = '/';
3210                 uri->canon_uri[pos+1] = '/';
3211            }
3212            uri->canon_len += 2;
3213         }
3214
3215         if(!canonicalize_authority(data, uri, flags, computeOnly))
3216             return FALSE;
3217
3218         if(data->is_relative && (data->password || data->username)) {
3219             if(!canonicalize_path_opaque(data, uri, flags, computeOnly))
3220                 return FALSE;
3221         } else {
3222             if(!canonicalize_path_hierarchical(data, uri, flags, computeOnly))
3223                 return FALSE;
3224         }
3225     } else {
3226         /* Opaque URI's don't have an authority. */
3227         uri->userinfo_start = uri->userinfo_split = -1;
3228         uri->userinfo_len = 0;
3229         uri->host_start = -1;
3230         uri->host_len = 0;
3231         uri->host_type = Uri_HOST_UNKNOWN;
3232         uri->has_port = FALSE;
3233         uri->authority_start = -1;
3234         uri->authority_len = 0;
3235         uri->domain_offset = -1;
3236         uri->port_offset = -1;
3237
3238         if(is_hierarchical_scheme(data->scheme_type)) {
3239             DWORD i;
3240
3241             /* Absolute URIs aren't displayed for known scheme types
3242              * which should be hierarchical URIs.
3243              */
3244             uri->display_modifiers |= URI_DISPLAY_NO_ABSOLUTE_URI;
3245
3246             /* Windows also sets the port for these (if they have one). */
3247             for(i = 0; i < sizeof(default_ports)/sizeof(default_ports[0]); ++i) {
3248                 if(data->scheme_type == default_ports[i].scheme) {
3249                     uri->has_port = TRUE;
3250                     uri->port = default_ports[i].port;
3251                     break;
3252                 }
3253             }
3254         }
3255
3256         if(!canonicalize_path_opaque(data, uri, flags, computeOnly))
3257             return FALSE;
3258     }
3259
3260     if(uri->path_start > -1 && !computeOnly)
3261         /* Finding file extensions happens for both types of URIs. */
3262         uri->extension_offset = find_file_extension(uri->canon_uri+uri->path_start, uri->path_len);
3263     else
3264         uri->extension_offset = -1;
3265
3266     return TRUE;
3267 }
3268
3269 /* Attempts to canonicalize the query string of the URI.
3270  *
3271  * Things that happen:
3272  *  1)  For known scheme types forbidden characters
3273  *      are percent encoded, unless the NO_DECODE_EXTRA_INFO flag is set
3274  *      or NO_ENCODE_FORBIDDEN_CHARACTERS is set.
3275  *
3276  *  2)  For known scheme types, percent encoded, unreserved characters
3277  *      are decoded as long as the NO_DECODE_EXTRA_INFO flag isn't set.
3278  */
3279 static BOOL canonicalize_query(const parse_data *data, Uri *uri, DWORD flags, BOOL computeOnly) {
3280     const WCHAR *ptr, *end;
3281     const BOOL known_scheme = data->scheme_type != URL_SCHEME_UNKNOWN;
3282
3283     if(!data->query) {
3284         uri->query_start = -1;
3285         uri->query_len = 0;
3286         return TRUE;
3287     }
3288
3289     uri->query_start = uri->canon_len;
3290
3291     end = data->query+data->query_len;
3292     for(ptr = data->query; ptr < end; ++ptr) {
3293         if(*ptr == '%') {
3294             if(known_scheme && !(flags & Uri_CREATE_NO_DECODE_EXTRA_INFO)) {
3295                 WCHAR val = decode_pct_val(ptr);
3296                 if(is_unreserved(val)) {
3297                     if(!computeOnly)
3298                         uri->canon_uri[uri->canon_len] = val;
3299                     ++uri->canon_len;
3300
3301                     ptr += 2;
3302                     continue;
3303                 }
3304             }
3305         } else if(known_scheme && !is_unreserved(*ptr) && !is_reserved(*ptr)) {
3306             if(!(flags & Uri_CREATE_NO_ENCODE_FORBIDDEN_CHARACTERS) &&
3307                !(flags & Uri_CREATE_NO_DECODE_EXTRA_INFO)) {
3308                 if(!computeOnly)
3309                     pct_encode_val(*ptr, uri->canon_uri+uri->canon_len);
3310                 uri->canon_len += 3;
3311                 continue;
3312             }
3313         }
3314
3315         if(!computeOnly)
3316             uri->canon_uri[uri->canon_len] = *ptr;
3317         ++uri->canon_len;
3318     }
3319
3320     uri->query_len = uri->canon_len - uri->query_start;
3321
3322     if(!computeOnly)
3323         TRACE("(%p %p %x %d): Canonicalized query string %s len=%d\n", data, uri, flags,
3324             computeOnly, debugstr_wn(uri->canon_uri+uri->query_start, uri->query_len),
3325             uri->query_len);
3326     return TRUE;
3327 }
3328
3329 static BOOL canonicalize_fragment(const parse_data *data, Uri *uri, DWORD flags, BOOL computeOnly) {
3330     const WCHAR *ptr, *end;
3331     const BOOL known_scheme = data->scheme_type != URL_SCHEME_UNKNOWN;
3332
3333     if(!data->fragment) {
3334         uri->fragment_start = -1;
3335         uri->fragment_len = 0;
3336         return TRUE;
3337     }
3338
3339     uri->fragment_start = uri->canon_len;
3340
3341     end = data->fragment + data->fragment_len;
3342     for(ptr = data->fragment; ptr < end; ++ptr) {
3343         if(*ptr == '%') {
3344             if(known_scheme && !(flags & Uri_CREATE_NO_DECODE_EXTRA_INFO)) {
3345                 WCHAR val = decode_pct_val(ptr);
3346                 if(is_unreserved(val)) {
3347                     if(!computeOnly)
3348                         uri->canon_uri[uri->canon_len] = val;
3349                     ++uri->canon_len;
3350
3351                     ptr += 2;
3352                     continue;
3353                 }
3354             }
3355         } else if(known_scheme && !is_unreserved(*ptr) && !is_reserved(*ptr)) {
3356             if(!(flags & Uri_CREATE_NO_ENCODE_FORBIDDEN_CHARACTERS) &&
3357                !(flags & Uri_CREATE_NO_DECODE_EXTRA_INFO)) {
3358                 if(!computeOnly)
3359                     pct_encode_val(*ptr, uri->canon_uri+uri->canon_len);
3360                 uri->canon_len += 3;
3361                 continue;
3362             }
3363         }
3364
3365         if(!computeOnly)
3366             uri->canon_uri[uri->canon_len] = *ptr;
3367         ++uri->canon_len;
3368     }
3369
3370     uri->fragment_len = uri->canon_len - uri->fragment_start;
3371
3372     if(!computeOnly)
3373         TRACE("(%p %p %x %d): Canonicalized fragment %s len=%d\n", data, uri, flags,
3374             computeOnly, debugstr_wn(uri->canon_uri+uri->fragment_start, uri->fragment_len),
3375             uri->fragment_len);
3376     return TRUE;
3377 }
3378
3379 /* Canonicalizes the scheme information specified in the parse_data using the specified flags. */
3380 static BOOL canonicalize_scheme(const parse_data *data, Uri *uri, DWORD flags, BOOL computeOnly) {
3381     uri->scheme_start = -1;
3382     uri->scheme_len = 0;
3383
3384     if(!data->scheme) {
3385         /* The only type of URI that doesn't have to have a scheme is a relative
3386          * URI.
3387          */
3388         if(!data->is_relative) {
3389             FIXME("(%p %p %x): Unable to determine the scheme type of %s.\n", data,
3390                     uri, flags, debugstr_w(data->uri));
3391             return FALSE;
3392         }
3393     } else {
3394         if(!computeOnly) {
3395             DWORD i;
3396             INT pos = uri->canon_len;
3397
3398             for(i = 0; i < data->scheme_len; ++i) {
3399                 /* Scheme name must be lower case after canonicalization. */
3400                 uri->canon_uri[i + pos] = tolowerW(data->scheme[i]);
3401             }
3402
3403             uri->canon_uri[i + pos] = ':';
3404             uri->scheme_start = pos;
3405
3406             TRACE("(%p %p %x): Canonicalized scheme=%s, len=%d.\n", data, uri, flags,
3407                     debugstr_wn(uri->canon_uri,  uri->scheme_len), data->scheme_len);
3408         }
3409
3410         /* This happens in both computation modes. */
3411         uri->canon_len += data->scheme_len + 1;
3412         uri->scheme_len = data->scheme_len;
3413     }
3414     return TRUE;
3415 }
3416
3417 /* Computes what the length of the URI specified by the parse_data will be
3418  * after canonicalization occurs using the specified flags.
3419  *
3420  * This function will return a non-zero value indicating the length of the canonicalized
3421  * URI, or -1 on error.
3422  */
3423 static int compute_canonicalized_length(const parse_data *data, DWORD flags) {
3424     Uri uri;
3425
3426     memset(&uri, 0, sizeof(Uri));
3427
3428     TRACE("(%p %x): Beginning to compute canonicalized length for URI %s\n", data, flags,
3429             debugstr_w(data->uri));
3430
3431     if(!canonicalize_scheme(data, &uri, flags, TRUE)) {
3432         ERR("(%p %x): Failed to compute URI scheme length.\n", data, flags);
3433         return -1;
3434     }
3435
3436     if(!canonicalize_hierpart(data, &uri, flags, TRUE)) {
3437         ERR("(%p %x): Failed to compute URI hierpart length.\n", data, flags);
3438         return -1;
3439     }
3440
3441     if(!canonicalize_query(data, &uri, flags, TRUE)) {
3442         ERR("(%p %x): Failed to compute query string length.\n", data, flags);
3443         return -1;
3444     }
3445
3446     if(!canonicalize_fragment(data, &uri, flags, TRUE)) {
3447         ERR("(%p %x): Failed to compute fragment length.\n", data, flags);
3448         return -1;
3449     }
3450
3451     TRACE("(%p %x): Finished computing canonicalized URI length. length=%d\n", data, flags, uri.canon_len);
3452
3453     return uri.canon_len;
3454 }
3455
3456 /* Canonicalizes the URI data specified in the parse_data, using the given flags. If the
3457  * canonicalization succeeds it will store all the canonicalization information
3458  * in the pointer to the Uri.
3459  *
3460  * To canonicalize a URI this function first computes what the length of the URI
3461  * specified by the parse_data will be. Once this is done it will then perform the actual
3462  * canonicalization of the URI.
3463  */
3464 static HRESULT canonicalize_uri(const parse_data *data, Uri *uri, DWORD flags) {
3465     INT len;
3466
3467     uri->canon_uri = NULL;
3468     uri->canon_size = uri->canon_len = 0;
3469
3470     TRACE("(%p %p %x): beginning to canonicalize URI %s.\n", data, uri, flags, debugstr_w(data->uri));
3471
3472     /* First try to compute the length of the URI. */
3473     len = compute_canonicalized_length(data, flags);
3474     if(len == -1) {
3475         ERR("(%p %p %x): Could not compute the canonicalized length of %s.\n", data, uri, flags,
3476                 debugstr_w(data->uri));
3477         return E_INVALIDARG;
3478     }
3479
3480     uri->canon_uri = heap_alloc((len+1)*sizeof(WCHAR));
3481     if(!uri->canon_uri)
3482         return E_OUTOFMEMORY;
3483
3484     uri->canon_size = len;
3485     if(!canonicalize_scheme(data, uri, flags, FALSE)) {
3486         ERR("(%p %p %x): Unable to canonicalize the scheme of the URI.\n", data, uri, flags);
3487         return E_INVALIDARG;
3488     }
3489     uri->scheme_type = data->scheme_type;
3490
3491     if(!canonicalize_hierpart(data, uri, flags, FALSE)) {
3492         ERR("(%p %p %x): Unable to canonicalize the heirpart of the URI\n", data, uri, flags);
3493         return E_INVALIDARG;
3494     }
3495
3496     if(!canonicalize_query(data, uri, flags, FALSE)) {
3497         ERR("(%p %p %x): Unable to canonicalize query string of the URI.\n",
3498             data, uri, flags);
3499         return E_INVALIDARG;
3500     }
3501
3502     if(!canonicalize_fragment(data, uri, flags, FALSE)) {
3503         ERR("(%p %p %x): Unable to canonicalize fragment of the URI.\n",
3504             data, uri, flags);
3505         return E_INVALIDARG;
3506     }
3507
3508     /* There's a possibility we didn't use all the space we allocated
3509      * earlier.
3510      */
3511     if(uri->canon_len < uri->canon_size) {
3512         /* This happens if the URI is hierarchical and dot
3513          * segments were removed from its path.
3514          */
3515         WCHAR *tmp = heap_realloc(uri->canon_uri, (uri->canon_len+1)*sizeof(WCHAR));
3516         if(!tmp)
3517             return E_OUTOFMEMORY;
3518
3519         uri->canon_uri = tmp;
3520         uri->canon_size = uri->canon_len;
3521     }
3522
3523     uri->canon_uri[uri->canon_len] = '\0';
3524     TRACE("(%p %p %x): finished canonicalizing the URI. uri=%s\n", data, uri, flags, debugstr_w(uri->canon_uri));
3525
3526     return S_OK;
3527 }
3528
3529 static HRESULT get_builder_component(LPWSTR *component, DWORD *component_len,
3530                                      LPCWSTR source, DWORD source_len,
3531                                      LPCWSTR *output, DWORD *output_len)
3532 {
3533     if(!output_len) {
3534         if(output)
3535             *output = NULL;
3536         return E_POINTER;
3537     }
3538
3539     if(!output) {
3540         *output_len = 0;
3541         return E_POINTER;
3542     }
3543
3544     if(!(*component) && source) {
3545         /* Allocate 'component', and copy the contents from 'source'
3546          * into the new allocation.
3547          */
3548         *component = heap_alloc((source_len+1)*sizeof(WCHAR));
3549         if(!(*component))
3550             return E_OUTOFMEMORY;
3551
3552         memcpy(*component, source, source_len*sizeof(WCHAR));
3553         (*component)[source_len] = '\0';
3554         *component_len = source_len;
3555     }
3556
3557     *output = *component;
3558     *output_len = *component_len;
3559     return *output ? S_OK : S_FALSE;
3560 }
3561
3562 /* Allocates 'component' and copies the string from 'new_value' into 'component'.
3563  * If 'prefix' is set and 'new_value' isn't NULL, then it checks if 'new_value'
3564  * starts with 'prefix'. If it doesn't then 'prefix' is prepended to 'component'.
3565  *
3566  * If everything is successful, then will set 'success_flag' in 'flags'.
3567  */
3568 static HRESULT set_builder_component(LPWSTR *component, DWORD *component_len, LPCWSTR new_value,
3569                                      WCHAR prefix, DWORD *flags, DWORD success_flag)
3570 {
3571     heap_free(*component);
3572
3573     if(!new_value) {
3574         *component = NULL;
3575         *component_len = 0;
3576     } else {
3577         BOOL add_prefix = FALSE;
3578         DWORD len = lstrlenW(new_value);
3579         DWORD pos = 0;
3580
3581         if(prefix && *new_value != prefix) {
3582             add_prefix = TRUE;
3583             *component = heap_alloc((len+2)*sizeof(WCHAR));
3584         } else
3585             *component = heap_alloc((len+1)*sizeof(WCHAR));
3586
3587         if(!(*component))
3588             return E_OUTOFMEMORY;
3589
3590         if(add_prefix)
3591             (*component)[pos++] = prefix;
3592
3593         memcpy(*component+pos, new_value, (len+1)*sizeof(WCHAR));
3594         *component_len = len+pos;
3595     }
3596
3597     *flags |= success_flag;
3598     return S_OK;
3599 }
3600
3601 static void reset_builder(UriBuilder *builder) {
3602     if(builder->uri)
3603         IUri_Release(&builder->uri->IUri_iface);
3604     builder->uri = NULL;
3605
3606     heap_free(builder->fragment);
3607     builder->fragment = NULL;
3608     builder->fragment_len = 0;
3609
3610     heap_free(builder->host);
3611     builder->host = NULL;
3612     builder->host_len = 0;
3613
3614     heap_free(builder->password);
3615     builder->password = NULL;
3616     builder->password_len = 0;
3617
3618     heap_free(builder->path);
3619     builder->path = NULL;
3620     builder->path_len = 0;
3621
3622     heap_free(builder->query);
3623     builder->query = NULL;
3624     builder->query_len = 0;
3625
3626     heap_free(builder->scheme);
3627     builder->scheme = NULL;
3628     builder->scheme_len = 0;
3629
3630     heap_free(builder->username);
3631     builder->username = NULL;
3632     builder->username_len = 0;
3633
3634     builder->has_port = FALSE;
3635     builder->port = 0;
3636     builder->modified_props = 0;
3637 }
3638
3639 static HRESULT validate_scheme_name(const UriBuilder *builder, parse_data *data, DWORD flags) {
3640     const WCHAR *component;
3641     const WCHAR *ptr;
3642     const WCHAR **pptr;
3643     DWORD expected_len;
3644
3645     if(builder->scheme) {
3646         ptr = builder->scheme;
3647         expected_len = builder->scheme_len;
3648     } else if(builder->uri && builder->uri->scheme_start > -1) {
3649         ptr = builder->uri->canon_uri+builder->uri->scheme_start;
3650         expected_len = builder->uri->scheme_len;
3651     } else {
3652         static const WCHAR nullW[] = {0};
3653         ptr = nullW;
3654         expected_len = 0;
3655     }
3656
3657     component = ptr;
3658     pptr = &ptr;
3659     if(parse_scheme(pptr, data, flags, ALLOW_NULL_TERM_SCHEME) &&
3660        data->scheme_len == expected_len) {
3661         if(data->scheme)
3662             TRACE("(%p %p %x): Found valid scheme component %s len=%d.\n", builder, data, flags,
3663                debugstr_wn(data->scheme, data->scheme_len), data->scheme_len);
3664     } else {
3665         TRACE("(%p %p %x): Invalid scheme component found %s.\n", builder, data, flags,
3666             debugstr_wn(component, expected_len));
3667         return INET_E_INVALID_URL;
3668    }
3669
3670     return S_OK;
3671 }
3672
3673 static HRESULT validate_username(const UriBuilder *builder, parse_data *data, DWORD flags) {
3674     const WCHAR *ptr;
3675     const WCHAR **pptr;
3676     DWORD expected_len;
3677
3678     if(builder->username) {
3679         ptr = builder->username;
3680         expected_len = builder->username_len;
3681     } else if(!(builder->modified_props & Uri_HAS_USER_NAME) && builder->uri &&
3682               builder->uri->userinfo_start > -1 && builder->uri->userinfo_split != 0) {
3683         /* Just use the username from the base Uri. */
3684         data->username = builder->uri->canon_uri+builder->uri->userinfo_start;
3685         data->username_len = (builder->uri->userinfo_split > -1) ?
3686                                         builder->uri->userinfo_split : builder->uri->userinfo_len;
3687         ptr = NULL;
3688     } else {
3689         ptr = NULL;
3690         expected_len = 0;
3691     }
3692
3693     if(ptr) {
3694         const WCHAR *component = ptr;
3695         pptr = &ptr;
3696         if(parse_username(pptr, data, flags, ALLOW_NULL_TERM_USER_NAME) &&
3697            data->username_len == expected_len)
3698             TRACE("(%p %p %x): Found valid username component %s len=%d.\n", builder, data, flags,
3699                 debugstr_wn(data->username, data->username_len), data->username_len);
3700         else {
3701             TRACE("(%p %p %x): Invalid username component found %s.\n", builder, data, flags,
3702                 debugstr_wn(component, expected_len));
3703             return INET_E_INVALID_URL;
3704         }
3705     }
3706
3707     return S_OK;
3708 }
3709
3710 static HRESULT validate_password(const UriBuilder *builder, parse_data *data, DWORD flags) {
3711     const WCHAR *ptr;
3712     const WCHAR **pptr;
3713     DWORD expected_len;
3714
3715     if(builder->password) {
3716         ptr = builder->password;
3717         expected_len = builder->password_len;
3718     } else if(!(builder->modified_props & Uri_HAS_PASSWORD) && builder->uri &&
3719               builder->uri->userinfo_split > -1) {
3720         data->password = builder->uri->canon_uri+builder->uri->userinfo_start+builder->uri->userinfo_split+1;
3721         data->password_len = builder->uri->userinfo_len-builder->uri->userinfo_split-1;
3722         ptr = NULL;
3723     } else {
3724         ptr = NULL;
3725         expected_len = 0;
3726     }
3727
3728     if(ptr) {
3729         const WCHAR *component = ptr;
3730         pptr = &ptr;
3731         if(parse_password(pptr, data, flags, ALLOW_NULL_TERM_PASSWORD) &&
3732            data->password_len == expected_len)
3733             TRACE("(%p %p %x): Found valid password component %s len=%d.\n", builder, data, flags,
3734                 debugstr_wn(data->password, data->password_len), data->password_len);
3735         else {
3736             TRACE("(%p %p %x): Invalid password component found %s.\n", builder, data, flags,
3737                 debugstr_wn(component, expected_len));
3738             return INET_E_INVALID_URL;
3739         }
3740     }
3741
3742     return S_OK;
3743 }
3744
3745 static HRESULT validate_userinfo(const UriBuilder *builder, parse_data *data, DWORD flags) {
3746     HRESULT hr;
3747
3748     hr = validate_username(builder, data, flags);
3749     if(FAILED(hr))
3750         return hr;
3751
3752     hr = validate_password(builder, data, flags);
3753     if(FAILED(hr))
3754         return hr;
3755
3756     return S_OK;
3757 }
3758
3759 static HRESULT validate_host(const UriBuilder *builder, parse_data *data, DWORD flags) {
3760     const WCHAR *ptr;
3761     const WCHAR **pptr;
3762     DWORD expected_len;
3763
3764     if(builder->host) {
3765         ptr = builder->host;
3766         expected_len = builder->host_len;
3767     } else if(!(builder->modified_props & Uri_HAS_HOST) && builder->uri && builder->uri->host_start > -1) {
3768         ptr = builder->uri->canon_uri + builder->uri->host_start;
3769         expected_len = builder->uri->host_len;
3770     } else
3771         ptr = NULL;
3772
3773     if(ptr) {
3774         const WCHAR *component = ptr;
3775         DWORD extras = ALLOW_BRACKETLESS_IP_LITERAL|IGNORE_PORT_DELIMITER|SKIP_IP_FUTURE_CHECK;
3776         pptr = &ptr;
3777
3778         if(parse_host(pptr, data, flags, extras) && data->host_len == expected_len)
3779             TRACE("(%p %p %x): Found valid host name %s len=%d type=%d.\n", builder, data, flags,
3780                 debugstr_wn(data->host, data->host_len), data->host_len, data->host_type);
3781         else {
3782             TRACE("(%p %p %x): Invalid host name found %s.\n", builder, data, flags,
3783                 debugstr_wn(component, expected_len));
3784             return INET_E_INVALID_URL;
3785         }
3786     }
3787
3788     return S_OK;
3789 }
3790
3791 static void setup_port(const UriBuilder *builder, parse_data *data, DWORD flags) {
3792     if(builder->modified_props & Uri_HAS_PORT) {
3793         if(builder->has_port) {
3794             data->has_port = TRUE;
3795             data->port_value = builder->port;
3796         }
3797     } else if(builder->uri && builder->uri->has_port) {
3798         data->has_port = TRUE;
3799         data->port_value = builder->uri->port;
3800     }
3801
3802     if(data->has_port)
3803         TRACE("(%p %p %x): Using %u as port for IUri.\n", builder, data, flags, data->port_value);
3804 }
3805
3806 static HRESULT validate_path(const UriBuilder *builder, parse_data *data, DWORD flags) {
3807     const WCHAR *ptr = NULL;
3808     const WCHAR *component;
3809     const WCHAR **pptr;
3810     DWORD expected_len;
3811     BOOL check_len = TRUE;
3812     BOOL valid = FALSE;
3813
3814     if(builder->path) {
3815         ptr = builder->path;
3816         expected_len = builder->path_len;
3817     } else if(!(builder->modified_props & Uri_HAS_PATH) &&
3818               builder->uri && builder->uri->path_start > -1) {
3819         ptr = builder->uri->canon_uri+builder->uri->path_start;
3820         expected_len = builder->uri->path_len;
3821     } else {
3822         static const WCHAR nullW[] = {0};
3823         ptr = nullW;
3824         check_len = FALSE;
3825         expected_len = -1;
3826     }
3827
3828     component = ptr;
3829     pptr = &ptr;
3830
3831     /* How the path is validated depends on what type of
3832      * URI it is.
3833      */
3834     valid = data->is_opaque ?
3835         parse_path_opaque(pptr, data, flags) : parse_path_hierarchical(pptr, data, flags);
3836
3837     if(!valid || (check_len && expected_len != data->path_len)) {
3838         TRACE("(%p %p %x): Invalid path component %s.\n", builder, data, flags,
3839             debugstr_wn(component, expected_len) );
3840         return INET_E_INVALID_URL;
3841     }
3842
3843     TRACE("(%p %p %x): Valid path component %s len=%d.\n", builder, data, flags,
3844         debugstr_wn(data->path, data->path_len), data->path_len);
3845
3846     return S_OK;
3847 }
3848
3849 static HRESULT validate_query(const UriBuilder *builder, parse_data *data, DWORD flags) {
3850     const WCHAR *ptr = NULL;
3851     const WCHAR **pptr;
3852     DWORD expected_len;
3853
3854     if(builder->query) {
3855         ptr = builder->query;
3856         expected_len = builder->query_len;
3857     } else if(!(builder->modified_props & Uri_HAS_QUERY) && builder->uri &&
3858               builder->uri->query_start > -1) {
3859         ptr = builder->uri->canon_uri+builder->uri->query_start;
3860         expected_len = builder->uri->query_len;
3861     }
3862
3863     if(ptr) {
3864         const WCHAR *component = ptr;
3865         pptr = &ptr;
3866
3867         if(parse_query(pptr, data, flags) && expected_len == data->query_len)
3868             TRACE("(%p %p %x): Valid query component %s len=%d.\n", builder, data, flags,
3869                 debugstr_wn(data->query, data->query_len), data->query_len);
3870         else {
3871             TRACE("(%p %p %x): Invalid query component %s.\n", builder, data, flags,
3872                 debugstr_wn(component, expected_len));
3873             return INET_E_INVALID_URL;
3874         }
3875     }
3876
3877     return S_OK;
3878 }
3879
3880 static HRESULT validate_fragment(const UriBuilder *builder, parse_data *data, DWORD flags) {
3881     const WCHAR *ptr = NULL;
3882     const WCHAR **pptr;
3883     DWORD expected_len;
3884
3885     if(builder->fragment) {
3886         ptr = builder->fragment;
3887         expected_len = builder->fragment_len;
3888     } else if(!(builder->modified_props & Uri_HAS_FRAGMENT) && builder->uri &&
3889               builder->uri->fragment_start > -1) {
3890         ptr = builder->uri->canon_uri+builder->uri->fragment_start;
3891         expected_len = builder->uri->fragment_len;
3892     }
3893
3894     if(ptr) {
3895         const WCHAR *component = ptr;
3896         pptr = &ptr;
3897
3898         if(parse_fragment(pptr, data, flags) && expected_len == data->fragment_len)
3899             TRACE("(%p %p %x): Valid fragment component %s len=%d.\n", builder, data, flags,
3900                 debugstr_wn(data->fragment, data->fragment_len), data->fragment_len);
3901         else {
3902             TRACE("(%p %p %x): Invalid fragment component %s.\n", builder, data, flags,
3903                 debugstr_wn(component, expected_len));
3904             return INET_E_INVALID_URL;
3905         }
3906     }
3907
3908     return S_OK;
3909 }
3910
3911 static HRESULT validate_components(const UriBuilder *builder, parse_data *data, DWORD flags) {
3912     HRESULT hr;
3913
3914     memset(data, 0, sizeof(parse_data));
3915
3916     TRACE("(%p %p %x): Beginning to validate builder components.\n", builder, data, flags);
3917
3918     hr = validate_scheme_name(builder, data, flags);
3919     if(FAILED(hr))
3920         return hr;
3921
3922     /* Extra validation for file schemes. */
3923     if(data->scheme_type == URL_SCHEME_FILE) {
3924         if((builder->password || (builder->uri && builder->uri->userinfo_split > -1)) ||
3925            (builder->username || (builder->uri && builder->uri->userinfo_start > -1))) {
3926             TRACE("(%p %p %x): File schemes can't contain a username or password.\n",
3927                 builder, data, flags);
3928             return INET_E_INVALID_URL;
3929         }
3930     }
3931
3932     hr = validate_userinfo(builder, data, flags);
3933     if(FAILED(hr))
3934         return hr;
3935
3936     hr = validate_host(builder, data, flags);
3937     if(FAILED(hr))
3938         return hr;
3939
3940     setup_port(builder, data, flags);
3941
3942     /* The URI is opaque if it doesn't have an authority component. */
3943     if(!data->is_relative)
3944         data->is_opaque = !data->username && !data->password && !data->host && !data->has_port
3945             && data->scheme_type != URL_SCHEME_FILE;
3946     else
3947         data->is_opaque = !data->host && !data->has_port;
3948
3949     hr = validate_path(builder, data, flags);
3950     if(FAILED(hr))
3951         return hr;
3952
3953     hr = validate_query(builder, data, flags);
3954     if(FAILED(hr))
3955         return hr;
3956
3957     hr = validate_fragment(builder, data, flags);
3958     if(FAILED(hr))
3959         return hr;
3960
3961     TRACE("(%p %p %x): Finished validating builder components.\n", builder, data, flags);
3962
3963     return S_OK;
3964 }
3965
3966 static void convert_to_dos_path(const WCHAR *path, DWORD path_len,
3967                                 WCHAR *output, DWORD *output_len)
3968 {
3969     const WCHAR *ptr = path;
3970
3971     if(path_len > 3 && *ptr == '/' && is_drive_path(path+1))
3972         /* Skip over the leading / before the drive path. */
3973         ++ptr;
3974
3975     for(; ptr < path+path_len; ++ptr) {
3976         if(*ptr == '/') {
3977             if(output)
3978                 *output++ = '\\';
3979             (*output_len)++;
3980         } else {
3981             if(output)
3982                 *output++ = *ptr;
3983             (*output_len)++;
3984         }
3985     }
3986 }
3987
3988 /* Generates a raw uri string using the parse_data. */
3989 static DWORD generate_raw_uri(const parse_data *data, BSTR uri, DWORD flags) {
3990     DWORD length = 0;
3991
3992     if(data->scheme) {
3993         if(uri) {
3994             memcpy(uri, data->scheme, data->scheme_len*sizeof(WCHAR));
3995             uri[data->scheme_len] = ':';
3996         }
3997         length += data->scheme_len+1;
3998     }
3999
4000     if(!data->is_opaque) {
4001         /* For the "//" which appears before the authority component. */
4002         if(uri) {
4003             uri[length] = '/';
4004             uri[length+1] = '/';
4005         }
4006         length += 2;
4007
4008         /* Check if we need to add the "\\" before the host name
4009          * of a UNC server name in a DOS path.
4010          */
4011         if(flags & RAW_URI_CONVERT_TO_DOS_PATH &&
4012            data->scheme_type == URL_SCHEME_FILE && data->host) {
4013             if(uri) {
4014                 uri[length] = '\\';
4015                 uri[length+1] = '\\';
4016             }
4017             length += 2;
4018         }
4019     }
4020
4021     if(data->username) {
4022         if(uri)
4023             memcpy(uri+length, data->username, data->username_len*sizeof(WCHAR));
4024         length += data->username_len;
4025     }
4026
4027     if(data->password) {
4028         if(uri) {
4029             uri[length] = ':';
4030             memcpy(uri+length+1, data->password, data->password_len*sizeof(WCHAR));
4031         }
4032         length += data->password_len+1;
4033     }
4034
4035     if(data->password || data->username) {
4036         if(uri)
4037             uri[length] = '@';
4038         ++length;
4039     }
4040
4041     if(data->host) {
4042         /* IPv6 addresses get the brackets added around them if they don't already
4043          * have them.
4044          */
4045         const BOOL add_brackets = data->host_type == Uri_HOST_IPV6 && *(data->host) != '[';
4046         if(add_brackets) {
4047             if(uri)
4048                 uri[length] = '[';
4049             ++length;
4050         }
4051
4052         if(uri)
4053             memcpy(uri+length, data->host, data->host_len*sizeof(WCHAR));
4054         length += data->host_len;
4055
4056         if(add_brackets) {
4057             if(uri)
4058                 uri[length] = ']';
4059             length++;
4060         }
4061     }
4062
4063     if(data->has_port) {
4064         /* The port isn't included in the raw uri if it's the default
4065          * port for the scheme type.
4066          */
4067         DWORD i;
4068         BOOL is_default = FALSE;
4069
4070         for(i = 0; i < sizeof(default_ports)/sizeof(default_ports[0]); ++i) {
4071             if(data->scheme_type == default_ports[i].scheme &&
4072                data->port_value == default_ports[i].port)
4073                 is_default = TRUE;
4074         }
4075
4076         if(!is_default || flags & RAW_URI_FORCE_PORT_DISP) {
4077             if(uri)
4078                 uri[length] = ':';
4079             ++length;
4080
4081             if(uri)
4082                 length += ui2str(uri+length, data->port_value);
4083             else
4084                 length += ui2str(NULL, data->port_value);
4085         }
4086     }
4087
4088     /* Check if a '/' should be added before the path for hierarchical URIs. */
4089     if(!data->is_opaque && data->path && *(data->path) != '/') {
4090         if(uri)
4091             uri[length] = '/';
4092         ++length;
4093     }
4094
4095     if(data->path) {
4096         if(!data->is_opaque && data->scheme_type == URL_SCHEME_FILE &&
4097            flags & RAW_URI_CONVERT_TO_DOS_PATH) {
4098             DWORD len = 0;
4099
4100             if(uri)
4101                 convert_to_dos_path(data->path, data->path_len, uri+length, &len);
4102             else
4103                 convert_to_dos_path(data->path, data->path_len, NULL, &len);
4104
4105             length += len;
4106         } else {
4107             if(uri)
4108                 memcpy(uri+length, data->path, data->path_len*sizeof(WCHAR));
4109             length += data->path_len;
4110         }
4111     }
4112
4113     if(data->query) {
4114         if(uri)
4115             memcpy(uri+length, data->query, data->query_len*sizeof(WCHAR));
4116         length += data->query_len;
4117     }
4118
4119     if(data->fragment) {
4120         if(uri)
4121             memcpy(uri+length, data->fragment, data->fragment_len*sizeof(WCHAR));
4122         length += data->fragment_len;
4123     }
4124
4125     if(uri)
4126         TRACE("(%p %p): Generated raw uri=%s len=%d\n", data, uri, debugstr_wn(uri, length), length);
4127     else
4128         TRACE("(%p %p): Computed raw uri len=%d\n", data, uri, length);
4129
4130     return length;
4131 }
4132
4133 static HRESULT generate_uri(const UriBuilder *builder, const parse_data *data, Uri *uri, DWORD flags) {
4134     HRESULT hr;
4135     DWORD length = generate_raw_uri(data, NULL, 0);
4136     uri->raw_uri = SysAllocStringLen(NULL, length);
4137     if(!uri->raw_uri)
4138         return E_OUTOFMEMORY;
4139
4140     generate_raw_uri(data, uri->raw_uri, 0);
4141
4142     hr = canonicalize_uri(data, uri, flags);
4143     if(FAILED(hr)) {
4144         if(hr == E_INVALIDARG)
4145             return INET_E_INVALID_URL;
4146         return hr;
4147     }
4148
4149     uri->create_flags = flags;
4150     return S_OK;
4151 }
4152
4153 static inline Uri* impl_from_IUri(IUri *iface)
4154 {
4155     return CONTAINING_RECORD(iface, Uri, IUri_iface);
4156 }
4157
4158 static inline void destory_uri_obj(Uri *This)
4159 {
4160     SysFreeString(This->raw_uri);
4161     heap_free(This->canon_uri);
4162     heap_free(This);
4163 }
4164
4165 static HRESULT WINAPI Uri_QueryInterface(IUri *iface, REFIID riid, void **ppv)
4166 {
4167     Uri *This = impl_from_IUri(iface);
4168
4169     if(IsEqualGUID(&IID_IUnknown, riid)) {
4170         TRACE("(%p)->(IID_IUnknown %p)\n", This, ppv);
4171         *ppv = &This->IUri_iface;
4172     }else if(IsEqualGUID(&IID_IUri, riid)) {
4173         TRACE("(%p)->(IID_IUri %p)\n", This, ppv);
4174         *ppv = &This->IUri_iface;
4175     }else if(IsEqualGUID(&IID_IUriBuilderFactory, riid)) {
4176         TRACE("(%p)->(IID_IUriBuilderFactory %p)\n", This, riid);
4177         *ppv = &This->IUriBuilderFactory_iface;
4178     }else if(IsEqualGUID(&IID_IUriObj, riid)) {
4179         TRACE("(%p)->(IID_IUriObj %p)\n", This, ppv);
4180         *ppv = This;
4181         return S_OK;
4182     }else {
4183         TRACE("(%p)->(%s %p)\n", This, debugstr_guid(riid), ppv);
4184         *ppv = NULL;
4185         return E_NOINTERFACE;
4186     }
4187
4188     IUnknown_AddRef((IUnknown*)*ppv);
4189     return S_OK;
4190 }
4191
4192 static ULONG WINAPI Uri_AddRef(IUri *iface)
4193 {
4194     Uri *This = impl_from_IUri(iface);
4195     LONG ref = InterlockedIncrement(&This->ref);
4196
4197     TRACE("(%p) ref=%d\n", This, ref);
4198
4199     return ref;
4200 }
4201
4202 static ULONG WINAPI Uri_Release(IUri *iface)
4203 {
4204     Uri *This = impl_from_IUri(iface);
4205     LONG ref = InterlockedDecrement(&This->ref);
4206
4207     TRACE("(%p) ref=%d\n", This, ref);
4208
4209     if(!ref)
4210         destory_uri_obj(This);
4211
4212     return ref;
4213 }
4214
4215 static HRESULT WINAPI Uri_GetPropertyBSTR(IUri *iface, Uri_PROPERTY uriProp, BSTR *pbstrProperty, DWORD dwFlags)
4216 {
4217     Uri *This = impl_from_IUri(iface);
4218     HRESULT hres;
4219     TRACE("(%p %s)->(%d %p %x)\n", This, debugstr_w(This->canon_uri), uriProp, pbstrProperty, dwFlags);
4220
4221     if(!pbstrProperty)
4222         return E_POINTER;
4223
4224     if(uriProp > Uri_PROPERTY_STRING_LAST) {
4225         /* Windows allocates an empty BSTR for invalid Uri_PROPERTY's. */
4226         *pbstrProperty = SysAllocStringLen(NULL, 0);
4227         if(!(*pbstrProperty))
4228             return E_OUTOFMEMORY;
4229
4230         /* It only returns S_FALSE for the ZONE property... */
4231         if(uriProp == Uri_PROPERTY_ZONE)
4232             return S_FALSE;
4233         else
4234             return S_OK;
4235     }
4236
4237     /* Don't have support for flags yet. */
4238     if(dwFlags) {
4239         FIXME("(%p)->(%d %p %x)\n", This, uriProp, pbstrProperty, dwFlags);
4240         return E_NOTIMPL;
4241     }
4242
4243     switch(uriProp) {
4244     case Uri_PROPERTY_ABSOLUTE_URI:
4245         if(This->display_modifiers & URI_DISPLAY_NO_ABSOLUTE_URI) {
4246             *pbstrProperty = SysAllocStringLen(NULL, 0);
4247             hres = S_FALSE;
4248         } else {
4249             if(This->scheme_type != URL_SCHEME_UNKNOWN && This->userinfo_start > -1) {
4250                 if(This->userinfo_len == 0) {
4251                     /* Don't include the '@' after the userinfo component. */
4252                     *pbstrProperty = SysAllocStringLen(NULL, This->canon_len-1);
4253                     hres = S_OK;
4254                     if(*pbstrProperty) {
4255                         /* Copy everything before it. */
4256                         memcpy(*pbstrProperty, This->canon_uri, This->userinfo_start*sizeof(WCHAR));
4257
4258                         /* And everything after it. */
4259                         memcpy(*pbstrProperty+This->userinfo_start, This->canon_uri+This->userinfo_start+1,
4260                                (This->canon_len-This->userinfo_start-1)*sizeof(WCHAR));
4261                     }
4262                 } else if(This->userinfo_split == 0 && This->userinfo_len == 1) {
4263                     /* Don't include the ":@" */
4264                     *pbstrProperty = SysAllocStringLen(NULL, This->canon_len-2);
4265                     hres = S_OK;
4266                     if(*pbstrProperty) {
4267                         memcpy(*pbstrProperty, This->canon_uri, This->userinfo_start*sizeof(WCHAR));
4268                         memcpy(*pbstrProperty+This->userinfo_start, This->canon_uri+This->userinfo_start+2,
4269                                (This->canon_len-This->userinfo_start-2)*sizeof(WCHAR));
4270                     }
4271                 } else {
4272                     *pbstrProperty = SysAllocString(This->canon_uri);
4273                     hres = S_OK;
4274                 }
4275             } else {
4276                 *pbstrProperty = SysAllocString(This->canon_uri);
4277                 hres = S_OK;
4278             }
4279         }
4280
4281         if(!(*pbstrProperty))
4282             hres = E_OUTOFMEMORY;
4283
4284         break;
4285     case Uri_PROPERTY_AUTHORITY:
4286         if(This->authority_start > -1) {
4287             if(This->port_offset > -1 && is_default_port(This->scheme_type, This->port) &&
4288                This->display_modifiers & URI_DISPLAY_NO_DEFAULT_PORT_AUTH)
4289                 /* Don't include the port in the authority component. */
4290                 *pbstrProperty = SysAllocStringLen(This->canon_uri+This->authority_start, This->port_offset);
4291             else
4292                 *pbstrProperty = SysAllocStringLen(This->canon_uri+This->authority_start, This->authority_len);
4293             hres = S_OK;
4294         } else {
4295             *pbstrProperty = SysAllocStringLen(NULL, 0);
4296             hres = S_FALSE;
4297         }
4298
4299         if(!(*pbstrProperty))
4300             hres = E_OUTOFMEMORY;
4301
4302         break;
4303     case Uri_PROPERTY_DISPLAY_URI:
4304         /* The Display URI contains everything except for the userinfo for known
4305          * scheme types.
4306          */
4307         if(This->scheme_type != URL_SCHEME_UNKNOWN && This->userinfo_start > -1) {
4308             *pbstrProperty = SysAllocStringLen(NULL, This->canon_len-This->userinfo_len);
4309
4310             if(*pbstrProperty) {
4311                 /* Copy everything before the userinfo over. */
4312                 memcpy(*pbstrProperty, This->canon_uri, This->userinfo_start*sizeof(WCHAR));
4313                 /* Copy everything after the userinfo over. */
4314                 memcpy(*pbstrProperty+This->userinfo_start,
4315                    This->canon_uri+This->userinfo_start+This->userinfo_len+1,
4316                    (This->canon_len-(This->userinfo_start+This->userinfo_len+1))*sizeof(WCHAR));
4317             }
4318         } else
4319             *pbstrProperty = SysAllocString(This->canon_uri);
4320
4321         if(!(*pbstrProperty))
4322             hres = E_OUTOFMEMORY;
4323         else
4324             hres = S_OK;
4325
4326         break;
4327     case Uri_PROPERTY_DOMAIN:
4328         if(This->domain_offset > -1) {
4329             *pbstrProperty = SysAllocStringLen(This->canon_uri+This->host_start+This->domain_offset,
4330                                                This->host_len-This->domain_offset);
4331             hres = S_OK;
4332         } else {
4333             *pbstrProperty = SysAllocStringLen(NULL, 0);
4334             hres = S_FALSE;
4335         }
4336
4337         if(!(*pbstrProperty))
4338             hres = E_OUTOFMEMORY;
4339
4340         break;
4341     case Uri_PROPERTY_EXTENSION:
4342         if(This->extension_offset > -1) {
4343             *pbstrProperty = SysAllocStringLen(This->canon_uri+This->path_start+This->extension_offset,
4344                                                This->path_len-This->extension_offset);
4345             hres = S_OK;
4346         } else {
4347             *pbstrProperty = SysAllocStringLen(NULL, 0);
4348             hres = S_FALSE;
4349         }
4350
4351         if(!(*pbstrProperty))
4352             hres = E_OUTOFMEMORY;
4353
4354         break;
4355     case Uri_PROPERTY_FRAGMENT:
4356         if(This->fragment_start > -1) {
4357             *pbstrProperty = SysAllocStringLen(This->canon_uri+This->fragment_start, This->fragment_len);
4358             hres = S_OK;
4359         } else {
4360             *pbstrProperty = SysAllocStringLen(NULL, 0);
4361             hres = S_FALSE;
4362         }
4363
4364         if(!(*pbstrProperty))
4365             hres = E_OUTOFMEMORY;
4366
4367         break;
4368     case Uri_PROPERTY_HOST:
4369         if(This->host_start > -1) {
4370             /* The '[' and ']' aren't included for IPv6 addresses. */
4371             if(This->host_type == Uri_HOST_IPV6)
4372                 *pbstrProperty = SysAllocStringLen(This->canon_uri+This->host_start+1, This->host_len-2);
4373             else
4374                 *pbstrProperty = SysAllocStringLen(This->canon_uri+This->host_start, This->host_len);
4375
4376             hres = S_OK;
4377         } else {
4378             *pbstrProperty = SysAllocStringLen(NULL, 0);
4379             hres = S_FALSE;
4380         }
4381
4382         if(!(*pbstrProperty))
4383             hres = E_OUTOFMEMORY;
4384
4385         break;
4386     case Uri_PROPERTY_PASSWORD:
4387         if(This->userinfo_split > -1) {
4388             *pbstrProperty = SysAllocStringLen(
4389                 This->canon_uri+This->userinfo_start+This->userinfo_split+1,
4390                 This->userinfo_len-This->userinfo_split-1);
4391             hres = S_OK;
4392         } else {
4393             *pbstrProperty = SysAllocStringLen(NULL, 0);
4394             hres = S_FALSE;
4395         }
4396
4397         if(!(*pbstrProperty))
4398             return E_OUTOFMEMORY;
4399
4400         break;
4401     case Uri_PROPERTY_PATH:
4402         if(This->path_start > -1) {
4403             *pbstrProperty = SysAllocStringLen(This->canon_uri+This->path_start, This->path_len);
4404             hres = S_OK;
4405         } else {
4406             *pbstrProperty = SysAllocStringLen(NULL, 0);
4407             hres = S_FALSE;
4408         }
4409
4410         if(!(*pbstrProperty))
4411             hres = E_OUTOFMEMORY;
4412
4413         break;
4414     case Uri_PROPERTY_PATH_AND_QUERY:
4415         if(This->path_start > -1) {
4416             *pbstrProperty = SysAllocStringLen(This->canon_uri+This->path_start, This->path_len+This->query_len);
4417             hres = S_OK;
4418         } else if(This->query_start > -1) {
4419             *pbstrProperty = SysAllocStringLen(This->canon_uri+This->query_start, This->query_len);
4420             hres = S_OK;
4421         } else {
4422             *pbstrProperty = SysAllocStringLen(NULL, 0);
4423             hres = S_FALSE;
4424         }
4425
4426         if(!(*pbstrProperty))
4427             hres = E_OUTOFMEMORY;
4428
4429         break;
4430     case Uri_PROPERTY_QUERY:
4431         if(This->query_start > -1) {
4432             *pbstrProperty = SysAllocStringLen(This->canon_uri+This->query_start, This->query_len);
4433             hres = S_OK;
4434         } else {
4435             *pbstrProperty = SysAllocStringLen(NULL, 0);
4436             hres = S_FALSE;
4437         }
4438
4439         if(!(*pbstrProperty))
4440             hres = E_OUTOFMEMORY;
4441
4442         break;
4443     case Uri_PROPERTY_RAW_URI:
4444         *pbstrProperty = SysAllocString(This->raw_uri);
4445         if(!(*pbstrProperty))
4446             hres = E_OUTOFMEMORY;
4447         else
4448             hres = S_OK;
4449         break;
4450     case Uri_PROPERTY_SCHEME_NAME:
4451         if(This->scheme_start > -1) {
4452             *pbstrProperty = SysAllocStringLen(This->canon_uri + This->scheme_start, This->scheme_len);
4453             hres = S_OK;
4454         } else {
4455             *pbstrProperty = SysAllocStringLen(NULL, 0);
4456             hres = S_FALSE;
4457         }
4458
4459         if(!(*pbstrProperty))
4460             hres = E_OUTOFMEMORY;
4461
4462         break;
4463     case Uri_PROPERTY_USER_INFO:
4464         if(This->userinfo_start > -1) {
4465             *pbstrProperty = SysAllocStringLen(This->canon_uri+This->userinfo_start, This->userinfo_len);
4466             hres = S_OK;
4467         } else {
4468             *pbstrProperty = SysAllocStringLen(NULL, 0);
4469             hres = S_FALSE;
4470         }
4471
4472         if(!(*pbstrProperty))
4473             hres = E_OUTOFMEMORY;
4474
4475         break;
4476     case Uri_PROPERTY_USER_NAME:
4477         if(This->userinfo_start > -1 && This->userinfo_split != 0) {
4478             /* If userinfo_split is set, that means a password exists
4479              * so the username is only from userinfo_start to userinfo_split.
4480              */
4481             if(This->userinfo_split > -1) {
4482                 *pbstrProperty = SysAllocStringLen(This->canon_uri + This->userinfo_start, This->userinfo_split);
4483                 hres = S_OK;
4484             } else {
4485                 *pbstrProperty = SysAllocStringLen(This->canon_uri + This->userinfo_start, This->userinfo_len);
4486                 hres = S_OK;
4487             }
4488         } else {
4489             *pbstrProperty = SysAllocStringLen(NULL, 0);
4490             hres = S_FALSE;
4491         }
4492
4493         if(!(*pbstrProperty))
4494             return E_OUTOFMEMORY;
4495
4496         break;
4497     default:
4498         FIXME("(%p)->(%d %p %x)\n", This, uriProp, pbstrProperty, dwFlags);
4499         hres = E_NOTIMPL;
4500     }
4501
4502     return hres;
4503 }
4504
4505 static HRESULT WINAPI Uri_GetPropertyLength(IUri *iface, Uri_PROPERTY uriProp, DWORD *pcchProperty, DWORD dwFlags)
4506 {
4507     Uri *This = impl_from_IUri(iface);
4508     HRESULT hres;
4509     TRACE("(%p %s)->(%d %p %x)\n", This, debugstr_w(This->canon_uri), uriProp, pcchProperty, dwFlags);
4510
4511     if(!pcchProperty)
4512         return E_INVALIDARG;
4513
4514     /* Can only return a length for a property if it's a string. */
4515     if(uriProp > Uri_PROPERTY_STRING_LAST)
4516         return E_INVALIDARG;
4517
4518     /* Don't have support for flags yet. */
4519     if(dwFlags) {
4520         FIXME("(%p)->(%d %p %x)\n", This, uriProp, pcchProperty, dwFlags);
4521         return E_NOTIMPL;
4522     }
4523
4524     switch(uriProp) {
4525     case Uri_PROPERTY_ABSOLUTE_URI:
4526         if(This->display_modifiers & URI_DISPLAY_NO_ABSOLUTE_URI) {
4527             *pcchProperty = 0;
4528             hres = S_FALSE;
4529         } else {
4530             if(This->scheme_type != URL_SCHEME_UNKNOWN) {
4531                 if(This->userinfo_start > -1 && This->userinfo_len == 0)
4532                     /* Don't include the '@' in the length. */
4533                     *pcchProperty = This->canon_len-1;
4534                 else if(This->userinfo_start > -1 && This->userinfo_len == 1 &&
4535                         This->userinfo_split == 0)
4536                     /* Don't include the ":@" in the length. */
4537                     *pcchProperty = This->canon_len-2;
4538                 else
4539                     *pcchProperty = This->canon_len;
4540             } else
4541                 *pcchProperty = This->canon_len;
4542
4543             hres = S_OK;
4544         }
4545
4546         break;
4547     case Uri_PROPERTY_AUTHORITY:
4548         if(This->port_offset > -1 &&
4549            This->display_modifiers & URI_DISPLAY_NO_DEFAULT_PORT_AUTH &&
4550            is_default_port(This->scheme_type, This->port))
4551             /* Only count up until the port in the authority. */
4552             *pcchProperty = This->port_offset;
4553         else
4554             *pcchProperty = This->authority_len;
4555         hres = (This->authority_start > -1) ? S_OK : S_FALSE;
4556         break;
4557     case Uri_PROPERTY_DISPLAY_URI:
4558         if(This->scheme_type != URL_SCHEME_UNKNOWN && This->userinfo_start > -1)
4559             *pcchProperty = This->canon_len-This->userinfo_len-1;
4560         else
4561             *pcchProperty = This->canon_len;
4562
4563         hres = S_OK;
4564         break;
4565     case Uri_PROPERTY_DOMAIN:
4566         if(This->domain_offset > -1)
4567             *pcchProperty = This->host_len - This->domain_offset;
4568         else
4569             *pcchProperty = 0;
4570
4571         hres = (This->domain_offset > -1) ? S_OK : S_FALSE;
4572         break;
4573     case Uri_PROPERTY_EXTENSION:
4574         if(This->extension_offset > -1) {
4575             *pcchProperty = This->path_len - This->extension_offset;
4576             hres = S_OK;
4577         } else {
4578             *pcchProperty = 0;
4579             hres = S_FALSE;
4580         }
4581
4582         break;
4583     case Uri_PROPERTY_FRAGMENT:
4584         *pcchProperty = This->fragment_len;
4585         hres = (This->fragment_start > -1) ? S_OK : S_FALSE;
4586         break;
4587     case Uri_PROPERTY_HOST:
4588         *pcchProperty = This->host_len;
4589
4590         /* '[' and ']' aren't included in the length. */
4591         if(This->host_type == Uri_HOST_IPV6)
4592             *pcchProperty -= 2;
4593
4594         hres = (This->host_start > -1) ? S_OK : S_FALSE;
4595         break;
4596     case Uri_PROPERTY_PASSWORD:
4597         *pcchProperty = (This->userinfo_split > -1) ? This->userinfo_len-This->userinfo_split-1 : 0;
4598         hres = (This->userinfo_split > -1) ? S_OK : S_FALSE;
4599         break;
4600     case Uri_PROPERTY_PATH:
4601         *pcchProperty = This->path_len;
4602         hres = (This->path_start > -1) ? S_OK : S_FALSE;
4603         break;
4604     case Uri_PROPERTY_PATH_AND_QUERY:
4605         *pcchProperty = This->path_len+This->query_len;
4606         hres = (This->path_start > -1 || This->query_start > -1) ? S_OK : S_FALSE;
4607         break;
4608     case Uri_PROPERTY_QUERY:
4609         *pcchProperty = This->query_len;
4610         hres = (This->query_start > -1) ? S_OK : S_FALSE;
4611         break;
4612     case Uri_PROPERTY_RAW_URI:
4613         *pcchProperty = SysStringLen(This->raw_uri);
4614         hres = S_OK;
4615         break;
4616     case Uri_PROPERTY_SCHEME_NAME:
4617         *pcchProperty = This->scheme_len;
4618         hres = (This->scheme_start > -1) ? S_OK : S_FALSE;
4619         break;
4620     case Uri_PROPERTY_USER_INFO:
4621         *pcchProperty = This->userinfo_len;
4622         hres = (This->userinfo_start > -1) ? S_OK : S_FALSE;
4623         break;
4624     case Uri_PROPERTY_USER_NAME:
4625         *pcchProperty = (This->userinfo_split > -1) ? This->userinfo_split : This->userinfo_len;
4626         if(This->userinfo_split == 0)
4627             hres = S_FALSE;
4628         else
4629             hres = (This->userinfo_start > -1) ? S_OK : S_FALSE;
4630         break;
4631     default:
4632         FIXME("(%p)->(%d %p %x)\n", This, uriProp, pcchProperty, dwFlags);
4633         hres = E_NOTIMPL;
4634     }
4635
4636     return hres;
4637 }
4638
4639 static HRESULT WINAPI Uri_GetPropertyDWORD(IUri *iface, Uri_PROPERTY uriProp, DWORD *pcchProperty, DWORD dwFlags)
4640 {
4641     Uri *This = impl_from_IUri(iface);
4642     HRESULT hres;
4643
4644     TRACE("(%p %s)->(%d %p %x)\n", This, debugstr_w(This->canon_uri), uriProp, pcchProperty, dwFlags);
4645
4646     if(!pcchProperty)
4647         return E_INVALIDARG;
4648
4649     /* Microsoft's implementation for the ZONE property of a URI seems to be lacking...
4650      * From what I can tell, instead of checking which URLZONE the URI belongs to it
4651      * simply assigns URLZONE_INVALID and returns E_NOTIMPL. This also applies to the GetZone
4652      * function.
4653      */
4654     if(uriProp == Uri_PROPERTY_ZONE) {
4655         *pcchProperty = URLZONE_INVALID;
4656         return E_NOTIMPL;
4657     }
4658
4659     if(uriProp < Uri_PROPERTY_DWORD_START) {
4660         *pcchProperty = 0;
4661         return E_INVALIDARG;
4662     }
4663
4664     switch(uriProp) {
4665     case Uri_PROPERTY_HOST_TYPE:
4666         *pcchProperty = This->host_type;
4667         hres = S_OK;
4668         break;
4669     case Uri_PROPERTY_PORT:
4670         if(!This->has_port) {
4671             *pcchProperty = 0;
4672             hres = S_FALSE;
4673         } else {
4674             *pcchProperty = This->port;
4675             hres = S_OK;
4676         }
4677
4678         break;
4679     case Uri_PROPERTY_SCHEME:
4680         *pcchProperty = This->scheme_type;
4681         hres = S_OK;
4682         break;
4683     default:
4684         FIXME("(%p)->(%d %p %x)\n", This, uriProp, pcchProperty, dwFlags);
4685         hres = E_NOTIMPL;
4686     }
4687
4688     return hres;
4689 }
4690
4691 static HRESULT WINAPI Uri_HasProperty(IUri *iface, Uri_PROPERTY uriProp, BOOL *pfHasProperty)
4692 {
4693     Uri *This = impl_from_IUri(iface);
4694
4695     TRACE("(%p %s)->(%d %p)\n", This, debugstr_w(This->canon_uri), uriProp, pfHasProperty);
4696
4697     if(!pfHasProperty)
4698         return E_INVALIDARG;
4699
4700     switch(uriProp) {
4701     case Uri_PROPERTY_ABSOLUTE_URI:
4702         *pfHasProperty = !(This->display_modifiers & URI_DISPLAY_NO_ABSOLUTE_URI);
4703         break;
4704     case Uri_PROPERTY_AUTHORITY:
4705         *pfHasProperty = This->authority_start > -1;
4706         break;
4707     case Uri_PROPERTY_DISPLAY_URI:
4708         *pfHasProperty = TRUE;
4709         break;
4710     case Uri_PROPERTY_DOMAIN:
4711         *pfHasProperty = This->domain_offset > -1;
4712         break;
4713     case Uri_PROPERTY_EXTENSION:
4714         *pfHasProperty = This->extension_offset > -1;
4715         break;
4716     case Uri_PROPERTY_FRAGMENT:
4717         *pfHasProperty = This->fragment_start > -1;
4718         break;
4719     case Uri_PROPERTY_HOST:
4720         *pfHasProperty = This->host_start > -1;
4721         break;
4722     case Uri_PROPERTY_PASSWORD:
4723         *pfHasProperty = This->userinfo_split > -1;
4724         break;
4725     case Uri_PROPERTY_PATH:
4726         *pfHasProperty = This->path_start > -1;
4727         break;
4728     case Uri_PROPERTY_PATH_AND_QUERY:
4729         *pfHasProperty = (This->path_start > -1 || This->query_start > -1);
4730         break;
4731     case Uri_PROPERTY_QUERY:
4732         *pfHasProperty = This->query_start > -1;
4733         break;
4734     case Uri_PROPERTY_RAW_URI:
4735         *pfHasProperty = TRUE;
4736         break;
4737     case Uri_PROPERTY_SCHEME_NAME:
4738         *pfHasProperty = This->scheme_start > -1;
4739         break;
4740     case Uri_PROPERTY_USER_INFO:
4741         *pfHasProperty = This->userinfo_start > -1;
4742         break;
4743     case Uri_PROPERTY_USER_NAME:
4744         if(This->userinfo_split == 0)
4745             *pfHasProperty = FALSE;
4746         else
4747             *pfHasProperty = This->userinfo_start > -1;
4748         break;
4749     case Uri_PROPERTY_HOST_TYPE:
4750         *pfHasProperty = TRUE;
4751         break;
4752     case Uri_PROPERTY_PORT:
4753         *pfHasProperty = This->has_port;
4754         break;
4755     case Uri_PROPERTY_SCHEME:
4756         *pfHasProperty = TRUE;
4757         break;
4758     case Uri_PROPERTY_ZONE:
4759         *pfHasProperty = FALSE;
4760         break;
4761     default:
4762         FIXME("(%p)->(%d %p): Unsupported property type.\n", This, uriProp, pfHasProperty);
4763         return E_NOTIMPL;
4764     }
4765
4766     return S_OK;
4767 }
4768
4769 static HRESULT WINAPI Uri_GetAbsoluteUri(IUri *iface, BSTR *pstrAbsoluteUri)
4770 {
4771     TRACE("(%p)->(%p)\n", iface, pstrAbsoluteUri);
4772     return IUri_GetPropertyBSTR(iface, Uri_PROPERTY_ABSOLUTE_URI, pstrAbsoluteUri, 0);
4773 }
4774
4775 static HRESULT WINAPI Uri_GetAuthority(IUri *iface, BSTR *pstrAuthority)
4776 {
4777     TRACE("(%p)->(%p)\n", iface, pstrAuthority);
4778     return IUri_GetPropertyBSTR(iface, Uri_PROPERTY_AUTHORITY, pstrAuthority, 0);
4779 }
4780
4781 static HRESULT WINAPI Uri_GetDisplayUri(IUri *iface, BSTR *pstrDisplayUri)
4782 {
4783     TRACE("(%p)->(%p)\n", iface, pstrDisplayUri);
4784     return IUri_GetPropertyBSTR(iface, Uri_PROPERTY_DISPLAY_URI, pstrDisplayUri, 0);
4785 }
4786
4787 static HRESULT WINAPI Uri_GetDomain(IUri *iface, BSTR *pstrDomain)
4788 {
4789     TRACE("(%p)->(%p)\n", iface, pstrDomain);
4790     return IUri_GetPropertyBSTR(iface, Uri_PROPERTY_DOMAIN, pstrDomain, 0);
4791 }
4792
4793 static HRESULT WINAPI Uri_GetExtension(IUri *iface, BSTR *pstrExtension)
4794 {
4795     TRACE("(%p)->(%p)\n", iface, pstrExtension);
4796     return IUri_GetPropertyBSTR(iface, Uri_PROPERTY_EXTENSION, pstrExtension, 0);
4797 }
4798
4799 static HRESULT WINAPI Uri_GetFragment(IUri *iface, BSTR *pstrFragment)
4800 {
4801     TRACE("(%p)->(%p)\n", iface, pstrFragment);
4802     return IUri_GetPropertyBSTR(iface, Uri_PROPERTY_FRAGMENT, pstrFragment, 0);
4803 }
4804
4805 static HRESULT WINAPI Uri_GetHost(IUri *iface, BSTR *pstrHost)
4806 {
4807     TRACE("(%p)->(%p)\n", iface, pstrHost);
4808     return IUri_GetPropertyBSTR(iface, Uri_PROPERTY_HOST, pstrHost, 0);
4809 }
4810
4811 static HRESULT WINAPI Uri_GetPassword(IUri *iface, BSTR *pstrPassword)
4812 {
4813     TRACE("(%p)->(%p)\n", iface, pstrPassword);
4814     return IUri_GetPropertyBSTR(iface, Uri_PROPERTY_PASSWORD, pstrPassword, 0);
4815 }
4816
4817 static HRESULT WINAPI Uri_GetPath(IUri *iface, BSTR *pstrPath)
4818 {
4819     TRACE("(%p)->(%p)\n", iface, pstrPath);
4820     return IUri_GetPropertyBSTR(iface, Uri_PROPERTY_PATH, pstrPath, 0);
4821 }
4822
4823 static HRESULT WINAPI Uri_GetPathAndQuery(IUri *iface, BSTR *pstrPathAndQuery)
4824 {
4825     TRACE("(%p)->(%p)\n", iface, pstrPathAndQuery);
4826     return IUri_GetPropertyBSTR(iface, Uri_PROPERTY_PATH_AND_QUERY, pstrPathAndQuery, 0);
4827 }
4828
4829 static HRESULT WINAPI Uri_GetQuery(IUri *iface, BSTR *pstrQuery)
4830 {
4831     TRACE("(%p)->(%p)\n", iface, pstrQuery);
4832     return IUri_GetPropertyBSTR(iface, Uri_PROPERTY_QUERY, pstrQuery, 0);
4833 }
4834
4835 static HRESULT WINAPI Uri_GetRawUri(IUri *iface, BSTR *pstrRawUri)
4836 {
4837     TRACE("(%p)->(%p)\n", iface, pstrRawUri);
4838     return IUri_GetPropertyBSTR(iface, Uri_PROPERTY_RAW_URI, pstrRawUri, 0);
4839 }
4840
4841 static HRESULT WINAPI Uri_GetSchemeName(IUri *iface, BSTR *pstrSchemeName)
4842 {
4843     TRACE("(%p)->(%p)\n", iface, pstrSchemeName);
4844     return IUri_GetPropertyBSTR(iface, Uri_PROPERTY_SCHEME_NAME, pstrSchemeName, 0);
4845 }
4846
4847 static HRESULT WINAPI Uri_GetUserInfo(IUri *iface, BSTR *pstrUserInfo)
4848 {
4849     TRACE("(%p)->(%p)\n", iface, pstrUserInfo);
4850     return IUri_GetPropertyBSTR(iface, Uri_PROPERTY_USER_INFO, pstrUserInfo, 0);
4851 }
4852
4853 static HRESULT WINAPI Uri_GetUserName(IUri *iface, BSTR *pstrUserName)
4854 {
4855     TRACE("(%p)->(%p)\n", iface, pstrUserName);
4856     return IUri_GetPropertyBSTR(iface, Uri_PROPERTY_USER_NAME, pstrUserName, 0);
4857 }
4858
4859 static HRESULT WINAPI Uri_GetHostType(IUri *iface, DWORD *pdwHostType)
4860 {
4861     TRACE("(%p)->(%p)\n", iface, pdwHostType);
4862     return IUri_GetPropertyDWORD(iface, Uri_PROPERTY_HOST_TYPE, pdwHostType, 0);
4863 }
4864
4865 static HRESULT WINAPI Uri_GetPort(IUri *iface, DWORD *pdwPort)
4866 {
4867     TRACE("(%p)->(%p)\n", iface, pdwPort);
4868     return IUri_GetPropertyDWORD(iface, Uri_PROPERTY_PORT, pdwPort, 0);
4869 }
4870
4871 static HRESULT WINAPI Uri_GetScheme(IUri *iface, DWORD *pdwScheme)
4872 {
4873     TRACE("(%p)->(%p)\n", iface, pdwScheme);
4874     return IUri_GetPropertyDWORD(iface, Uri_PROPERTY_SCHEME, pdwScheme, 0);
4875 }
4876
4877 static HRESULT WINAPI Uri_GetZone(IUri *iface, DWORD *pdwZone)
4878 {
4879     TRACE("(%p)->(%p)\n", iface, pdwZone);
4880     return IUri_GetPropertyDWORD(iface, Uri_PROPERTY_ZONE,pdwZone, 0);
4881 }
4882
4883 static HRESULT WINAPI Uri_GetProperties(IUri *iface, DWORD *pdwProperties)
4884 {
4885     Uri *This = impl_from_IUri(iface);
4886     TRACE("(%p %s)->(%p)\n", This, debugstr_w(This->canon_uri), pdwProperties);
4887
4888     if(!pdwProperties)
4889         return E_INVALIDARG;
4890
4891     /* All URIs have these. */
4892     *pdwProperties = Uri_HAS_DISPLAY_URI|Uri_HAS_RAW_URI|Uri_HAS_SCHEME|Uri_HAS_HOST_TYPE;
4893
4894     if(!(This->display_modifiers & URI_DISPLAY_NO_ABSOLUTE_URI))
4895         *pdwProperties |= Uri_HAS_ABSOLUTE_URI;
4896
4897     if(This->scheme_start > -1)
4898         *pdwProperties |= Uri_HAS_SCHEME_NAME;
4899
4900     if(This->authority_start > -1) {
4901         *pdwProperties |= Uri_HAS_AUTHORITY;
4902         if(This->userinfo_start > -1) {
4903             *pdwProperties |= Uri_HAS_USER_INFO;
4904             if(This->userinfo_split != 0)
4905                 *pdwProperties |= Uri_HAS_USER_NAME;
4906         }
4907         if(This->userinfo_split > -1)
4908             *pdwProperties |= Uri_HAS_PASSWORD;
4909         if(This->host_start > -1)
4910             *pdwProperties |= Uri_HAS_HOST;
4911         if(This->domain_offset > -1)
4912             *pdwProperties |= Uri_HAS_DOMAIN;
4913     }
4914
4915     if(This->has_port)
4916         *pdwProperties |= Uri_HAS_PORT;
4917     if(This->path_start > -1)
4918         *pdwProperties |= Uri_HAS_PATH|Uri_HAS_PATH_AND_QUERY;
4919     if(This->query_start > -1)
4920         *pdwProperties |= Uri_HAS_QUERY|Uri_HAS_PATH_AND_QUERY;
4921
4922     if(This->extension_offset > -1)
4923         *pdwProperties |= Uri_HAS_EXTENSION;
4924
4925     if(This->fragment_start > -1)
4926         *pdwProperties |= Uri_HAS_FRAGMENT;
4927
4928     return S_OK;
4929 }
4930
4931 static HRESULT WINAPI Uri_IsEqual(IUri *iface, IUri *pUri, BOOL *pfEqual)
4932 {
4933     Uri *This = impl_from_IUri(iface);
4934     Uri *other;
4935
4936     TRACE("(%p %s)->(%p %p)\n", This, debugstr_w(This->canon_uri), pUri, pfEqual);
4937
4938     if(!pfEqual)
4939         return E_POINTER;
4940
4941     if(!pUri) {
4942         *pfEqual = FALSE;
4943
4944         /* For some reason Windows returns S_OK here... */
4945         return S_OK;
4946     }
4947
4948     /* Try to convert it to a Uri (allows for a more simple comparison). */
4949     if((other = get_uri_obj(pUri))) {
4950         TRACE("comparing to %s\n", debugstr_w(other->canon_uri));
4951         *pfEqual = are_equal_simple(This, other);
4952     }else {
4953         /* Do it the hard way. */
4954         FIXME("(%p)->(%p %p) No support for unknown IUri's yet.\n", iface, pUri, pfEqual);
4955         return E_NOTIMPL;
4956     }
4957
4958     return S_OK;
4959 }
4960
4961 static const IUriVtbl UriVtbl = {
4962     Uri_QueryInterface,
4963     Uri_AddRef,
4964     Uri_Release,
4965     Uri_GetPropertyBSTR,
4966     Uri_GetPropertyLength,
4967     Uri_GetPropertyDWORD,
4968     Uri_HasProperty,
4969     Uri_GetAbsoluteUri,
4970     Uri_GetAuthority,
4971     Uri_GetDisplayUri,
4972     Uri_GetDomain,
4973     Uri_GetExtension,
4974     Uri_GetFragment,
4975     Uri_GetHost,
4976     Uri_GetPassword,
4977     Uri_GetPath,
4978     Uri_GetPathAndQuery,
4979     Uri_GetQuery,
4980     Uri_GetRawUri,
4981     Uri_GetSchemeName,
4982     Uri_GetUserInfo,
4983     Uri_GetUserName,
4984     Uri_GetHostType,
4985     Uri_GetPort,
4986     Uri_GetScheme,
4987     Uri_GetZone,
4988     Uri_GetProperties,
4989     Uri_IsEqual
4990 };
4991
4992 static inline Uri* impl_from_IUriBuilderFactory(IUriBuilderFactory *iface)
4993 {
4994     return CONTAINING_RECORD(iface, Uri, IUriBuilderFactory_iface);
4995 }
4996
4997 static HRESULT WINAPI UriBuilderFactory_QueryInterface(IUriBuilderFactory *iface, REFIID riid, void **ppv)
4998 {
4999     Uri *This = impl_from_IUriBuilderFactory(iface);
5000
5001     if(IsEqualGUID(&IID_IUnknown, riid)) {
5002         TRACE("(%p)->(IID_IUnknown %p)\n", This, ppv);
5003         *ppv = &This->IUriBuilderFactory_iface;
5004     }else if(IsEqualGUID(&IID_IUriBuilderFactory, riid)) {
5005         TRACE("(%p)->(IID_IUriBuilderFactory %p)\n", This, ppv);
5006         *ppv = &This->IUriBuilderFactory_iface;
5007     }else if(IsEqualGUID(&IID_IUri, riid)) {
5008         TRACE("(%p)->(IID_IUri %p)\n", This, ppv);
5009         *ppv = &This->IUri_iface;
5010     }else {
5011         TRACE("(%p)->(%s %p)\n", This, debugstr_guid(riid), ppv);
5012         *ppv = NULL;
5013         return E_NOINTERFACE;
5014     }
5015
5016     IUnknown_AddRef((IUnknown*)*ppv);
5017     return S_OK;
5018 }
5019
5020 static ULONG WINAPI UriBuilderFactory_AddRef(IUriBuilderFactory *iface)
5021 {
5022     Uri *This = impl_from_IUriBuilderFactory(iface);
5023     LONG ref = InterlockedIncrement(&This->ref);
5024
5025     TRACE("(%p) ref=%d\n", This, ref);
5026
5027     return ref;
5028 }
5029
5030 static ULONG WINAPI UriBuilderFactory_Release(IUriBuilderFactory *iface)
5031 {
5032     Uri *This = impl_from_IUriBuilderFactory(iface);
5033     LONG ref = InterlockedDecrement(&This->ref);
5034
5035     TRACE("(%p) ref=%d\n", This, ref);
5036
5037     if(!ref)
5038         destory_uri_obj(This);
5039
5040     return ref;
5041 }
5042
5043 static HRESULT WINAPI UriBuilderFactory_CreateIUriBuilder(IUriBuilderFactory *iface,
5044                                                           DWORD dwFlags,
5045                                                           DWORD_PTR dwReserved,
5046                                                           IUriBuilder **ppIUriBuilder)
5047 {
5048     Uri *This = impl_from_IUriBuilderFactory(iface);
5049     TRACE("(%p)->(%08x %08x %p)\n", This, dwFlags, (DWORD)dwReserved, ppIUriBuilder);
5050
5051     if(!ppIUriBuilder)
5052         return E_POINTER;
5053
5054     if(dwFlags || dwReserved) {
5055         *ppIUriBuilder = NULL;
5056         return E_INVALIDARG;
5057     }
5058
5059     return CreateIUriBuilder(NULL, 0, 0, ppIUriBuilder);
5060 }
5061
5062 static HRESULT WINAPI UriBuilderFactory_CreateInitializedIUriBuilder(IUriBuilderFactory *iface,
5063                                                                      DWORD dwFlags,
5064                                                                      DWORD_PTR dwReserved,
5065                                                                      IUriBuilder **ppIUriBuilder)
5066 {
5067     Uri *This = impl_from_IUriBuilderFactory(iface);
5068     TRACE("(%p)->(%08x %08x %p)\n", This, dwFlags, (DWORD)dwReserved, ppIUriBuilder);
5069
5070     if(!ppIUriBuilder)
5071         return E_POINTER;
5072
5073     if(dwFlags || dwReserved) {
5074         *ppIUriBuilder = NULL;
5075         return E_INVALIDARG;
5076     }
5077
5078     return CreateIUriBuilder(&This->IUri_iface, 0, 0, ppIUriBuilder);
5079 }
5080
5081 static const IUriBuilderFactoryVtbl UriBuilderFactoryVtbl = {
5082     UriBuilderFactory_QueryInterface,
5083     UriBuilderFactory_AddRef,
5084     UriBuilderFactory_Release,
5085     UriBuilderFactory_CreateIUriBuilder,
5086     UriBuilderFactory_CreateInitializedIUriBuilder
5087 };
5088
5089 static Uri* create_uri_obj(void) {
5090     Uri *ret = heap_alloc_zero(sizeof(Uri));
5091     if(ret) {
5092         ret->IUri_iface.lpVtbl = &UriVtbl;
5093         ret->IUriBuilderFactory_iface.lpVtbl = &UriBuilderFactoryVtbl;
5094         ret->ref = 1;
5095     }
5096
5097     return ret;
5098 }
5099
5100 /***********************************************************************
5101  *           CreateUri (urlmon.@)
5102  *
5103  * Creates a new IUri object using the URI represented by pwzURI. This function
5104  * parses and validates the components of pwzURI and then canonicalizes the
5105  * parsed components.
5106  *
5107  * PARAMS
5108  *  pwzURI      [I] The URI to parse, validate, and canonicalize.
5109  *  dwFlags     [I] Flags which can affect how the parsing/canonicalization is performed.
5110  *  dwReserved  [I] Reserved (not used).
5111  *  ppURI       [O] The resulting IUri after parsing/canonicalization occurs.
5112  *
5113  * RETURNS
5114  *  Success: Returns S_OK. ppURI contains the pointer to the newly allocated IUri.
5115  *  Failure: E_INVALIDARG if there are invalid flag combinations in dwFlags, or an
5116  *           invalid parameter, or pwzURI doesn't represent a valid URI.
5117  *           E_OUTOFMEMORY if any memory allocation fails.
5118  *
5119  * NOTES
5120  *  Default flags:
5121  *      Uri_CREATE_CANONICALIZE, Uri_CREATE_DECODE_EXTRA_INFO, Uri_CREATE_CRACK_UNKNOWN_SCHEMES,
5122  *      Uri_CREATE_PRE_PROCESS_HTML_URI, Uri_CREATE_NO_IE_SETTINGS.
5123  */
5124 HRESULT WINAPI CreateUri(LPCWSTR pwzURI, DWORD dwFlags, DWORD_PTR dwReserved, IUri **ppURI)
5125 {
5126     const DWORD supported_flags = Uri_CREATE_ALLOW_RELATIVE|Uri_CREATE_ALLOW_IMPLICIT_WILDCARD_SCHEME|
5127         Uri_CREATE_ALLOW_IMPLICIT_FILE_SCHEME|Uri_CREATE_NO_CANONICALIZE|Uri_CREATE_CANONICALIZE|
5128         Uri_CREATE_DECODE_EXTRA_INFO|Uri_CREATE_NO_DECODE_EXTRA_INFO|Uri_CREATE_CRACK_UNKNOWN_SCHEMES|
5129         Uri_CREATE_NO_CRACK_UNKNOWN_SCHEMES|Uri_CREATE_PRE_PROCESS_HTML_URI|Uri_CREATE_NO_PRE_PROCESS_HTML_URI|
5130         Uri_CREATE_NO_IE_SETTINGS|Uri_CREATE_NO_ENCODE_FORBIDDEN_CHARACTERS|Uri_CREATE_FILE_USE_DOS_PATH;
5131     Uri *ret;
5132     HRESULT hr;
5133     parse_data data;
5134
5135     TRACE("(%s %x %x %p)\n", debugstr_w(pwzURI), dwFlags, (DWORD)dwReserved, ppURI);
5136
5137     if(!ppURI)
5138         return E_INVALIDARG;
5139
5140     if(!pwzURI) {
5141         *ppURI = NULL;
5142         return E_INVALIDARG;
5143     }
5144
5145     /* Check for invalid flags. */
5146     if(has_invalid_flag_combination(dwFlags)) {
5147         *ppURI = NULL;
5148         return E_INVALIDARG;
5149     }
5150
5151     /* Currently unsupported. */
5152     if(dwFlags & ~supported_flags)
5153         FIXME("Ignoring unsupported flag(s) %x\n", dwFlags & ~supported_flags);
5154
5155     ret = create_uri_obj();
5156     if(!ret) {
5157         *ppURI = NULL;
5158         return E_OUTOFMEMORY;
5159     }
5160
5161     /* Explicitly set the default flags if it doesn't cause a flag conflict. */
5162     apply_default_flags(&dwFlags);
5163
5164     /* Pre process the URI, unless told otherwise. */
5165     if(!(dwFlags & Uri_CREATE_NO_PRE_PROCESS_HTML_URI))
5166         ret->raw_uri = pre_process_uri(pwzURI);
5167     else
5168         ret->raw_uri = SysAllocString(pwzURI);
5169
5170     if(!ret->raw_uri) {
5171         heap_free(ret);
5172         return E_OUTOFMEMORY;
5173     }
5174
5175     memset(&data, 0, sizeof(parse_data));
5176     data.uri = ret->raw_uri;
5177
5178     /* Validate and parse the URI into its components. */
5179     if(!parse_uri(&data, dwFlags)) {
5180         /* Encountered an unsupported or invalid URI */
5181         IUri_Release(&ret->IUri_iface);
5182         *ppURI = NULL;
5183         return E_INVALIDARG;
5184     }
5185
5186     /* Canonicalize the URI. */
5187     hr = canonicalize_uri(&data, ret, dwFlags);
5188     if(FAILED(hr)) {
5189         IUri_Release(&ret->IUri_iface);
5190         *ppURI = NULL;
5191         return hr;
5192     }
5193
5194     ret->create_flags = dwFlags;
5195
5196     *ppURI = &ret->IUri_iface;
5197     return S_OK;
5198 }
5199
5200 /***********************************************************************
5201  *           CreateUriWithFragment (urlmon.@)
5202  *
5203  * Creates a new IUri object. This is almost the same as CreateUri, expect that
5204  * it allows you to explicitly specify a fragment (pwzFragment) for pwzURI.
5205  *
5206  * PARAMS
5207  *  pwzURI      [I] The URI to parse and perform canonicalization on.
5208  *  pwzFragment [I] The explicit fragment string which should be added to pwzURI.
5209  *  dwFlags     [I] The flags which will be passed to CreateUri.
5210  *  dwReserved  [I] Reserved (not used).
5211  *  ppURI       [O] The resulting IUri after parsing/canonicalization.
5212  *
5213  * RETURNS
5214  *  Success: S_OK. ppURI contains the pointer to the newly allocated IUri.
5215  *  Failure: E_INVALIDARG if pwzURI already contains a fragment and pwzFragment
5216  *           isn't NULL. Will also return E_INVALIDARG for the same reasons as
5217  *           CreateUri will. E_OUTOFMEMORY if any allocation fails.
5218  */
5219 HRESULT WINAPI CreateUriWithFragment(LPCWSTR pwzURI, LPCWSTR pwzFragment, DWORD dwFlags,
5220                                      DWORD_PTR dwReserved, IUri **ppURI)
5221 {
5222     HRESULT hres;
5223     TRACE("(%s %s %x %x %p)\n", debugstr_w(pwzURI), debugstr_w(pwzFragment), dwFlags, (DWORD)dwReserved, ppURI);
5224
5225     if(!ppURI)
5226         return E_INVALIDARG;
5227
5228     if(!pwzURI) {
5229         *ppURI = NULL;
5230         return E_INVALIDARG;
5231     }
5232
5233     /* Check if a fragment should be appended to the URI string. */
5234     if(pwzFragment) {
5235         WCHAR *uriW;
5236         DWORD uri_len, frag_len;
5237         BOOL add_pound;
5238
5239         /* Check if the original URI already has a fragment component. */
5240         if(StrChrW(pwzURI, '#')) {
5241             *ppURI = NULL;
5242             return E_INVALIDARG;
5243         }
5244
5245         uri_len = lstrlenW(pwzURI);
5246         frag_len = lstrlenW(pwzFragment);
5247
5248         /* If the fragment doesn't start with a '#', one will be added. */
5249         add_pound = *pwzFragment != '#';
5250
5251         if(add_pound)
5252             uriW = heap_alloc((uri_len+frag_len+2)*sizeof(WCHAR));
5253         else
5254             uriW = heap_alloc((uri_len+frag_len+1)*sizeof(WCHAR));
5255
5256         if(!uriW)
5257             return E_OUTOFMEMORY;
5258
5259         memcpy(uriW, pwzURI, uri_len*sizeof(WCHAR));
5260         if(add_pound)
5261             uriW[uri_len++] = '#';
5262         memcpy(uriW+uri_len, pwzFragment, (frag_len+1)*sizeof(WCHAR));
5263
5264         hres = CreateUri(uriW, dwFlags, 0, ppURI);
5265
5266         heap_free(uriW);
5267     } else
5268         /* A fragment string wasn't specified, so just forward the call. */
5269         hres = CreateUri(pwzURI, dwFlags, 0, ppURI);
5270
5271     return hres;
5272 }
5273
5274 static HRESULT build_uri(const UriBuilder *builder, IUri **uri, DWORD create_flags,
5275                          DWORD use_orig_flags, DWORD encoding_mask)
5276 {
5277     HRESULT hr;
5278     parse_data data;
5279     Uri *ret;
5280
5281     if(!uri)
5282         return E_POINTER;
5283
5284     if(encoding_mask && (!builder->uri || builder->modified_props)) {
5285         *uri = NULL;
5286         return E_NOTIMPL;
5287     }
5288
5289     /* Decide what flags should be used when creating the Uri. */
5290     if((use_orig_flags & UriBuilder_USE_ORIGINAL_FLAGS) && builder->uri)
5291         create_flags = builder->uri->create_flags;
5292     else {
5293         if(has_invalid_flag_combination(create_flags)) {
5294             *uri = NULL;
5295             return E_INVALIDARG;
5296         }
5297
5298         /* Set the default flags if they don't cause a conflict. */
5299         apply_default_flags(&create_flags);
5300     }
5301
5302     /* Return the base IUri if no changes have been made and the create_flags match. */
5303     if(builder->uri && !builder->modified_props && builder->uri->create_flags == create_flags) {
5304         *uri = &builder->uri->IUri_iface;
5305         IUri_AddRef(*uri);
5306         return S_OK;
5307     }
5308
5309     hr = validate_components(builder, &data, create_flags);
5310     if(FAILED(hr)) {
5311         *uri = NULL;
5312         return hr;
5313     }
5314
5315     ret = create_uri_obj();
5316     if(!ret) {
5317         *uri = NULL;
5318         return E_OUTOFMEMORY;
5319     }
5320
5321     hr = generate_uri(builder, &data, ret, create_flags);
5322     if(FAILED(hr)) {
5323         IUri_Release(&ret->IUri_iface);
5324         *uri = NULL;
5325         return hr;
5326     }
5327
5328     *uri = &ret->IUri_iface;
5329     return S_OK;
5330 }
5331
5332 static inline UriBuilder* impl_from_IUriBuilder(IUriBuilder *iface)
5333 {
5334     return CONTAINING_RECORD(iface, UriBuilder, IUriBuilder_iface);
5335 }
5336
5337 static HRESULT WINAPI UriBuilder_QueryInterface(IUriBuilder *iface, REFIID riid, void **ppv)
5338 {
5339     UriBuilder *This = impl_from_IUriBuilder(iface);
5340
5341     if(IsEqualGUID(&IID_IUnknown, riid)) {
5342         TRACE("(%p)->(IID_IUnknown %p)\n", This, ppv);
5343         *ppv = &This->IUriBuilder_iface;
5344     }else if(IsEqualGUID(&IID_IUriBuilder, riid)) {
5345         TRACE("(%p)->(IID_IUriBuilder %p)\n", This, ppv);
5346         *ppv = &This->IUriBuilder_iface;
5347     }else {
5348         TRACE("(%p)->(%s %p)\n", This, debugstr_guid(riid), ppv);
5349         *ppv = NULL;
5350         return E_NOINTERFACE;
5351     }
5352
5353     IUnknown_AddRef((IUnknown*)*ppv);
5354     return S_OK;
5355 }
5356
5357 static ULONG WINAPI UriBuilder_AddRef(IUriBuilder *iface)
5358 {
5359     UriBuilder *This = impl_from_IUriBuilder(iface);
5360     LONG ref = InterlockedIncrement(&This->ref);
5361
5362     TRACE("(%p) ref=%d\n", This, ref);
5363
5364     return ref;
5365 }
5366
5367 static ULONG WINAPI UriBuilder_Release(IUriBuilder *iface)
5368 {
5369     UriBuilder *This = impl_from_IUriBuilder(iface);
5370     LONG ref = InterlockedDecrement(&This->ref);
5371
5372     TRACE("(%p) ref=%d\n", This, ref);
5373
5374     if(!ref) {
5375         if(This->uri) IUri_Release(&This->uri->IUri_iface);
5376         heap_free(This->fragment);
5377         heap_free(This->host);
5378         heap_free(This->password);
5379         heap_free(This->path);
5380         heap_free(This->query);
5381         heap_free(This->scheme);
5382         heap_free(This->username);
5383         heap_free(This);
5384     }
5385
5386     return ref;
5387 }
5388
5389 static HRESULT WINAPI UriBuilder_CreateUriSimple(IUriBuilder *iface,
5390                                                  DWORD        dwAllowEncodingPropertyMask,
5391                                                  DWORD_PTR    dwReserved,
5392                                                  IUri       **ppIUri)
5393 {
5394     UriBuilder *This = impl_from_IUriBuilder(iface);
5395     HRESULT hr;
5396     TRACE("(%p)->(%d %d %p)\n", This, dwAllowEncodingPropertyMask, (DWORD)dwReserved, ppIUri);
5397
5398     hr = build_uri(This, ppIUri, 0, UriBuilder_USE_ORIGINAL_FLAGS, dwAllowEncodingPropertyMask);
5399     if(hr == E_NOTIMPL)
5400         FIXME("(%p)->(%d %d %p)\n", This, dwAllowEncodingPropertyMask, (DWORD)dwReserved, ppIUri);
5401     return hr;
5402 }
5403
5404 static HRESULT WINAPI UriBuilder_CreateUri(IUriBuilder *iface,
5405                                            DWORD        dwCreateFlags,
5406                                            DWORD        dwAllowEncodingPropertyMask,
5407                                            DWORD_PTR    dwReserved,
5408                                            IUri       **ppIUri)
5409 {
5410     UriBuilder *This = impl_from_IUriBuilder(iface);
5411     HRESULT hr;
5412     TRACE("(%p)->(0x%08x %d %d %p)\n", This, dwCreateFlags, dwAllowEncodingPropertyMask, (DWORD)dwReserved, ppIUri);
5413
5414     if(dwCreateFlags == -1)
5415         hr = build_uri(This, ppIUri, 0, UriBuilder_USE_ORIGINAL_FLAGS, dwAllowEncodingPropertyMask);
5416     else
5417         hr = build_uri(This, ppIUri, dwCreateFlags, 0, dwAllowEncodingPropertyMask);
5418
5419     if(hr == E_NOTIMPL)
5420         FIXME("(%p)->(0x%08x %d %d %p)\n", This, dwCreateFlags, dwAllowEncodingPropertyMask, (DWORD)dwReserved, ppIUri);
5421     return hr;
5422 }
5423
5424 static HRESULT WINAPI UriBuilder_CreateUriWithFlags(IUriBuilder *iface,
5425                                          DWORD        dwCreateFlags,
5426                                          DWORD        dwUriBuilderFlags,
5427                                          DWORD        dwAllowEncodingPropertyMask,
5428                                          DWORD_PTR    dwReserved,
5429                                          IUri       **ppIUri)
5430 {
5431     UriBuilder *This = impl_from_IUriBuilder(iface);
5432     HRESULT hr;
5433     TRACE("(%p)->(0x%08x 0x%08x %d %d %p)\n", This, dwCreateFlags, dwUriBuilderFlags,
5434         dwAllowEncodingPropertyMask, (DWORD)dwReserved, ppIUri);
5435
5436     hr = build_uri(This, ppIUri, dwCreateFlags, dwUriBuilderFlags, dwAllowEncodingPropertyMask);
5437     if(hr == E_NOTIMPL)
5438         FIXME("(%p)->(0x%08x 0x%08x %d %d %p)\n", This, dwCreateFlags, dwUriBuilderFlags,
5439             dwAllowEncodingPropertyMask, (DWORD)dwReserved, ppIUri);
5440     return hr;
5441 }
5442
5443 static HRESULT WINAPI  UriBuilder_GetIUri(IUriBuilder *iface, IUri **ppIUri)
5444 {
5445     UriBuilder *This = impl_from_IUriBuilder(iface);
5446     TRACE("(%p)->(%p)\n", This, ppIUri);
5447
5448     if(!ppIUri)
5449         return E_POINTER;
5450
5451     if(This->uri) {
5452         IUri *uri = &This->uri->IUri_iface;
5453         IUri_AddRef(uri);
5454         *ppIUri = uri;
5455     } else
5456         *ppIUri = NULL;
5457
5458     return S_OK;
5459 }
5460
5461 static HRESULT WINAPI UriBuilder_SetIUri(IUriBuilder *iface, IUri *pIUri)
5462 {
5463     UriBuilder *This = impl_from_IUriBuilder(iface);
5464     TRACE("(%p)->(%p)\n", This, pIUri);
5465
5466     if(pIUri) {
5467         Uri *uri;
5468
5469         if((uri = get_uri_obj(pIUri))) {
5470             /* Only reset the builder if it's Uri isn't the same as
5471              * the Uri passed to the function.
5472              */
5473             if(This->uri != uri) {
5474                 reset_builder(This);
5475
5476                 This->uri = uri;
5477                 if(uri->has_port)
5478                     This->port = uri->port;
5479
5480                 IUri_AddRef(pIUri);
5481             }
5482         } else {
5483             FIXME("(%p)->(%p) Unknown IUri types not supported yet.\n", This, pIUri);
5484             return E_NOTIMPL;
5485         }
5486     } else if(This->uri)
5487         /* Only reset the builder if it's Uri isn't NULL. */
5488         reset_builder(This);
5489
5490     return S_OK;
5491 }
5492
5493 static HRESULT WINAPI UriBuilder_GetFragment(IUriBuilder *iface, DWORD *pcchFragment, LPCWSTR *ppwzFragment)
5494 {
5495     UriBuilder *This = impl_from_IUriBuilder(iface);
5496     TRACE("(%p)->(%p %p)\n", This, pcchFragment, ppwzFragment);
5497
5498     if(!This->uri || This->uri->fragment_start == -1 || This->modified_props & Uri_HAS_FRAGMENT)
5499         return get_builder_component(&This->fragment, &This->fragment_len, NULL, 0, ppwzFragment, pcchFragment);
5500     else
5501         return get_builder_component(&This->fragment, &This->fragment_len, This->uri->canon_uri+This->uri->fragment_start,
5502                                      This->uri->fragment_len, ppwzFragment, pcchFragment);
5503 }
5504
5505 static HRESULT WINAPI UriBuilder_GetHost(IUriBuilder *iface, DWORD *pcchHost, LPCWSTR *ppwzHost)
5506 {
5507     UriBuilder *This = impl_from_IUriBuilder(iface);
5508     TRACE("(%p)->(%p %p)\n", This, pcchHost, ppwzHost);
5509
5510     if(!This->uri || This->uri->host_start == -1 || This->modified_props & Uri_HAS_HOST)
5511         return get_builder_component(&This->host, &This->host_len, NULL, 0, ppwzHost, pcchHost);
5512     else {
5513         if(This->uri->host_type == Uri_HOST_IPV6)
5514             /* Don't include the '[' and ']' around the address. */
5515             return get_builder_component(&This->host, &This->host_len, This->uri->canon_uri+This->uri->host_start+1,
5516                                          This->uri->host_len-2, ppwzHost, pcchHost);
5517         else
5518             return get_builder_component(&This->host, &This->host_len, This->uri->canon_uri+This->uri->host_start,
5519                                          This->uri->host_len, ppwzHost, pcchHost);
5520     }
5521 }
5522
5523 static HRESULT WINAPI UriBuilder_GetPassword(IUriBuilder *iface, DWORD *pcchPassword, LPCWSTR *ppwzPassword)
5524 {
5525     UriBuilder *This = impl_from_IUriBuilder(iface);
5526     TRACE("(%p)->(%p %p)\n", This, pcchPassword, ppwzPassword);
5527
5528     if(!This->uri || This->uri->userinfo_split == -1 || This->modified_props & Uri_HAS_PASSWORD)
5529         return get_builder_component(&This->password, &This->password_len, NULL, 0, ppwzPassword, pcchPassword);
5530     else {
5531         const WCHAR *start = This->uri->canon_uri+This->uri->userinfo_start+This->uri->userinfo_split+1;
5532         DWORD len = This->uri->userinfo_len-This->uri->userinfo_split-1;
5533         return get_builder_component(&This->password, &This->password_len, start, len, ppwzPassword, pcchPassword);
5534     }
5535 }
5536
5537 static HRESULT WINAPI UriBuilder_GetPath(IUriBuilder *iface, DWORD *pcchPath, LPCWSTR *ppwzPath)
5538 {
5539     UriBuilder *This = impl_from_IUriBuilder(iface);
5540     TRACE("(%p)->(%p %p)\n", This, pcchPath, ppwzPath);
5541
5542     if(!This->uri || This->uri->path_start == -1 || This->modified_props & Uri_HAS_PATH)
5543         return get_builder_component(&This->path, &This->path_len, NULL, 0, ppwzPath, pcchPath);
5544     else
5545         return get_builder_component(&This->path, &This->path_len, This->uri->canon_uri+This->uri->path_start,
5546                                      This->uri->path_len, ppwzPath, pcchPath);
5547 }
5548
5549 static HRESULT WINAPI UriBuilder_GetPort(IUriBuilder *iface, BOOL *pfHasPort, DWORD *pdwPort)
5550 {
5551     UriBuilder *This = impl_from_IUriBuilder(iface);
5552     TRACE("(%p)->(%p %p)\n", This, pfHasPort, pdwPort);
5553
5554     if(!pfHasPort) {
5555         if(pdwPort)
5556             *pdwPort = 0;
5557         return E_POINTER;
5558     }
5559
5560     if(!pdwPort) {
5561         *pfHasPort = FALSE;
5562         return E_POINTER;
5563     }
5564
5565     *pfHasPort = This->has_port;
5566     *pdwPort = This->port;
5567     return S_OK;
5568 }
5569
5570 static HRESULT WINAPI UriBuilder_GetQuery(IUriBuilder *iface, DWORD *pcchQuery, LPCWSTR *ppwzQuery)
5571 {
5572     UriBuilder *This = impl_from_IUriBuilder(iface);
5573     TRACE("(%p)->(%p %p)\n", This, pcchQuery, ppwzQuery);
5574
5575     if(!This->uri || This->uri->query_start == -1 || This->modified_props & Uri_HAS_QUERY)
5576         return get_builder_component(&This->query, &This->query_len, NULL, 0, ppwzQuery, pcchQuery);
5577     else
5578         return get_builder_component(&This->query, &This->query_len, This->uri->canon_uri+This->uri->query_start,
5579                                      This->uri->query_len, ppwzQuery, pcchQuery);
5580 }
5581
5582 static HRESULT WINAPI UriBuilder_GetSchemeName(IUriBuilder *iface, DWORD *pcchSchemeName, LPCWSTR *ppwzSchemeName)
5583 {
5584     UriBuilder *This = impl_from_IUriBuilder(iface);
5585     TRACE("(%p)->(%p %p)\n", This, pcchSchemeName, ppwzSchemeName);
5586
5587     if(!This->uri || This->uri->scheme_start == -1 || This->modified_props & Uri_HAS_SCHEME_NAME)
5588         return get_builder_component(&This->scheme, &This->scheme_len, NULL, 0, ppwzSchemeName, pcchSchemeName);
5589     else
5590         return get_builder_component(&This->scheme, &This->scheme_len, This->uri->canon_uri+This->uri->scheme_start,
5591                                      This->uri->scheme_len, ppwzSchemeName, pcchSchemeName);
5592 }
5593
5594 static HRESULT WINAPI UriBuilder_GetUserName(IUriBuilder *iface, DWORD *pcchUserName, LPCWSTR *ppwzUserName)
5595 {
5596     UriBuilder *This = impl_from_IUriBuilder(iface);
5597     TRACE("(%p)->(%p %p)\n", This, pcchUserName, ppwzUserName);
5598
5599     if(!This->uri || This->uri->userinfo_start == -1 || This->uri->userinfo_split == 0 ||
5600        This->modified_props & Uri_HAS_USER_NAME)
5601         return get_builder_component(&This->username, &This->username_len, NULL, 0, ppwzUserName, pcchUserName);
5602     else {
5603         const WCHAR *start = This->uri->canon_uri+This->uri->userinfo_start;
5604
5605         /* Check if there's a password in the userinfo section. */
5606         if(This->uri->userinfo_split > -1)
5607             /* Don't include the password. */
5608             return get_builder_component(&This->username, &This->username_len, start,
5609                                          This->uri->userinfo_split, ppwzUserName, pcchUserName);
5610         else
5611             return get_builder_component(&This->username, &This->username_len, start,
5612                                          This->uri->userinfo_len, ppwzUserName, pcchUserName);
5613     }
5614 }
5615
5616 static HRESULT WINAPI UriBuilder_SetFragment(IUriBuilder *iface, LPCWSTR pwzNewValue)
5617 {
5618     UriBuilder *This = impl_from_IUriBuilder(iface);
5619     TRACE("(%p)->(%s)\n", This, debugstr_w(pwzNewValue));
5620     return set_builder_component(&This->fragment, &This->fragment_len, pwzNewValue, '#',
5621                                  &This->modified_props, Uri_HAS_FRAGMENT);
5622 }
5623
5624 static HRESULT WINAPI UriBuilder_SetHost(IUriBuilder *iface, LPCWSTR pwzNewValue)
5625 {
5626     UriBuilder *This = impl_from_IUriBuilder(iface);
5627     TRACE("(%p)->(%s)\n", This, debugstr_w(pwzNewValue));
5628
5629     /* Host name can't be set to NULL. */
5630     if(!pwzNewValue)
5631         return E_INVALIDARG;
5632
5633     return set_builder_component(&This->host, &This->host_len, pwzNewValue, 0,
5634                                  &This->modified_props, Uri_HAS_HOST);
5635 }
5636
5637 static HRESULT WINAPI UriBuilder_SetPassword(IUriBuilder *iface, LPCWSTR pwzNewValue)
5638 {
5639     UriBuilder *This = impl_from_IUriBuilder(iface);
5640     TRACE("(%p)->(%s)\n", This, debugstr_w(pwzNewValue));
5641     return set_builder_component(&This->password, &This->password_len, pwzNewValue, 0,
5642                                  &This->modified_props, Uri_HAS_PASSWORD);
5643 }
5644
5645 static HRESULT WINAPI UriBuilder_SetPath(IUriBuilder *iface, LPCWSTR pwzNewValue)
5646 {
5647     UriBuilder *This = impl_from_IUriBuilder(iface);
5648     TRACE("(%p)->(%s)\n", This, debugstr_w(pwzNewValue));
5649     return set_builder_component(&This->path, &This->path_len, pwzNewValue, 0,
5650                                  &This->modified_props, Uri_HAS_PATH);
5651 }
5652
5653 static HRESULT WINAPI UriBuilder_SetPort(IUriBuilder *iface, BOOL fHasPort, DWORD dwNewValue)
5654 {
5655     UriBuilder *This = impl_from_IUriBuilder(iface);
5656     TRACE("(%p)->(%d %d)\n", This, fHasPort, dwNewValue);
5657
5658     This->has_port = fHasPort;
5659     This->port = dwNewValue;
5660     This->modified_props |= Uri_HAS_PORT;
5661     return S_OK;
5662 }
5663
5664 static HRESULT WINAPI UriBuilder_SetQuery(IUriBuilder *iface, LPCWSTR pwzNewValue)
5665 {
5666     UriBuilder *This = impl_from_IUriBuilder(iface);
5667     TRACE("(%p)->(%s)\n", This, debugstr_w(pwzNewValue));
5668     return set_builder_component(&This->query, &This->query_len, pwzNewValue, '?',
5669                                  &This->modified_props, Uri_HAS_QUERY);
5670 }
5671
5672 static HRESULT WINAPI UriBuilder_SetSchemeName(IUriBuilder *iface, LPCWSTR pwzNewValue)
5673 {
5674     UriBuilder *This = impl_from_IUriBuilder(iface);
5675     TRACE("(%p)->(%s)\n", This, debugstr_w(pwzNewValue));
5676
5677     /* Only set the scheme name if it's not NULL or empty. */
5678     if(!pwzNewValue || !*pwzNewValue)
5679         return E_INVALIDARG;
5680
5681     return set_builder_component(&This->scheme, &This->scheme_len, pwzNewValue, 0,
5682                                  &This->modified_props, Uri_HAS_SCHEME_NAME);
5683 }
5684
5685 static HRESULT WINAPI UriBuilder_SetUserName(IUriBuilder *iface, LPCWSTR pwzNewValue)
5686 {
5687     UriBuilder *This = impl_from_IUriBuilder(iface);
5688     TRACE("(%p)->(%s)\n", This, debugstr_w(pwzNewValue));
5689     return set_builder_component(&This->username, &This->username_len, pwzNewValue, 0,
5690                                  &This->modified_props, Uri_HAS_USER_NAME);
5691 }
5692
5693 static HRESULT WINAPI UriBuilder_RemoveProperties(IUriBuilder *iface, DWORD dwPropertyMask)
5694 {
5695     const DWORD accepted_flags = Uri_HAS_AUTHORITY|Uri_HAS_DOMAIN|Uri_HAS_EXTENSION|Uri_HAS_FRAGMENT|Uri_HAS_HOST|
5696                                  Uri_HAS_PASSWORD|Uri_HAS_PATH|Uri_HAS_PATH_AND_QUERY|Uri_HAS_QUERY|
5697                                  Uri_HAS_USER_INFO|Uri_HAS_USER_NAME;
5698
5699     UriBuilder *This = impl_from_IUriBuilder(iface);
5700     TRACE("(%p)->(0x%08x)\n", This, dwPropertyMask);
5701
5702     if(dwPropertyMask & ~accepted_flags)
5703         return E_INVALIDARG;
5704
5705     if(dwPropertyMask & Uri_HAS_FRAGMENT)
5706         UriBuilder_SetFragment(iface, NULL);
5707
5708     /* Even though you can't set the host name to NULL or an
5709      * empty string, you can still remove it... for some reason.
5710      */
5711     if(dwPropertyMask & Uri_HAS_HOST)
5712         set_builder_component(&This->host, &This->host_len, NULL, 0,
5713                               &This->modified_props, Uri_HAS_HOST);
5714
5715     if(dwPropertyMask & Uri_HAS_PASSWORD)
5716         UriBuilder_SetPassword(iface, NULL);
5717
5718     if(dwPropertyMask & Uri_HAS_PATH)
5719         UriBuilder_SetPath(iface, NULL);
5720
5721     if(dwPropertyMask & Uri_HAS_PORT)
5722         UriBuilder_SetPort(iface, FALSE, 0);
5723
5724     if(dwPropertyMask & Uri_HAS_QUERY)
5725         UriBuilder_SetQuery(iface, NULL);
5726
5727     if(dwPropertyMask & Uri_HAS_USER_NAME)
5728         UriBuilder_SetUserName(iface, NULL);
5729
5730     return S_OK;
5731 }
5732
5733 static HRESULT WINAPI UriBuilder_HasBeenModified(IUriBuilder *iface, BOOL *pfModified)
5734 {
5735     UriBuilder *This = impl_from_IUriBuilder(iface);
5736     TRACE("(%p)->(%p)\n", This, pfModified);
5737
5738     if(!pfModified)
5739         return E_POINTER;
5740
5741     *pfModified = This->modified_props > 0;
5742     return S_OK;
5743 }
5744
5745 static const IUriBuilderVtbl UriBuilderVtbl = {
5746     UriBuilder_QueryInterface,
5747     UriBuilder_AddRef,
5748     UriBuilder_Release,
5749     UriBuilder_CreateUriSimple,
5750     UriBuilder_CreateUri,
5751     UriBuilder_CreateUriWithFlags,
5752     UriBuilder_GetIUri,
5753     UriBuilder_SetIUri,
5754     UriBuilder_GetFragment,
5755     UriBuilder_GetHost,
5756     UriBuilder_GetPassword,
5757     UriBuilder_GetPath,
5758     UriBuilder_GetPort,
5759     UriBuilder_GetQuery,
5760     UriBuilder_GetSchemeName,
5761     UriBuilder_GetUserName,
5762     UriBuilder_SetFragment,
5763     UriBuilder_SetHost,
5764     UriBuilder_SetPassword,
5765     UriBuilder_SetPath,
5766     UriBuilder_SetPort,
5767     UriBuilder_SetQuery,
5768     UriBuilder_SetSchemeName,
5769     UriBuilder_SetUserName,
5770     UriBuilder_RemoveProperties,
5771     UriBuilder_HasBeenModified,
5772 };
5773
5774 /***********************************************************************
5775  *           CreateIUriBuilder (urlmon.@)
5776  */
5777 HRESULT WINAPI CreateIUriBuilder(IUri *pIUri, DWORD dwFlags, DWORD_PTR dwReserved, IUriBuilder **ppIUriBuilder)
5778 {
5779     UriBuilder *ret;
5780
5781     TRACE("(%p %x %x %p)\n", pIUri, dwFlags, (DWORD)dwReserved, ppIUriBuilder);
5782
5783     if(!ppIUriBuilder)
5784         return E_POINTER;
5785
5786     ret = heap_alloc_zero(sizeof(UriBuilder));
5787     if(!ret)
5788         return E_OUTOFMEMORY;
5789
5790     ret->IUriBuilder_iface.lpVtbl = &UriBuilderVtbl;
5791     ret->ref = 1;
5792
5793     if(pIUri) {
5794         Uri *uri;
5795
5796         if((uri = get_uri_obj(pIUri))) {
5797             IUri_AddRef(pIUri);
5798             ret->uri = uri;
5799
5800             if(uri->has_port)
5801                 /* Windows doesn't set 'has_port' to TRUE in this case. */
5802                 ret->port = uri->port;
5803
5804         } else {
5805             heap_free(ret);
5806             *ppIUriBuilder = NULL;
5807             FIXME("(%p %x %x %p): Unknown IUri types not supported yet.\n", pIUri, dwFlags,
5808                 (DWORD)dwReserved, ppIUriBuilder);
5809             return E_NOTIMPL;
5810         }
5811     }
5812
5813     *ppIUriBuilder = &ret->IUriBuilder_iface;
5814     return S_OK;
5815 }
5816
5817 /* Merges the base path with the relative path and stores the resulting path
5818  * and path len in 'result' and 'result_len'.
5819  */
5820 static HRESULT merge_paths(parse_data *data, const WCHAR *base, DWORD base_len, const WCHAR *relative,
5821                            DWORD relative_len, WCHAR **result, DWORD *result_len, DWORD flags)
5822 {
5823     const WCHAR *end = NULL;
5824     DWORD base_copy_len = 0;
5825     WCHAR *ptr;
5826
5827     if(base_len) {
5828         /* Find the characters that will be copied over from
5829          * the base path.
5830          */
5831         end = memrchrW(base, '/', base_len);
5832         if(!end && data->scheme_type == URL_SCHEME_FILE)
5833             /* Try looking for a '\\'. */
5834             end = memrchrW(base, '\\', base_len);
5835     }
5836
5837     if(end) {
5838         base_copy_len = (end+1)-base;
5839         *result = heap_alloc((base_copy_len+relative_len+1)*sizeof(WCHAR));
5840     } else
5841         *result = heap_alloc((relative_len+1)*sizeof(WCHAR));
5842
5843     if(!(*result)) {
5844         *result_len = 0;
5845         return E_OUTOFMEMORY;
5846     }
5847
5848     ptr = *result;
5849     if(end) {
5850         memcpy(ptr, base, base_copy_len*sizeof(WCHAR));
5851         ptr += base_copy_len;
5852     }
5853
5854     memcpy(ptr, relative, relative_len*sizeof(WCHAR));
5855     ptr += relative_len;
5856     *ptr = '\0';
5857
5858     *result_len = (ptr-*result);
5859     return S_OK;
5860 }
5861
5862 static HRESULT combine_uri(Uri *base, Uri *relative, DWORD flags, IUri **result, DWORD extras) {
5863     Uri *ret;
5864     HRESULT hr;
5865     parse_data data;
5866     DWORD create_flags = 0, len = 0;
5867
5868     memset(&data, 0, sizeof(parse_data));
5869
5870     /* Base case is when the relative Uri has a scheme name,
5871      * if it does, then 'result' will contain the same data
5872      * as the relative Uri.
5873      */
5874     if(relative->scheme_start > -1) {
5875         data.uri = SysAllocString(relative->raw_uri);
5876         if(!data.uri) {
5877             *result = NULL;
5878             return E_OUTOFMEMORY;
5879         }
5880
5881         parse_uri(&data, 0);
5882
5883         ret = create_uri_obj();
5884         if(!ret) {
5885             *result = NULL;
5886             return E_OUTOFMEMORY;
5887         }
5888
5889         if(extras & COMBINE_URI_FORCE_FLAG_USE) {
5890             if(flags & URL_DONT_SIMPLIFY)
5891                 create_flags |= Uri_CREATE_NO_CANONICALIZE;
5892             if(flags & URL_DONT_UNESCAPE_EXTRA_INFO)
5893                 create_flags |= Uri_CREATE_NO_DECODE_EXTRA_INFO;
5894         }
5895
5896         ret->raw_uri = data.uri;
5897         hr = canonicalize_uri(&data, ret, create_flags);
5898         if(FAILED(hr)) {
5899             IUri_Release(&ret->IUri_iface);
5900             *result = NULL;
5901             return hr;
5902         }
5903
5904         apply_default_flags(&create_flags);
5905         ret->create_flags = create_flags;
5906
5907         *result = &ret->IUri_iface;
5908     } else {
5909         WCHAR *path = NULL;
5910         DWORD raw_flags = 0;
5911
5912         if(base->scheme_start > -1) {
5913             data.scheme = base->canon_uri+base->scheme_start;
5914             data.scheme_len = base->scheme_len;
5915             data.scheme_type = base->scheme_type;
5916         } else {
5917             data.is_relative = TRUE;
5918             data.scheme_type = URL_SCHEME_UNKNOWN;
5919             create_flags |= Uri_CREATE_ALLOW_RELATIVE;
5920         }
5921
5922         if(base->authority_start > -1) {
5923             if(base->userinfo_start > -1 && base->userinfo_split != 0) {
5924                 data.username = base->canon_uri+base->userinfo_start;
5925                 data.username_len = (base->userinfo_split > -1) ? base->userinfo_split : base->userinfo_len;
5926             }
5927
5928             if(base->userinfo_split > -1) {
5929                 data.password = base->canon_uri+base->userinfo_start+base->userinfo_split+1;
5930                 data.password_len = base->userinfo_len-base->userinfo_split-1;
5931             }
5932
5933             if(base->host_start > -1) {
5934                 data.host = base->canon_uri+base->host_start;
5935                 data.host_len = base->host_len;
5936                 data.host_type = base->host_type;
5937             }
5938
5939             if(base->has_port) {
5940                 data.has_port = TRUE;
5941                 data.port_value = base->port;
5942             }
5943         } else if(base->scheme_type != URL_SCHEME_FILE)
5944             data.is_opaque = TRUE;
5945
5946         if(relative->path_start == -1 || !relative->path_len) {
5947             if(base->path_start > -1) {
5948                 data.path = base->canon_uri+base->path_start;
5949                 data.path_len = base->path_len;
5950             } else if((base->path_start == -1 || !base->path_len) && !data.is_opaque) {
5951                 /* Just set the path as a '/' if the base didn't have
5952                  * one and if it's an hierarchical URI.
5953                  */
5954                 static const WCHAR slashW[] = {'/',0};
5955                 data.path = slashW;
5956                 data.path_len = 1;
5957             }
5958
5959             if(relative->query_start > -1) {
5960                 data.query = relative->canon_uri+relative->query_start;
5961                 data.query_len = relative->query_len;
5962             } else if(base->query_start > -1) {
5963                 data.query = base->canon_uri+base->query_start;
5964                 data.query_len = base->query_len;
5965             }
5966         } else {
5967             const WCHAR *ptr, **pptr;
5968             DWORD path_offset = 0, path_len = 0;
5969
5970             /* There's two possibilities on what will happen to the path component
5971              * of the result IUri. First, if the relative path begins with a '/'
5972              * then the resulting path will just be the relative path. Second, if
5973              * relative path doesn't begin with a '/' then the base path and relative
5974              * path are merged together.
5975              */
5976             if(relative->path_len && *(relative->canon_uri+relative->path_start) == '/') {
5977                 WCHAR *tmp = NULL;
5978                 BOOL copy_drive_path = FALSE;
5979
5980                 /* If the relative IUri's path starts with a '/', then we
5981                  * don't use the base IUri's path. Unless the base IUri
5982                  * is a file URI, in which case it uses the drive path of
5983                  * the base IUri (if it has any) in the new path.
5984                  */
5985                 if(base->scheme_type == URL_SCHEME_FILE) {
5986                     if(base->path_len > 3 && *(base->canon_uri+base->path_start) == '/' &&
5987                        is_drive_path(base->canon_uri+base->path_start+1)) {
5988                         path_len += 3;
5989                         copy_drive_path = TRUE;
5990                     }
5991                 }
5992
5993                 path_len += relative->path_len;
5994
5995                 path = heap_alloc((path_len+1)*sizeof(WCHAR));
5996                 if(!path) {
5997                     *result = NULL;
5998                     return E_OUTOFMEMORY;
5999                 }
6000
6001                 tmp = path;
6002
6003                 /* Copy the base paths, drive path over. */
6004                 if(copy_drive_path) {
6005                     memcpy(tmp, base->canon_uri+base->path_start, 3*sizeof(WCHAR));
6006                     tmp += 3;
6007                 }
6008
6009                 memcpy(tmp, relative->canon_uri+relative->path_start, relative->path_len*sizeof(WCHAR));
6010                 path[path_len] = '\0';
6011             } else {
6012                 /* Merge the base path with the relative path. */
6013                 hr = merge_paths(&data, base->canon_uri+base->path_start, base->path_len,
6014                                  relative->canon_uri+relative->path_start, relative->path_len,
6015                                  &path, &path_len, flags);
6016                 if(FAILED(hr)) {
6017                     *result = NULL;
6018                     return hr;
6019                 }
6020
6021                 /* If the resulting IUri is a file URI, the drive path isn't
6022                  * reduced out when the dot segments are removed.
6023                  */
6024                 if(path_len >= 3 && data.scheme_type == URL_SCHEME_FILE && !data.host) {
6025                     if(*path == '/' && is_drive_path(path+1))
6026                         path_offset = 2;
6027                     else if(is_drive_path(path))
6028                         path_offset = 1;
6029                 }
6030             }
6031
6032             /* Check if the dot segments need to be removed from the path. */
6033             if(!(flags & URL_DONT_SIMPLIFY) && !data.is_opaque) {
6034                 DWORD offset = (path_offset > 0) ? path_offset+1 : 0;
6035                 DWORD new_len = remove_dot_segments(path+offset,path_len-offset);
6036
6037                 if(new_len != path_len) {
6038                     WCHAR *tmp = heap_realloc(path, (offset+new_len+1)*sizeof(WCHAR));
6039                     if(!tmp) {
6040                         heap_free(path);
6041                         *result = NULL;
6042                         return E_OUTOFMEMORY;
6043                     }
6044
6045                     tmp[new_len+offset] = '\0';
6046                     path = tmp;
6047                     path_len = new_len+offset;
6048                 }
6049             }
6050
6051             if(relative->query_start > -1) {
6052                 data.query = relative->canon_uri+relative->query_start;
6053                 data.query_len = relative->query_len;
6054             }
6055
6056             /* Make sure the path component is valid. */
6057             ptr = path;
6058             pptr = &ptr;
6059             if((data.is_opaque && !parse_path_opaque(pptr, &data, 0)) ||
6060                (!data.is_opaque && !parse_path_hierarchical(pptr, &data, 0))) {
6061                 heap_free(path);
6062                 *result = NULL;
6063                 return E_INVALIDARG;
6064             }
6065         }
6066
6067         if(relative->fragment_start > -1) {
6068             data.fragment = relative->canon_uri+relative->fragment_start;
6069             data.fragment_len = relative->fragment_len;
6070         }
6071
6072         if(flags & URL_DONT_SIMPLIFY)
6073             raw_flags |= RAW_URI_FORCE_PORT_DISP;
6074         if(flags & URL_FILE_USE_PATHURL)
6075             raw_flags |= RAW_URI_CONVERT_TO_DOS_PATH;
6076
6077         len = generate_raw_uri(&data, data.uri, raw_flags);
6078         data.uri = SysAllocStringLen(NULL, len);
6079         if(!data.uri) {
6080             heap_free(path);
6081             *result = NULL;
6082             return E_OUTOFMEMORY;
6083         }
6084
6085         generate_raw_uri(&data, data.uri, raw_flags);
6086
6087         ret = create_uri_obj();
6088         if(!ret) {
6089             SysFreeString(data.uri);
6090             heap_free(path);
6091             *result = NULL;
6092             return E_OUTOFMEMORY;
6093         }
6094
6095         if(flags & URL_DONT_SIMPLIFY)
6096             create_flags |= Uri_CREATE_NO_CANONICALIZE;
6097         if(flags & URL_FILE_USE_PATHURL)
6098             create_flags |= Uri_CREATE_FILE_USE_DOS_PATH;
6099
6100         ret->raw_uri = data.uri;
6101         hr = canonicalize_uri(&data, ret, create_flags);
6102         if(FAILED(hr)) {
6103             IUri_Release(&ret->IUri_iface);
6104             *result = NULL;
6105             return hr;
6106         }
6107
6108         if(flags & URL_DONT_SIMPLIFY)
6109             ret->display_modifiers |= URI_DISPLAY_NO_DEFAULT_PORT_AUTH;
6110
6111         apply_default_flags(&create_flags);
6112         ret->create_flags = create_flags;
6113         *result = &ret->IUri_iface;
6114
6115         heap_free(path);
6116     }
6117
6118     return S_OK;
6119 }
6120
6121 /***********************************************************************
6122  *           CoInternetCombineIUri (urlmon.@)
6123  */
6124 HRESULT WINAPI CoInternetCombineIUri(IUri *pBaseUri, IUri *pRelativeUri, DWORD dwCombineFlags,
6125                                      IUri **ppCombinedUri, DWORD_PTR dwReserved)
6126 {
6127     HRESULT hr;
6128     IInternetProtocolInfo *info;
6129     Uri *relative, *base;
6130     TRACE("(%p %p %x %p %x)\n", pBaseUri, pRelativeUri, dwCombineFlags, ppCombinedUri, (DWORD)dwReserved);
6131
6132     if(!ppCombinedUri)
6133         return E_INVALIDARG;
6134
6135     if(!pBaseUri || !pRelativeUri) {
6136         *ppCombinedUri = NULL;
6137         return E_INVALIDARG;
6138     }
6139
6140     relative = get_uri_obj(pRelativeUri);
6141     base = get_uri_obj(pBaseUri);
6142     if(!relative || !base) {
6143         *ppCombinedUri = NULL;
6144         FIXME("(%p %p %x %p %x) Unknown IUri types not supported yet.\n",
6145             pBaseUri, pRelativeUri, dwCombineFlags, ppCombinedUri, (DWORD)dwReserved);
6146         return E_NOTIMPL;
6147     }
6148
6149     info = get_protocol_info(base->canon_uri);
6150     if(info) {
6151         WCHAR result[INTERNET_MAX_URL_LENGTH+1];
6152         DWORD result_len = 0;
6153
6154         hr = IInternetProtocolInfo_CombineUrl(info, base->canon_uri, relative->canon_uri, dwCombineFlags,
6155                                               result, INTERNET_MAX_URL_LENGTH+1, &result_len, 0);
6156         IInternetProtocolInfo_Release(info);
6157         if(SUCCEEDED(hr)) {
6158             hr = CreateUri(result, Uri_CREATE_ALLOW_RELATIVE, 0, ppCombinedUri);
6159             if(SUCCEEDED(hr))
6160                 return hr;
6161         }
6162     }
6163
6164     return combine_uri(base, relative, dwCombineFlags, ppCombinedUri, 0);
6165 }
6166
6167 /***********************************************************************
6168  *           CoInternetCombineUrlEx (urlmon.@)
6169  */
6170 HRESULT WINAPI CoInternetCombineUrlEx(IUri *pBaseUri, LPCWSTR pwzRelativeUrl, DWORD dwCombineFlags,
6171                                       IUri **ppCombinedUri, DWORD_PTR dwReserved)
6172 {
6173     IUri *relative;
6174     Uri *base;
6175     HRESULT hr;
6176     IInternetProtocolInfo *info;
6177
6178     TRACE("(%p %s %x %p %x) stub\n", pBaseUri, debugstr_w(pwzRelativeUrl), dwCombineFlags,
6179         ppCombinedUri, (DWORD)dwReserved);
6180
6181     if(!ppCombinedUri)
6182         return E_POINTER;
6183
6184     if(!pwzRelativeUrl) {
6185         *ppCombinedUri = NULL;
6186         return E_UNEXPECTED;
6187     }
6188
6189     if(!pBaseUri) {
6190         *ppCombinedUri = NULL;
6191         return E_INVALIDARG;
6192     }
6193
6194     base = get_uri_obj(pBaseUri);
6195     if(!base) {
6196         *ppCombinedUri = NULL;
6197         FIXME("(%p %s %x %p %x) Unknown IUri's not supported yet.\n", pBaseUri, debugstr_w(pwzRelativeUrl),
6198             dwCombineFlags, ppCombinedUri, (DWORD)dwReserved);
6199         return E_NOTIMPL;
6200     }
6201
6202     info = get_protocol_info(base->canon_uri);
6203     if(info) {
6204         WCHAR result[INTERNET_MAX_URL_LENGTH+1];
6205         DWORD result_len = 0;
6206
6207         hr = IInternetProtocolInfo_CombineUrl(info, base->canon_uri, pwzRelativeUrl, dwCombineFlags,
6208                                               result, INTERNET_MAX_URL_LENGTH+1, &result_len, 0);
6209         IInternetProtocolInfo_Release(info);
6210         if(SUCCEEDED(hr)) {
6211             hr = CreateUri(result, Uri_CREATE_ALLOW_RELATIVE, 0, ppCombinedUri);
6212             if(SUCCEEDED(hr))
6213                 return hr;
6214         }
6215     }
6216
6217     hr = CreateUri(pwzRelativeUrl, Uri_CREATE_ALLOW_RELATIVE, 0, &relative);
6218     if(FAILED(hr)) {
6219         *ppCombinedUri = NULL;
6220         return hr;
6221     }
6222
6223     hr = combine_uri(base, get_uri_obj(relative), dwCombineFlags, ppCombinedUri, COMBINE_URI_FORCE_FLAG_USE);
6224
6225     IUri_Release(relative);
6226     return hr;
6227 }
6228
6229 static HRESULT parse_canonicalize(const Uri *uri, DWORD flags, LPWSTR output,
6230                                   DWORD output_len, DWORD *result_len)
6231 {
6232     const WCHAR *ptr = NULL;
6233     WCHAR *path = NULL;
6234     const WCHAR **pptr;
6235     WCHAR buffer[INTERNET_MAX_URL_LENGTH+1];
6236     DWORD len = 0;
6237     BOOL reduce_path;
6238
6239     /* URL_UNESCAPE only has effect if none of the URL_ESCAPE flags are set. */
6240     const BOOL allow_unescape = !(flags & URL_ESCAPE_UNSAFE) &&
6241                                 !(flags & URL_ESCAPE_SPACES_ONLY) &&
6242                                 !(flags & URL_ESCAPE_PERCENT);
6243
6244
6245     /* Check if the dot segments need to be removed from the
6246      * path component.
6247      */
6248     if(uri->scheme_start > -1 && uri->path_start > -1) {
6249         ptr = uri->canon_uri+uri->scheme_start+uri->scheme_len+1;
6250         pptr = &ptr;
6251     }
6252     reduce_path = !(flags & URL_NO_META) &&
6253                   !(flags & URL_DONT_SIMPLIFY) &&
6254                   ptr && check_hierarchical(pptr);
6255
6256     for(ptr = uri->canon_uri; ptr < uri->canon_uri+uri->canon_len; ++ptr) {
6257         BOOL do_default_action = TRUE;
6258
6259         /* Keep track of the path if we need to remove dot segments from
6260          * it later.
6261          */
6262         if(reduce_path && !path && ptr == uri->canon_uri+uri->path_start)
6263             path = buffer+len;
6264
6265         /* Check if it's time to reduce the path. */
6266         if(reduce_path && ptr == uri->canon_uri+uri->path_start+uri->path_len) {
6267             DWORD current_path_len = (buffer+len) - path;
6268             DWORD new_path_len = remove_dot_segments(path, current_path_len);
6269
6270             /* Update the current length. */
6271             len -= (current_path_len-new_path_len);
6272             reduce_path = FALSE;
6273         }
6274
6275         if(*ptr == '%') {
6276             const WCHAR decoded = decode_pct_val(ptr);
6277             if(decoded) {
6278                 if(allow_unescape && (flags & URL_UNESCAPE)) {
6279                     buffer[len++] = decoded;
6280                     ptr += 2;
6281                     do_default_action = FALSE;
6282                 }
6283             }
6284
6285             /* See if %'s needed to encoded. */
6286             if(do_default_action && (flags & URL_ESCAPE_PERCENT)) {
6287                 pct_encode_val(*ptr, buffer+len);
6288                 len += 3;
6289                 do_default_action = FALSE;
6290             }
6291         } else if(*ptr == ' ') {
6292             if((flags & URL_ESCAPE_SPACES_ONLY) &&
6293                !(flags & URL_ESCAPE_UNSAFE)) {
6294                 pct_encode_val(*ptr, buffer+len);
6295                 len += 3;
6296                 do_default_action = FALSE;
6297             }
6298         } else if(!is_reserved(*ptr) && !is_unreserved(*ptr)) {
6299             if(flags & URL_ESCAPE_UNSAFE) {
6300                 pct_encode_val(*ptr, buffer+len);
6301                 len += 3;
6302                 do_default_action = FALSE;
6303             }
6304         }
6305
6306         if(do_default_action)
6307             buffer[len++] = *ptr;
6308     }
6309
6310     /* Sometimes the path is the very last component of the IUri, so
6311      * see if the dot segments need to be reduced now.
6312      */
6313     if(reduce_path && path) {
6314         DWORD current_path_len = (buffer+len) - path;
6315         DWORD new_path_len = remove_dot_segments(path, current_path_len);
6316
6317         /* Update the current length. */
6318         len -= (current_path_len-new_path_len);
6319     }
6320
6321     buffer[len++] = 0;
6322
6323     /* The null terminator isn't included in the length. */
6324     *result_len = len-1;
6325     if(len > output_len)
6326         return STRSAFE_E_INSUFFICIENT_BUFFER;
6327     else
6328         memcpy(output, buffer, len*sizeof(WCHAR));
6329
6330     return S_OK;
6331 }
6332
6333 static HRESULT parse_friendly(IUri *uri, LPWSTR output, DWORD output_len,
6334                               DWORD *result_len)
6335 {
6336     HRESULT hr;
6337     DWORD display_len;
6338     BSTR display;
6339
6340     hr = IUri_GetPropertyLength(uri, Uri_PROPERTY_DISPLAY_URI, &display_len, 0);
6341     if(FAILED(hr)) {
6342         *result_len = 0;
6343         return hr;
6344     }
6345
6346     *result_len = display_len;
6347     if(display_len+1 > output_len)
6348         return STRSAFE_E_INSUFFICIENT_BUFFER;
6349
6350     hr = IUri_GetDisplayUri(uri, &display);
6351     if(FAILED(hr)) {
6352         *result_len = 0;
6353         return hr;
6354     }
6355
6356     memcpy(output, display, (display_len+1)*sizeof(WCHAR));
6357     SysFreeString(display);
6358     return S_OK;
6359 }
6360
6361 static HRESULT parse_rootdocument(const Uri *uri, LPWSTR output, DWORD output_len,
6362                                   DWORD *result_len)
6363 {
6364     static const WCHAR colon_slashesW[] = {':','/','/'};
6365
6366     WCHAR *ptr;
6367     DWORD len = 0;
6368
6369     /* Windows only returns the root document if the URI has an authority
6370      * and it's not an unknown scheme type or a file scheme type.
6371      */
6372     if(uri->authority_start == -1 ||
6373        uri->scheme_type == URL_SCHEME_UNKNOWN ||
6374        uri->scheme_type == URL_SCHEME_FILE) {
6375         *result_len = 0;
6376         if(!output_len)
6377             return STRSAFE_E_INSUFFICIENT_BUFFER;
6378
6379         output[0] = 0;
6380         return S_OK;
6381     }
6382
6383     len = uri->scheme_len+uri->authority_len;
6384     /* For the "://" and '/' which will be added. */
6385     len += 4;
6386
6387     if(len+1 > output_len) {
6388         *result_len = len;
6389         return STRSAFE_E_INSUFFICIENT_BUFFER;
6390     }
6391
6392     ptr = output;
6393     memcpy(ptr, uri->canon_uri+uri->scheme_start, uri->scheme_len*sizeof(WCHAR));
6394
6395     /* Add the "://". */
6396     ptr += uri->scheme_len;
6397     memcpy(ptr, colon_slashesW, sizeof(colon_slashesW));
6398
6399     /* Add the authority. */
6400     ptr += sizeof(colon_slashesW)/sizeof(WCHAR);
6401     memcpy(ptr, uri->canon_uri+uri->authority_start, uri->authority_len*sizeof(WCHAR));
6402
6403     /* Add the '/' after the authority. */
6404     ptr += uri->authority_len;
6405     *ptr = '/';
6406     ptr[1] = 0;
6407
6408     *result_len = len;
6409     return S_OK;
6410 }
6411
6412 static HRESULT parse_document(const Uri *uri, LPWSTR output, DWORD output_len,
6413                               DWORD *result_len)
6414 {
6415     DWORD len = 0;
6416
6417     /* It has to be a known scheme type, but, it can't be a file
6418      * scheme. It also has to hierarchical.
6419      */
6420     if(uri->scheme_type == URL_SCHEME_UNKNOWN ||
6421        uri->scheme_type == URL_SCHEME_FILE ||
6422        uri->authority_start == -1) {
6423         *result_len = 0;
6424         if(output_len < 1)
6425             return STRSAFE_E_INSUFFICIENT_BUFFER;
6426
6427         output[0] = 0;
6428         return S_OK;
6429     }
6430
6431     if(uri->fragment_start > -1)
6432         len = uri->fragment_start;
6433     else
6434         len = uri->canon_len;
6435
6436     *result_len = len;
6437     if(len+1 > output_len)
6438         return STRSAFE_E_INSUFFICIENT_BUFFER;
6439
6440     memcpy(output, uri->canon_uri, len*sizeof(WCHAR));
6441     output[len] = 0;
6442     return S_OK;
6443 }
6444
6445 static HRESULT parse_path_from_url(const Uri *uri, LPWSTR output, DWORD output_len,
6446                                    DWORD *result_len)
6447 {
6448     const WCHAR *path_ptr;
6449     WCHAR buffer[INTERNET_MAX_URL_LENGTH+1];
6450     WCHAR *ptr;
6451
6452     if(uri->scheme_type != URL_SCHEME_FILE) {
6453         *result_len = 0;
6454         if(output_len > 0)
6455             output[0] = 0;
6456         return E_INVALIDARG;
6457     }
6458
6459     ptr = buffer;
6460     if(uri->host_start > -1) {
6461         static const WCHAR slash_slashW[] = {'\\','\\'};
6462
6463         memcpy(ptr, slash_slashW, sizeof(slash_slashW));
6464         ptr += sizeof(slash_slashW)/sizeof(WCHAR);
6465         memcpy(ptr, uri->canon_uri+uri->host_start, uri->host_len*sizeof(WCHAR));
6466         ptr += uri->host_len;
6467     }
6468
6469     path_ptr = uri->canon_uri+uri->path_start;
6470     if(uri->path_len > 3 && *path_ptr == '/' && is_drive_path(path_ptr+1))
6471         /* Skip past the '/' in front of the drive path. */
6472         ++path_ptr;
6473
6474     for(; path_ptr < uri->canon_uri+uri->path_start+uri->path_len; ++path_ptr, ++ptr) {
6475         BOOL do_default_action = TRUE;
6476
6477         if(*path_ptr == '%') {
6478             const WCHAR decoded = decode_pct_val(path_ptr);
6479             if(decoded) {
6480                 *ptr = decoded;
6481                 path_ptr += 2;
6482                 do_default_action = FALSE;
6483             }
6484         } else if(*path_ptr == '/') {
6485             *ptr = '\\';
6486             do_default_action = FALSE;
6487         }
6488
6489         if(do_default_action)
6490             *ptr = *path_ptr;
6491     }
6492
6493     *ptr = 0;
6494
6495     *result_len = ptr-buffer;
6496     if(*result_len+1 > output_len)
6497         return STRSAFE_E_INSUFFICIENT_BUFFER;
6498
6499     memcpy(output, buffer, (*result_len+1)*sizeof(WCHAR));
6500     return S_OK;
6501 }
6502
6503 static HRESULT parse_url_from_path(IUri *uri, LPWSTR output, DWORD output_len,
6504                                    DWORD *result_len)
6505 {
6506     HRESULT hr;
6507     BSTR received;
6508     DWORD len = 0;
6509
6510     hr = IUri_GetPropertyLength(uri, Uri_PROPERTY_ABSOLUTE_URI, &len, 0);
6511     if(FAILED(hr)) {
6512         *result_len = 0;
6513         return hr;
6514     }
6515
6516     *result_len = len;
6517     if(len+1 > output_len)
6518         return STRSAFE_E_INSUFFICIENT_BUFFER;
6519
6520     hr = IUri_GetAbsoluteUri(uri, &received);
6521     if(FAILED(hr)) {
6522         *result_len = 0;
6523         return hr;
6524     }
6525
6526     memcpy(output, received, (len+1)*sizeof(WCHAR));
6527     SysFreeString(received);
6528
6529     return S_OK;
6530 }
6531
6532 static HRESULT parse_schema(IUri *uri, LPWSTR output, DWORD output_len,
6533                             DWORD *result_len)
6534 {
6535     HRESULT hr;
6536     DWORD len;
6537     BSTR received;
6538
6539     hr = IUri_GetPropertyLength(uri, Uri_PROPERTY_SCHEME_NAME, &len, 0);
6540     if(FAILED(hr)) {
6541         *result_len = 0;
6542         return hr;
6543     }
6544
6545     *result_len = len;
6546     if(len+1 > output_len)
6547         return STRSAFE_E_INSUFFICIENT_BUFFER;
6548
6549     hr = IUri_GetSchemeName(uri, &received);
6550     if(FAILED(hr)) {
6551         *result_len = 0;
6552         return hr;
6553     }
6554
6555     memcpy(output, received, (len+1)*sizeof(WCHAR));
6556     SysFreeString(received);
6557
6558     return S_OK;
6559 }
6560
6561 static HRESULT parse_site(IUri *uri, LPWSTR output, DWORD output_len, DWORD *result_len)
6562 {
6563     HRESULT hr;
6564     DWORD len;
6565     BSTR received;
6566
6567     hr = IUri_GetPropertyLength(uri, Uri_PROPERTY_HOST, &len, 0);
6568     if(FAILED(hr)) {
6569         *result_len = 0;
6570         return hr;
6571     }
6572
6573     *result_len = len;
6574     if(len+1 > output_len)
6575         return STRSAFE_E_INSUFFICIENT_BUFFER;
6576
6577     hr = IUri_GetHost(uri, &received);
6578     if(FAILED(hr)) {
6579         *result_len = 0;
6580         return hr;
6581     }
6582
6583     memcpy(output, received, (len+1)*sizeof(WCHAR));
6584     SysFreeString(received);
6585
6586     return S_OK;
6587 }
6588
6589 static HRESULT parse_domain(IUri *uri, LPWSTR output, DWORD output_len, DWORD *result_len)
6590 {
6591     HRESULT hr;
6592     DWORD len;
6593     BSTR received;
6594
6595     hr = IUri_GetPropertyLength(uri, Uri_PROPERTY_DOMAIN, &len, 0);
6596     if(FAILED(hr)) {
6597         *result_len = 0;
6598         return hr;
6599     }
6600
6601     *result_len = len;
6602     if(len+1 > output_len)
6603         return STRSAFE_E_INSUFFICIENT_BUFFER;
6604
6605     hr = IUri_GetDomain(uri, &received);
6606     if(FAILED(hr)) {
6607         *result_len = 0;
6608         return hr;
6609     }
6610
6611     memcpy(output, received, (len+1)*sizeof(WCHAR));
6612     SysFreeString(received);
6613
6614     return S_OK;
6615 }
6616
6617 static HRESULT parse_anchor(IUri *uri, LPWSTR output, DWORD output_len, DWORD *result_len)
6618 {
6619     HRESULT hr;
6620     DWORD len;
6621     BSTR received;
6622
6623     hr = IUri_GetPropertyLength(uri, Uri_PROPERTY_FRAGMENT, &len, 0);
6624     if(FAILED(hr)) {
6625         *result_len = 0;
6626         return hr;
6627     }
6628
6629     *result_len = len;
6630     if(len+1 > output_len)
6631         return STRSAFE_E_INSUFFICIENT_BUFFER;
6632
6633     hr = IUri_GetFragment(uri, &received);
6634     if(FAILED(hr)) {
6635         *result_len = 0;
6636         return hr;
6637     }
6638
6639     memcpy(output, received, (len+1)*sizeof(WCHAR));
6640     SysFreeString(received);
6641
6642     return S_OK;
6643 }
6644
6645 /***********************************************************************
6646  *           CoInternetParseIUri (urlmon.@)
6647  */
6648 HRESULT WINAPI CoInternetParseIUri(IUri *pIUri, PARSEACTION ParseAction, DWORD dwFlags,
6649                                    LPWSTR pwzResult, DWORD cchResult, DWORD *pcchResult,
6650                                    DWORD_PTR dwReserved)
6651 {
6652     HRESULT hr;
6653     Uri *uri;
6654     IInternetProtocolInfo *info;
6655
6656     TRACE("(%p %d %x %p %d %p %x)\n", pIUri, ParseAction, dwFlags, pwzResult,
6657         cchResult, pcchResult, (DWORD)dwReserved);
6658
6659     if(!pcchResult)
6660         return E_POINTER;
6661
6662     if(!pwzResult || !pIUri) {
6663         *pcchResult = 0;
6664         return E_INVALIDARG;
6665     }
6666
6667     if(!(uri = get_uri_obj(pIUri))) {
6668         *pcchResult = 0;
6669         FIXME("(%p %d %x %p %d %p %x) Unknown IUri's not supported for this action.\n",
6670             pIUri, ParseAction, dwFlags, pwzResult, cchResult, pcchResult, (DWORD)dwReserved);
6671         return E_NOTIMPL;
6672     }
6673
6674     info = get_protocol_info(uri->canon_uri);
6675     if(info) {
6676         hr = IInternetProtocolInfo_ParseUrl(info, uri->canon_uri, ParseAction, dwFlags,
6677                                             pwzResult, cchResult, pcchResult, 0);
6678         IInternetProtocolInfo_Release(info);
6679         if(SUCCEEDED(hr)) return hr;
6680     }
6681
6682     switch(ParseAction) {
6683     case PARSE_CANONICALIZE:
6684         hr = parse_canonicalize(uri, dwFlags, pwzResult, cchResult, pcchResult);
6685         break;
6686     case PARSE_FRIENDLY:
6687         hr = parse_friendly(pIUri, pwzResult, cchResult, pcchResult);
6688         break;
6689     case PARSE_ROOTDOCUMENT:
6690         hr = parse_rootdocument(uri, pwzResult, cchResult, pcchResult);
6691         break;
6692     case PARSE_DOCUMENT:
6693         hr = parse_document(uri, pwzResult, cchResult, pcchResult);
6694         break;
6695     case PARSE_PATH_FROM_URL:
6696         hr = parse_path_from_url(uri, pwzResult, cchResult, pcchResult);
6697         break;
6698     case PARSE_URL_FROM_PATH:
6699         hr = parse_url_from_path(pIUri, pwzResult, cchResult, pcchResult);
6700         break;
6701     case PARSE_SCHEMA:
6702         hr = parse_schema(pIUri, pwzResult, cchResult, pcchResult);
6703         break;
6704     case PARSE_SITE:
6705         hr = parse_site(pIUri, pwzResult, cchResult, pcchResult);
6706         break;
6707     case PARSE_DOMAIN:
6708         hr = parse_domain(pIUri, pwzResult, cchResult, pcchResult);
6709         break;
6710     case PARSE_LOCATION:
6711     case PARSE_ANCHOR:
6712         hr = parse_anchor(pIUri, pwzResult, cchResult, pcchResult);
6713         break;
6714     case PARSE_SECURITY_URL:
6715     case PARSE_MIME:
6716     case PARSE_SERVER:
6717     case PARSE_SECURITY_DOMAIN:
6718         *pcchResult = 0;
6719         hr = E_FAIL;
6720         break;
6721     default:
6722         *pcchResult = 0;
6723         hr = E_NOTIMPL;
6724         FIXME("(%p %d %x %p %d %p %x) Partial stub.\n", pIUri, ParseAction, dwFlags,
6725             pwzResult, cchResult, pcchResult, (DWORD)dwReserved);
6726     }
6727
6728     return hr;
6729 }