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