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