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