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