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