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