urlmon: Improved MapUrlToZone{Ex2} and GetSecurityId support.
[wine] / dlls / urlmon / sec_mgr.c
1 /*
2  * Internet Security and Zone Manager
3  *
4  * Copyright (c) 2004 Huw D M Davies
5  * Copyright 2004 Jacek Caban
6  * Copyright 2009 Detlef Riekenberg
7  * Copyright 2011 Thomas Mullaly for CodeWeavers
8  *
9  * This library is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public
11  * License as published by the Free Software Foundation; either
12  * version 2.1 of the License, or (at your option) any later version.
13  *
14  * This library is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public
20  * License along with this library; if not, write to the Free Software
21  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
22  */
23
24 #include <stdio.h>
25
26 #include "urlmon_main.h"
27 #include "winreg.h"
28 #include "wininet.h"
29
30 #define NO_SHLWAPI_REG
31 #include "shlwapi.h"
32
33 #include "wine/debug.h"
34
35 WINE_DEFAULT_DEBUG_CHANNEL(urlmon);
36
37 static const WCHAR currentlevelW[] = {'C','u','r','r','e','n','t','L','e','v','e','l',0};
38 static const WCHAR descriptionW[] = {'D','e','s','c','r','i','p','t','i','o','n',0};
39 static const WCHAR displaynameW[] = {'D','i','s','p','l','a','y','N','a','m','e',0};
40 static const WCHAR fileW[] = {'f','i','l','e',0};
41 static const WCHAR flagsW[] = {'F','l','a','g','s',0};
42 static const WCHAR iconW[] = {'I','c','o','n',0};
43 static const WCHAR minlevelW[] = {'M','i','n','L','e','v','e','l',0};
44 static const WCHAR recommendedlevelW[] = {'R','e','c','o','m','m','e','n','d','e','d',
45                                           'L','e','v','e','l',0};
46 static const WCHAR wszZonesKey[] = {'S','o','f','t','w','a','r','e','\\',
47                                     'M','i','c','r','o','s','o','f','t','\\',
48                                     'W','i','n','d','o','w','s','\\',
49                                     'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
50                                     'I','n','t','e','r','n','e','t',' ','S','e','t','t','i','n','g','s','\\',
51                                     'Z','o','n','e','s','\\',0};
52 static const WCHAR wszZoneMapDomainsKey[] = {'S','o','f','t','w','a','r','e','\\',
53                                              'M','i','c','r','o','s','o','f','t','\\',
54                                              'W','i','n','d','o','w','s','\\',
55                                              'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
56                                              'I','n','t','e','r','n','e','t',' ','S','e','t','t','i','n','g','s','\\',
57                                              'Z','o','n','e','M','a','p','\\',
58                                              'D','o','m','a','i','n','s',0};
59
60 static inline BOOL is_drive_path(const WCHAR *path)
61 {
62     return isalphaW(*path) && *(path+1) == ':';
63 }
64
65 /* List of schemes types Windows seems to expect to be hierarchical. */
66 static inline BOOL is_hierarchical_scheme(URL_SCHEME type) {
67     return(type == URL_SCHEME_HTTP || type == URL_SCHEME_FTP ||
68            type == URL_SCHEME_GOPHER || type == URL_SCHEME_NNTP ||
69            type == URL_SCHEME_TELNET || type == URL_SCHEME_WAIS ||
70            type == URL_SCHEME_FILE || type == URL_SCHEME_HTTPS ||
71            type == URL_SCHEME_RES);
72 }
73
74 /********************************************************************
75  * get_string_from_reg [internal]
76  *
77  * helper to get a string from the reg.
78  *
79  */
80 static void get_string_from_reg(HKEY hcu, HKEY hklm, LPCWSTR name, LPWSTR out, DWORD maxlen)
81 {
82     DWORD type = REG_SZ;
83     DWORD len = maxlen * sizeof(WCHAR);
84     DWORD res;
85
86     res = RegQueryValueExW(hcu, name, NULL, &type, (LPBYTE) out, &len);
87
88     if (res && hklm) {
89         len = maxlen * sizeof(WCHAR);
90         type = REG_SZ;
91         res = RegQueryValueExW(hklm, name, NULL, &type, (LPBYTE) out, &len);
92     }
93
94     if (res) {
95         TRACE("%s failed: %d\n", debugstr_w(name), res);
96         *out = '\0';
97     }
98 }
99
100 /********************************************************************
101  * get_dword_from_reg [internal]
102  *
103  * helper to get a dword from the reg.
104  *
105  */
106 static void get_dword_from_reg(HKEY hcu, HKEY hklm, LPCWSTR name, LPDWORD out)
107 {
108     DWORD type = REG_DWORD;
109     DWORD len = sizeof(DWORD);
110     DWORD res;
111
112     res = RegQueryValueExW(hcu, name, NULL, &type, (LPBYTE) out, &len);
113
114     if (res && hklm) {
115         len = sizeof(DWORD);
116         type = REG_DWORD;
117         res = RegQueryValueExW(hklm, name, NULL, &type, (LPBYTE) out, &len);
118     }
119
120     if (res) {
121         TRACE("%s failed: %d\n", debugstr_w(name), res);
122         *out = 0;
123     }
124 }
125
126 static HRESULT get_zone_from_reg(LPCWSTR schema, DWORD *zone)
127 {
128     DWORD res, size;
129     HKEY hkey;
130
131     static const WCHAR wszZoneMapProtocolKey[] =
132         {'S','o','f','t','w','a','r','e','\\',
133          'M','i','c','r','o','s','o','f','t','\\',
134          'W','i','n','d','o','w','s','\\',
135          'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
136          'I','n','t','e','r','n','e','t',' ','S','e','t','t','i','n','g','s','\\',
137          'Z','o','n','e','M','a','p','\\',
138          'P','r','o','t','o','c','o','l','D','e','f','a','u','l','t','s',0};
139
140     res = RegOpenKeyW(HKEY_CURRENT_USER, wszZoneMapProtocolKey, &hkey);
141     if(res != ERROR_SUCCESS) {
142         ERR("Could not open key %s\n", debugstr_w(wszZoneMapProtocolKey));
143         return E_UNEXPECTED;
144     }
145
146     size = sizeof(DWORD);
147     res = RegQueryValueExW(hkey, schema, NULL, NULL, (PBYTE)zone, &size);
148     RegCloseKey(hkey);
149     if(res == ERROR_SUCCESS)
150         return S_OK;
151
152     res = RegOpenKeyW(HKEY_LOCAL_MACHINE, wszZoneMapProtocolKey, &hkey);
153     if(res != ERROR_SUCCESS) {
154         ERR("Could not open key %s\n", debugstr_w(wszZoneMapProtocolKey));
155         return E_UNEXPECTED;
156     }
157
158     size = sizeof(DWORD);
159     res = RegQueryValueExW(hkey, schema, NULL, NULL, (PBYTE)zone, &size);
160     RegCloseKey(hkey);
161     if(res == ERROR_SUCCESS)
162         return S_OK;
163
164     *zone = 3;
165     return S_OK;
166 }
167
168 /********************************************************************
169  * matches_domain_pattern [internal]
170  *
171  * Checks if the given string matches the specified domain pattern.
172  *
173  * This function looks for explicit wildcard domain components iff
174  * they appear at the very beginning of the 'pattern' string
175  *
176  *  pattern = "*.google.com"
177  */
178 static BOOL matches_domain_pattern(LPCWSTR pattern, LPCWSTR str, BOOL implicit_wildcard, LPCWSTR *matched)
179 {
180     BOOL matches = FALSE;
181     DWORD pattern_len = strlenW(pattern);
182     DWORD str_len = strlenW(str);
183
184     TRACE("(%d) Checking if %s matches %s\n", implicit_wildcard, debugstr_w(str), debugstr_w(pattern));
185
186     *matched = NULL;
187     if(str_len >= pattern_len) {
188         /* Check if there's an explicit wildcard in the pattern. */
189         if(pattern[0] == '*' && pattern[1] == '.') {
190             /* Make sure that 'str' matches the wildcard pattern.
191              *
192              * Example:
193              *  pattern = "*.google.com"
194              *
195              * So in this case 'str' would have to end with ".google.com" in order
196              * to map to this pattern.
197              */
198             if(str_len >= pattern_len+1 && !strcmpiW(str+(str_len-pattern_len+1), pattern+1)) {
199                 /* Check if there's another '.' inside of the "unmatched" portion
200                  * of 'str'.
201                  *
202                  * Example:
203                  *  pattern = "*.google.com"
204                  *  str     = "test.testing.google.com"
205                  *
206                  * The currently matched portion is ".google.com" in 'str', we need
207                  * see if there's a '.' inside of the unmatched portion ("test.testing"), because
208                  * if there is and 'implicit_wildcard' isn't set, then this isn't
209                  * a match.
210                  */
211                 const WCHAR *ptr;
212                 if(str_len > pattern_len+1 && (ptr = memrchrW(str, '.', str_len-pattern_len-2))) {
213                     if(implicit_wildcard) {
214                         matches = TRUE;
215                         *matched = ptr+1;
216                     }
217                 } else {
218                     matches = TRUE;
219                     *matched = str;
220                 }
221             }
222         } else if(implicit_wildcard && str_len > pattern_len) {
223             /* When the pattern has an implicit wildcard component, it means
224              * that anything goes in 'str' as long as it ends with the pattern
225              * and that the beginning of the match has a '.' before it.
226              *
227              * Example:
228              *  pattern = "google.com"
229              *  str     = "www.google.com"
230              *
231              * Implicitly matches the pattern, where as:
232              *
233              *  pattern = "google.com"
234              *  str     = "wwwgoogle.com"
235              *
236              * Doesn't match the pattern.
237              */
238             if(str_len > pattern_len) {
239                 if(str[str_len-pattern_len-1] == '.' && !strcmpiW(str+(str_len-pattern_len), pattern)) {
240                     matches = TRUE;
241                     *matched = str+(str_len-pattern_len);
242                 }
243             }
244         } else {
245             /* The pattern doesn't have an implicit wildcard, or an explicit wildcard,
246              * so 'str' has to be an exact match to the 'pattern'.
247              */
248             if(!strcmpiW(str, pattern)) {
249                 matches = TRUE;
250                 *matched = str;
251             }
252         }
253     }
254
255     if(matches)
256         TRACE("Found a match: matched=%s\n", debugstr_w(*matched));
257     else
258         TRACE("No match found\n");
259
260     return matches;
261 }
262
263 static BOOL get_zone_for_scheme(HKEY key, LPCWSTR schema, DWORD *zone)
264 {
265     static const WCHAR wildcardW[] = {'*',0};
266
267     DWORD res;
268     DWORD size = sizeof(DWORD);
269     DWORD type;
270
271     /* See if the key contains a value for the scheme first. */
272     res = RegQueryValueExW(key, schema, NULL, &type, (BYTE*)zone, &size);
273     if(res == ERROR_SUCCESS) {
274         if(type == REG_DWORD)
275             return TRUE;
276         WARN("Unexpected value type %d for value %s, expected REG_DWORD\n", type, debugstr_w(schema));
277     }
278
279     /* Try to get the zone for the wildcard scheme. */
280     size = sizeof(DWORD);
281     res = RegQueryValueExW(key, wildcardW, NULL, &type, (BYTE*)zone, &size);
282     if(res != ERROR_SUCCESS)
283         return FALSE;
284
285     if(type != REG_DWORD) {
286         WARN("Unexpected value type %d for value %s, expected REG_DWORD\n", type, debugstr_w(wildcardW));
287         return FALSE;
288     }
289
290     return TRUE;
291 }
292
293 /********************************************************************
294  * search_domain_for_zone [internal]
295  *
296  * Searches the specified 'domain' registry key to see if 'host' maps into it, or any
297  * of it's subdomain registry keys.
298  *
299  * Returns S_OK if a match is found, S_FALSE if no matches were found, or an error code.
300  */
301 static HRESULT search_domain_for_zone(HKEY domains, LPCWSTR domain, DWORD domain_len, LPCWSTR schema,
302                                       LPCWSTR host, DWORD host_len, DWORD *zone)
303 {
304     BOOL found = FALSE;
305     HKEY domain_key;
306     DWORD res;
307     LPCWSTR matched;
308
309     if(host_len >= domain_len && matches_domain_pattern(domain, host, TRUE, &matched)) {
310         res = RegOpenKeyW(domains, domain, &domain_key);
311         if(res != ERROR_SUCCESS) {
312             ERR("Failed to open domain key %s: %d\n", debugstr_w(domain), res);
313             return E_UNEXPECTED;
314         }
315
316         if(matched == host)
317             found = get_zone_for_scheme(domain_key, schema, zone);
318         else {
319             INT domain_offset;
320             DWORD subdomain_count, subdomain_len;
321             BOOL check_domain = TRUE;
322
323             find_domain_name(domain, domain_len, &domain_offset);
324
325             res = RegQueryInfoKeyW(domain_key, NULL, NULL, NULL, &subdomain_count, &subdomain_len,
326                                    NULL, NULL, NULL, NULL, NULL, NULL);
327             if(res != ERROR_SUCCESS) {
328                 ERR("Unable to query info for key %s: %d\n", debugstr_w(domain), res);
329                 RegCloseKey(domain_key);
330                 return E_UNEXPECTED;
331             }
332
333             if(subdomain_count) {
334                 WCHAR *subdomain;
335                 WCHAR *component;
336                 DWORD i;
337
338                 subdomain = heap_alloc((subdomain_len+1)*sizeof(WCHAR));
339                 if(!subdomain) {
340                     RegCloseKey(domain_key);
341                     return E_OUTOFMEMORY;
342                 }
343
344                 component = heap_strndupW(host, matched-host-1);
345                 if(!component) {
346                     heap_free(subdomain);
347                     RegCloseKey(domain_key);
348                     return E_OUTOFMEMORY;
349                 }
350
351                 for(i = 0; i < subdomain_count; ++i) {
352                     DWORD len = subdomain_len+1;
353                     const WCHAR *sub_matched;
354
355                     res = RegEnumKeyExW(domain_key, i, subdomain, &len, NULL, NULL, NULL, NULL);
356                     if(res != ERROR_SUCCESS) {
357                         heap_free(component);
358                         heap_free(subdomain);
359                         RegCloseKey(domain_key);
360                         return E_UNEXPECTED;
361                     }
362
363                     if(matches_domain_pattern(subdomain, component, FALSE, &sub_matched)) {
364                         HKEY subdomain_key;
365
366                         res = RegOpenKeyW(domain_key, subdomain, &subdomain_key);
367                         if(res != ERROR_SUCCESS) {
368                             ERR("Unable to open subdomain key %s of %s: %d\n", debugstr_w(subdomain),
369                                 debugstr_w(domain), res);
370                             heap_free(component);
371                             heap_free(subdomain);
372                             RegCloseKey(domain_key);
373                             return E_UNEXPECTED;
374                         }
375
376                         found = get_zone_for_scheme(subdomain_key, schema, zone);
377                         check_domain = FALSE;
378                         RegCloseKey(subdomain_key);
379                         break;
380                     }
381                 }
382                 heap_free(subdomain);
383                 heap_free(component);
384             }
385
386             /* There's a chance that 'host' implicitly mapped into 'domain', in
387              * which case we check to see if 'domain' contains zone information.
388              *
389              * This can only happen if 'domain' is it's own domain name.
390              *  Example:
391              *      "google.com" (domain name = "google.com")
392              *
393              *  So if:
394              *      host = "www.google.com"
395              *
396              *  Then host would map directly into the "google.com" domain key.
397              *
398              * If 'domain' has more than just it's domain name, or it does not
399              * have a domain name, then we don't perform the check. The reason
400              * for this is that these domains don't allow implicit mappings.
401              *  Example:
402              *      domain = "org" (has no domain name)
403              *      host   = "www.org"
404              *
405              *  The mapping would only happen if the "org" key had an explicit subkey
406              *  called "www".
407              */
408             if(check_domain && !domain_offset && !strchrW(host, matched-host-1))
409                 found = get_zone_for_scheme(domain_key, schema, zone);
410         }
411         RegCloseKey(domain_key);
412     }
413
414     return found ? S_OK : S_FALSE;
415 }
416
417 static HRESULT search_for_domain_mapping(HKEY domains, LPCWSTR schema, LPCWSTR host, DWORD host_len, DWORD *zone)
418 {
419     WCHAR *domain;
420     DWORD domain_count, domain_len, i;
421     DWORD res;
422     HRESULT hres = S_FALSE;
423
424     res = RegQueryInfoKeyW(domains, NULL, NULL, NULL, &domain_count, &domain_len,
425                            NULL, NULL, NULL, NULL, NULL, NULL);
426     if(res != ERROR_SUCCESS) {
427         WARN("Failed to retrieve information about key\n");
428         return E_UNEXPECTED;
429     }
430
431     if(!domain_count)
432         return S_FALSE;
433
434     domain = heap_alloc((domain_len+1)*sizeof(WCHAR));
435     if(!domain)
436         return E_OUTOFMEMORY;
437
438     for(i = 0; i < domain_count; ++i) {
439         DWORD len = domain_len+1;
440
441         res = RegEnumKeyExW(domains, i, domain, &len, NULL, NULL, NULL, NULL);
442         if(res != ERROR_SUCCESS) {
443             heap_free(domain);
444             return E_UNEXPECTED;
445         }
446
447         hres = search_domain_for_zone(domains, domain, len, schema, host, host_len, zone);
448         if(FAILED(hres) || hres == S_OK)
449             break;
450     }
451
452     heap_free(domain);
453     return hres;
454 }
455
456 static HRESULT get_zone_from_domains(IUri *uri, DWORD *zone)
457 {
458     HRESULT hres;
459     BSTR host, scheme;
460     DWORD res;
461     HKEY domains;
462     DWORD scheme_type;
463
464     hres = IUri_GetScheme(uri, &scheme_type);
465     if(FAILED(hres))
466         return hres;
467
468     /* Windows doesn't play nice with unknown scheme types when it tries
469      * to check if a host name maps into any domains.
470      */
471     if(scheme_type == URL_SCHEME_UNKNOWN)
472         return S_FALSE;
473
474     hres = IUri_GetHost(uri, &host);
475     if(FAILED(hres))
476         return hres;
477
478     /* Known hierarchical scheme types must have a host. If they don't Windows
479      * assigns URLZONE_INVALID to the zone.
480      */
481     if((scheme_type != URL_SCHEME_UNKNOWN && scheme_type != URL_SCHEME_FILE)
482         && is_hierarchical_scheme(scheme_type) && !*host) {
483         *zone = URLZONE_INVALID;
484
485         SysFreeString(host);
486
487         /* The MapUrlToZone functions return S_OK when this condition occurs. */
488         return S_OK;
489     }
490
491     hres = IUri_GetSchemeName(uri, &scheme);
492     if(FAILED(hres)) {
493         SysFreeString(host);
494         return hres;
495     }
496
497     /* First try CURRENT_USER. */
498     res = RegOpenKeyW(HKEY_CURRENT_USER, wszZoneMapDomainsKey, &domains);
499     if(res == ERROR_SUCCESS) {
500         hres = search_for_domain_mapping(domains, scheme, host, SysStringLen(host), zone);
501         RegCloseKey(domains);
502     } else
503         WARN("Failed to open HKCU's %s key\n", debugstr_w(wszZoneMapDomainsKey));
504
505     /* If that doesn't work try LOCAL_MACHINE. */
506     if(hres == S_FALSE) {
507         res = RegOpenKeyW(HKEY_LOCAL_MACHINE, wszZoneMapDomainsKey, &domains);
508         if(res == ERROR_SUCCESS) {
509             hres = search_for_domain_mapping(domains, scheme, host, SysStringLen(host), zone);
510             RegCloseKey(domains);
511         } else
512             WARN("Failed to open HKLM's %s key\n", debugstr_w(wszZoneMapDomainsKey));
513     }
514
515     SysFreeString(host);
516     SysFreeString(scheme);
517     return hres;
518 }
519
520 static HRESULT map_security_uri_to_zone(IUri *uri, DWORD *zone)
521 {
522     HRESULT hres;
523     BSTR scheme;
524
525     *zone = URLZONE_INVALID;
526
527     hres = IUri_GetSchemeName(uri, &scheme);
528     if(FAILED(hres))
529         return hres;
530
531     if(!strcmpiW(scheme, fileW)) {
532         BSTR path;
533         WCHAR *ptr, *path_start, root[20];
534
535         hres = IUri_GetPath(uri, &path);
536         if(FAILED(hres)) {
537             SysFreeString(scheme);
538             return hres;
539         }
540
541         if(*path == '/' && is_drive_path(path+1))
542             path_start = path+1;
543         else
544             path_start = path;
545
546         if(((ptr = strchrW(path_start, '\\')) || (ptr = strchrW(path_start, '/'))) && ptr-path_start < sizeof(root)/sizeof(WCHAR)) {
547             UINT type;
548
549             memcpy(root, path_start, (ptr-path_start)*sizeof(WCHAR));
550             root[ptr-path_start] = 0;
551
552             type = GetDriveTypeW(root);
553
554             switch(type) {
555             case DRIVE_UNKNOWN:
556             case DRIVE_NO_ROOT_DIR:
557                 break;
558             case DRIVE_REMOVABLE:
559             case DRIVE_FIXED:
560             case DRIVE_CDROM:
561             case DRIVE_RAMDISK:
562                 *zone = URLZONE_LOCAL_MACHINE;
563                 hres = S_OK;
564                 break;
565             case DRIVE_REMOTE:
566                 *zone = URLZONE_INTERNET;
567                 hres = S_OK;
568                 break;
569             default:
570                 FIXME("unsupported drive type %d\n", type);
571             }
572         }
573         SysFreeString(path);
574     }
575
576     if(*zone == URLZONE_INVALID) {
577         hres = get_zone_from_domains(uri, zone);
578         if(hres == S_FALSE)
579             hres = get_zone_from_reg(scheme, zone);
580     }
581
582     SysFreeString(scheme);
583     return hres;
584 }
585
586 static HRESULT map_url_to_zone(LPCWSTR url, DWORD *zone, LPWSTR *ret_url)
587 {
588     IUri *secur_uri;
589     LPWSTR secur_url;
590     HRESULT hres;
591
592     *zone = URLZONE_INVALID;
593
594     hres = CoInternetGetSecurityUrl(url, &secur_url, PSU_SECURITY_URL_ONLY, 0);
595     if(hres != S_OK) {
596         DWORD size = strlenW(url)*sizeof(WCHAR);
597
598         secur_url = CoTaskMemAlloc(size);
599         if(!secur_url)
600             return E_OUTOFMEMORY;
601
602         memcpy(secur_url, url, size);
603     }
604
605     hres = CreateUri(secur_url, 0, 0, &secur_uri);
606     if(FAILED(hres)) {
607         CoTaskMemFree(secur_url);
608         return hres;
609     }
610
611     hres = map_security_uri_to_zone(secur_uri, zone);
612     IUri_Release(secur_uri);
613
614     if(FAILED(hres) || !ret_url)
615         CoTaskMemFree(secur_url);
616     else
617         *ret_url = secur_url;
618
619     return hres;
620 }
621
622 static HRESULT map_uri_to_zone(IUri *uri, DWORD *zone)
623 {
624     HRESULT hres;
625     IUri *secur_uri;
626
627     hres = CoInternetGetSecurityUrlEx(uri, &secur_uri, PSU_SECURITY_URL_ONLY, 0);
628     if(FAILED(hres))
629         return hres;
630
631     hres = map_security_uri_to_zone(secur_uri, zone);
632     IUri_Release(secur_uri);
633
634     return hres;
635 }
636
637 static HRESULT open_zone_key(HKEY parent_key, DWORD zone, HKEY *hkey)
638 {
639     static const WCHAR wszFormat[] = {'%','s','%','u',0};
640
641     WCHAR key_name[sizeof(wszZonesKey)/sizeof(WCHAR)+12];
642     DWORD res;
643
644     wsprintfW(key_name, wszFormat, wszZonesKey, zone);
645
646     res = RegOpenKeyW(parent_key, key_name, hkey);
647
648     if(res != ERROR_SUCCESS) {
649         WARN("RegOpenKey failed\n");
650         return E_INVALIDARG;
651     }
652
653     return S_OK;
654 }
655
656 static HRESULT get_action_policy(DWORD zone, DWORD action, BYTE *policy, DWORD size, URLZONEREG zone_reg)
657 {
658     HKEY parent_key;
659     HKEY hkey;
660     LONG res;
661     HRESULT hres;
662
663     switch(action) {
664     case URLACTION_SCRIPT_OVERRIDE_SAFETY:
665     case URLACTION_ACTIVEX_OVERRIDE_SCRIPT_SAFETY:
666         *(DWORD*)policy = URLPOLICY_DISALLOW;
667         return S_OK;
668     }
669
670     switch(zone_reg) {
671     case URLZONEREG_DEFAULT:
672     case URLZONEREG_HKCU:
673         parent_key = HKEY_CURRENT_USER;
674         break;
675     case URLZONEREG_HKLM:
676         parent_key = HKEY_LOCAL_MACHINE;
677         break;
678     default:
679         WARN("Unknown URLZONEREG: %d\n", zone_reg);
680         return E_FAIL;
681     };
682
683     hres = open_zone_key(parent_key, zone, &hkey);
684     if(SUCCEEDED(hres)) {
685         WCHAR action_str[16];
686         DWORD len = size;
687
688         static const WCHAR formatW[] = {'%','X',0};
689
690         wsprintfW(action_str, formatW, action);
691
692         res = RegQueryValueExW(hkey, action_str, NULL, NULL, policy, &len);
693         if(res == ERROR_MORE_DATA) {
694             hres = E_INVALIDARG;
695         }else if(res == ERROR_FILE_NOT_FOUND) {
696             hres = E_FAIL;
697         }else if(res != ERROR_SUCCESS) {
698             ERR("RegQueryValue failed: %d\n", res);
699             hres = E_UNEXPECTED;
700         }
701
702         RegCloseKey(hkey);
703     }
704
705     if(FAILED(hres) && zone_reg == URLZONEREG_DEFAULT)
706         return get_action_policy(zone, action, policy, size, URLZONEREG_HKLM);
707
708     return hres;
709 }
710
711 static HRESULT get_security_id(LPCWSTR url, BYTE *secid, DWORD *secid_len)
712 {
713     LPWSTR secur_url, ptr, ptr2;
714     DWORD zone, len;
715     HRESULT hres;
716
717     static const WCHAR wszFile[] = {'f','i','l','e',':'};
718
719     hres = map_url_to_zone(url, &zone, &secur_url);
720     if(zone == URLZONE_INVALID)
721         return (hres == 0x80041001 || hres == S_OK) ? E_INVALIDARG : hres;
722
723     /* file protocol is a special case */
724     if(strlenW(secur_url) >= sizeof(wszFile)/sizeof(WCHAR)
725             && !memcmp(secur_url, wszFile, sizeof(wszFile))) {
726         WCHAR path[MAX_PATH];
727         len = sizeof(path)/sizeof(WCHAR);
728
729         hres = CoInternetParseUrl(secur_url, PARSE_PATH_FROM_URL, 0, path, len, &len, 0);
730         if(hres == S_OK && !PathIsNetworkPathW(path)) {
731             static const BYTE secidFile[] = {'f','i','l','e',':'};
732
733             CoTaskMemFree(secur_url);
734
735             if(*secid_len < sizeof(secidFile)+sizeof(zone))
736                 return HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER);
737
738             memcpy(secid, secidFile, sizeof(secidFile));
739             *(DWORD*)(secid+sizeof(secidFile)) = zone;
740
741             *secid_len = sizeof(secidFile)+sizeof(zone);
742             return S_OK;
743         }
744     }
745
746     ptr = strchrW(secur_url, ':');
747     ptr2 = ++ptr;
748     while(*ptr2 == '/')
749         ptr2++;
750     if(ptr2 != ptr)
751         memmove(ptr, ptr2, (strlenW(ptr2)+1)*sizeof(WCHAR));
752
753     ptr = strchrW(ptr, '/');
754     if(ptr)
755         *ptr = 0;
756
757     len = WideCharToMultiByte(CP_ACP, 0, secur_url, -1, NULL, 0, NULL, NULL)-1;
758
759     if(len+sizeof(DWORD) > *secid_len) {
760         CoTaskMemFree(secur_url);
761         return HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER);
762     }
763
764     WideCharToMultiByte(CP_ACP, 0, secur_url, -1, (LPSTR)secid, len, NULL, NULL);
765     CoTaskMemFree(secur_url);
766
767     *(DWORD*)(secid+len) = zone;
768
769     *secid_len = len+sizeof(DWORD);
770
771     return S_OK;
772 }
773
774 /***********************************************************************
775  *           InternetSecurityManager implementation
776  *
777  */
778 typedef struct {
779     IInternetSecurityManagerEx2 IInternetSecurityManagerEx2_iface;
780
781     LONG ref;
782
783     IInternetSecurityMgrSite *mgrsite;
784     IInternetSecurityManager *custom_manager;
785 } SecManagerImpl;
786
787 static inline SecManagerImpl *impl_from_IInternetSecurityManagerEx2(IInternetSecurityManagerEx2 *iface)
788 {
789     return CONTAINING_RECORD(iface, SecManagerImpl, IInternetSecurityManagerEx2_iface);
790 }
791
792 static HRESULT WINAPI SecManagerImpl_QueryInterface(IInternetSecurityManagerEx2* iface,REFIID riid,void** ppvObject)
793 {
794     SecManagerImpl *This = impl_from_IInternetSecurityManagerEx2(iface);
795
796     TRACE("(%p)->(%s,%p)\n",This,debugstr_guid(riid),ppvObject);
797
798     /* Perform a sanity check on the parameters.*/
799     if ( (This==0) || (ppvObject==0) )
800         return E_INVALIDARG;
801
802     /* Initialize the return parameter */
803     *ppvObject = 0;
804
805     /* Compare the riid with the interface IDs implemented by this object.*/
806     if (IsEqualIID(&IID_IUnknown, riid) ||
807         IsEqualIID(&IID_IInternetSecurityManager, riid) ||
808         IsEqualIID(&IID_IInternetSecurityManagerEx, riid) ||
809         IsEqualIID(&IID_IInternetSecurityManagerEx2, riid))
810         *ppvObject = iface;
811
812     /* Check that we obtained an interface.*/
813     if (!*ppvObject) {
814         WARN("not supported interface %s\n", debugstr_guid(riid));
815         return E_NOINTERFACE;
816     }
817
818     /* Query Interface always increases the reference count by one when it is successful */
819     IInternetSecurityManager_AddRef(iface);
820
821     return S_OK;
822 }
823
824 static ULONG WINAPI SecManagerImpl_AddRef(IInternetSecurityManagerEx2* iface)
825 {
826     SecManagerImpl *This = impl_from_IInternetSecurityManagerEx2(iface);
827     ULONG refCount = InterlockedIncrement(&This->ref);
828
829     TRACE("(%p) ref=%u\n", This, refCount);
830
831     return refCount;
832 }
833
834 static ULONG WINAPI SecManagerImpl_Release(IInternetSecurityManagerEx2* iface)
835 {
836     SecManagerImpl *This = impl_from_IInternetSecurityManagerEx2(iface);
837     ULONG refCount = InterlockedDecrement(&This->ref);
838
839     TRACE("(%p) ref=%u\n", This, refCount);
840
841     /* destroy the object if there's no more reference on it */
842     if (!refCount){
843         if(This->mgrsite)
844             IInternetSecurityMgrSite_Release(This->mgrsite);
845         if(This->custom_manager)
846             IInternetSecurityManager_Release(This->custom_manager);
847
848         heap_free(This);
849
850         URLMON_UnlockModule();
851     }
852
853     return refCount;
854 }
855
856 static HRESULT WINAPI SecManagerImpl_SetSecuritySite(IInternetSecurityManagerEx2 *iface,
857                                                      IInternetSecurityMgrSite *pSite)
858 {
859     SecManagerImpl *This = impl_from_IInternetSecurityManagerEx2(iface);
860
861     TRACE("(%p)->(%p)\n", This, pSite);
862
863     if(This->mgrsite)
864         IInternetSecurityMgrSite_Release(This->mgrsite);
865
866     if(This->custom_manager) {
867         IInternetSecurityManager_Release(This->custom_manager);
868         This->custom_manager = NULL;
869     }
870
871     This->mgrsite = pSite;
872
873     if(pSite) {
874         IServiceProvider *servprov;
875         HRESULT hres;
876
877         IInternetSecurityMgrSite_AddRef(pSite);
878
879         hres = IInternetSecurityMgrSite_QueryInterface(pSite, &IID_IServiceProvider,
880                 (void**)&servprov);
881         if(SUCCEEDED(hres)) {
882             IServiceProvider_QueryService(servprov, &SID_SInternetSecurityManager,
883                     &IID_IInternetSecurityManager, (void**)&This->custom_manager);
884             IServiceProvider_Release(servprov);
885         }
886     }
887
888     return S_OK;
889 }
890
891 static HRESULT WINAPI SecManagerImpl_GetSecuritySite(IInternetSecurityManagerEx2 *iface,
892                                                      IInternetSecurityMgrSite **ppSite)
893 {
894     SecManagerImpl *This = impl_from_IInternetSecurityManagerEx2(iface);
895
896     TRACE("(%p)->(%p)\n", This, ppSite);
897
898     if(!ppSite)
899         return E_INVALIDARG;
900
901     if(This->mgrsite)
902         IInternetSecurityMgrSite_AddRef(This->mgrsite);
903
904     *ppSite = This->mgrsite;
905     return S_OK;
906 }
907
908 static HRESULT WINAPI SecManagerImpl_MapUrlToZone(IInternetSecurityManagerEx2 *iface,
909                                                   LPCWSTR pwszUrl, DWORD *pdwZone,
910                                                   DWORD dwFlags)
911 {
912     SecManagerImpl *This = impl_from_IInternetSecurityManagerEx2(iface);
913     HRESULT hres;
914
915     TRACE("(%p)->(%s %p %08x)\n", iface, debugstr_w(pwszUrl), pdwZone, dwFlags);
916
917     if(This->custom_manager) {
918         hres = IInternetSecurityManager_MapUrlToZone(This->custom_manager,
919                 pwszUrl, pdwZone, dwFlags);
920         if(hres != INET_E_DEFAULT_ACTION)
921             return hres;
922     }
923
924     if(!pwszUrl) {
925         *pdwZone = URLZONE_INVALID;
926         return E_INVALIDARG;
927     }
928
929     if(dwFlags)
930         FIXME("not supported flags: %08x\n", dwFlags);
931
932     return map_url_to_zone(pwszUrl, pdwZone, NULL);
933 }
934
935 static HRESULT WINAPI SecManagerImpl_GetSecurityId(IInternetSecurityManagerEx2 *iface,
936         LPCWSTR pwszUrl, BYTE *pbSecurityId, DWORD *pcbSecurityId, DWORD_PTR dwReserved)
937 {
938     SecManagerImpl *This = impl_from_IInternetSecurityManagerEx2(iface);
939
940     TRACE("(%p)->(%s %p %p %08lx)\n", iface, debugstr_w(pwszUrl), pbSecurityId,
941           pcbSecurityId, dwReserved);
942
943     if(This->custom_manager) {
944         HRESULT hres;
945
946         hres = IInternetSecurityManager_GetSecurityId(This->custom_manager,
947                 pwszUrl, pbSecurityId, pcbSecurityId, dwReserved);
948         if(hres != INET_E_DEFAULT_ACTION)
949             return hres;
950     }
951
952     if(!pwszUrl || !pbSecurityId || !pcbSecurityId)
953         return E_INVALIDARG;
954
955     if(dwReserved)
956         FIXME("dwReserved is not supported\n");
957
958     return get_security_id(pwszUrl, pbSecurityId, pcbSecurityId);
959 }
960
961
962 static HRESULT WINAPI SecManagerImpl_ProcessUrlAction(IInternetSecurityManagerEx2 *iface,
963                                                       LPCWSTR pwszUrl, DWORD dwAction,
964                                                       BYTE *pPolicy, DWORD cbPolicy,
965                                                       BYTE *pContext, DWORD cbContext,
966                                                       DWORD dwFlags, DWORD dwReserved)
967 {
968     SecManagerImpl *This = impl_from_IInternetSecurityManagerEx2(iface);
969     DWORD zone, policy;
970     HRESULT hres;
971
972     TRACE("(%p)->(%s %08x %p %08x %p %08x %08x %08x)\n", iface, debugstr_w(pwszUrl), dwAction,
973           pPolicy, cbPolicy, pContext, cbContext, dwFlags, dwReserved);
974
975     if(This->custom_manager) {
976         hres = IInternetSecurityManager_ProcessUrlAction(This->custom_manager, pwszUrl, dwAction,
977                 pPolicy, cbPolicy, pContext, cbContext, dwFlags, dwReserved);
978         if(hres != INET_E_DEFAULT_ACTION)
979             return hres;
980     }
981
982     if(dwFlags || dwReserved)
983         FIXME("Unsupported arguments\n");
984
985     if(!pwszUrl)
986         return E_INVALIDARG;
987
988     hres = map_url_to_zone(pwszUrl, &zone, NULL);
989     if(FAILED(hres))
990         return hres;
991
992     hres = get_action_policy(zone, dwAction, (BYTE*)&policy, sizeof(policy), URLZONEREG_DEFAULT);
993     if(FAILED(hres))
994         return hres;
995
996     TRACE("policy %x\n", policy);
997     if(cbPolicy >= sizeof(DWORD))
998         *(DWORD*)pPolicy = policy;
999
1000     switch(GetUrlPolicyPermissions(policy)) {
1001     case URLPOLICY_ALLOW:
1002     case URLPOLICY_CHANNEL_SOFTDIST_PRECACHE:
1003         return S_OK;
1004     case URLPOLICY_DISALLOW:
1005         return S_FALSE;
1006     case URLPOLICY_QUERY:
1007         FIXME("URLPOLICY_QUERY not implemented\n");
1008         return E_FAIL;
1009     default:
1010         FIXME("Not implemented policy %x\n", policy);
1011     }
1012
1013     return E_FAIL;
1014 }
1015                                                
1016
1017 static HRESULT WINAPI SecManagerImpl_QueryCustomPolicy(IInternetSecurityManagerEx2 *iface,
1018                                                        LPCWSTR pwszUrl, REFGUID guidKey,
1019                                                        BYTE **ppPolicy, DWORD *pcbPolicy,
1020                                                        BYTE *pContext, DWORD cbContext,
1021                                                        DWORD dwReserved)
1022 {
1023     SecManagerImpl *This = impl_from_IInternetSecurityManagerEx2(iface);
1024     HRESULT hres;
1025
1026     TRACE("(%p)->(%s %s %p %p %p %08x %08x )\n", iface, debugstr_w(pwszUrl), debugstr_guid(guidKey),
1027           ppPolicy, pcbPolicy, pContext, cbContext, dwReserved);
1028
1029     if(This->custom_manager) {
1030         hres = IInternetSecurityManager_QueryCustomPolicy(This->custom_manager, pwszUrl, guidKey,
1031                 ppPolicy, pcbPolicy, pContext, cbContext, dwReserved);
1032         if(hres != INET_E_DEFAULT_ACTION)
1033             return hres;
1034     }
1035
1036     WARN("Unknown guidKey %s\n", debugstr_guid(guidKey));
1037     return HRESULT_FROM_WIN32(ERROR_NOT_FOUND);
1038 }
1039
1040 static HRESULT WINAPI SecManagerImpl_SetZoneMapping(IInternetSecurityManagerEx2 *iface,
1041                                                     DWORD dwZone, LPCWSTR pwszPattern, DWORD dwFlags)
1042 {
1043     SecManagerImpl *This = impl_from_IInternetSecurityManagerEx2(iface);
1044     HRESULT hres;
1045
1046     TRACE("(%p)->(%08x %s %08x)\n", iface, dwZone, debugstr_w(pwszPattern),dwFlags);
1047
1048     if(This->custom_manager) {
1049         hres = IInternetSecurityManager_SetZoneMapping(This->custom_manager, dwZone,
1050                 pwszPattern, dwFlags);
1051         if(hres != INET_E_DEFAULT_ACTION)
1052             return hres;
1053     }
1054
1055     FIXME("Default action is not implemented\n");
1056     return E_NOTIMPL;
1057 }
1058
1059 static HRESULT WINAPI SecManagerImpl_GetZoneMappings(IInternetSecurityManagerEx2 *iface,
1060         DWORD dwZone, IEnumString **ppenumString, DWORD dwFlags)
1061 {
1062     SecManagerImpl *This = impl_from_IInternetSecurityManagerEx2(iface);
1063     HRESULT hres;
1064
1065     TRACE("(%p)->(%08x %p %08x)\n", iface, dwZone, ppenumString,dwFlags);
1066
1067     if(This->custom_manager) {
1068         hres = IInternetSecurityManager_GetZoneMappings(This->custom_manager, dwZone,
1069                 ppenumString, dwFlags);
1070         if(hres != INET_E_DEFAULT_ACTION)
1071             return hres;
1072     }
1073
1074     FIXME("Default action is not implemented\n");
1075     return E_NOTIMPL;
1076 }
1077
1078 static HRESULT WINAPI SecManagerImpl_ProcessUrlActionEx(IInternetSecurityManagerEx2 *iface,
1079         LPCWSTR pwszUrl, DWORD dwAction, BYTE *pPolicy, DWORD cbPolicy, BYTE *pContext, DWORD cbContext,
1080         DWORD dwFlags, DWORD dwReserved, DWORD *pdwOutFlags)
1081 {
1082     SecManagerImpl *This = impl_from_IInternetSecurityManagerEx2(iface);
1083     FIXME("(%p)->(%s %08x %p %d %p %d %08x %08x %p) stub\n", This, debugstr_w(pwszUrl), dwAction, pPolicy, cbPolicy,
1084           pContext, cbContext, dwFlags, dwReserved, pdwOutFlags);
1085     return E_NOTIMPL;
1086 }
1087
1088 static HRESULT WINAPI SecManagerImpl_MapUrlToZoneEx2(IInternetSecurityManagerEx2 *iface,
1089         IUri *pUri, DWORD *pdwZone, DWORD dwFlags, LPWSTR *ppwszMappedUrl, DWORD *pdwOutFlags)
1090 {
1091     SecManagerImpl *This = impl_from_IInternetSecurityManagerEx2(iface);
1092
1093     TRACE("(%p)->(%p %p %08x %p %p)\n", This, pUri, pdwZone, dwFlags, ppwszMappedUrl, pdwOutFlags);
1094
1095     if(This->custom_manager) {
1096         HRESULT hres;
1097         IInternetSecurityManagerEx2 *sec_mgr2;
1098
1099         hres = IInternetSecurityManager_QueryInterface(This->custom_manager, &IID_IInternetSecurityManagerEx2,
1100                 (void**)&sec_mgr2);
1101         if(SUCCEEDED(hres)) {
1102             hres = IInternetSecurityManagerEx2_MapUrlToZoneEx2(sec_mgr2, pUri, pdwZone, dwFlags, ppwszMappedUrl, pdwOutFlags);
1103             IInternetSecurityManagerEx2_Release(sec_mgr2);
1104         } else {
1105             BSTR url;
1106
1107             hres = IUri_GetDisplayUri(pUri, &url);
1108             if(FAILED(hres))
1109                 return hres;
1110
1111             hres = IInternetSecurityManager_MapUrlToZone(This->custom_manager, url, pdwZone, dwFlags);
1112             SysFreeString(url);
1113         }
1114
1115         if(hres != INET_E_DEFAULT_ACTION)
1116             return hres;
1117     }
1118
1119     if(!pdwZone)
1120         return E_INVALIDARG;
1121
1122     if(!pUri) {
1123         *pdwZone = URLZONE_INVALID;
1124         return E_INVALIDARG;
1125     }
1126
1127     if(dwFlags)
1128         FIXME("Unsupported flags: %08x\n", dwFlags);
1129
1130     return map_uri_to_zone(pUri, pdwZone);
1131 }
1132
1133 static HRESULT WINAPI SecManagerImpl_ProcessUrlActionEx2(IInternetSecurityManagerEx2 *iface,
1134         IUri *pUri, DWORD dwAction, BYTE *pPolicy, DWORD cbPolicy, BYTE *pContext, DWORD cbContext,
1135         DWORD dwFlags, DWORD_PTR dwReserved, DWORD *pdwOutFlags)
1136 {
1137     SecManagerImpl *This = impl_from_IInternetSecurityManagerEx2(iface);
1138     FIXME("(%p)->(%p %08x %p %d %p %d %08x %08x %p) stub\n", This, pUri, dwAction, pPolicy,
1139           cbPolicy, pContext, cbContext, dwFlags, (DWORD)dwReserved, pdwOutFlags);
1140     return E_NOTIMPL;
1141 }
1142
1143 static HRESULT WINAPI SecManagerImpl_GetSecurityIdEx2(IInternetSecurityManagerEx2 *iface,
1144         IUri *pUri, BYTE *pbSecurityId, DWORD *pcbSecurityId, DWORD_PTR dwReserved)
1145 {
1146     SecManagerImpl *This = impl_from_IInternetSecurityManagerEx2(iface);
1147     FIXME("(%p)->(%p %p %p %08x) stub\n", This, pUri, pbSecurityId, pcbSecurityId, (DWORD)dwReserved);
1148     return E_NOTIMPL;
1149 }
1150
1151 static HRESULT WINAPI SecManagerImpl_QueryCustomPolicyEx2(IInternetSecurityManagerEx2 *iface,
1152         IUri *pUri, REFGUID guidKey, BYTE **ppPolicy, DWORD *pcbPolicy, BYTE *pContext,
1153         DWORD cbContext, DWORD_PTR dwReserved)
1154 {
1155     SecManagerImpl *This = impl_from_IInternetSecurityManagerEx2(iface);
1156     FIXME("(%p)->(%p %s %p %p %p %d %08x) stub\n", This, pUri, debugstr_guid(guidKey), ppPolicy, pcbPolicy,
1157           pContext, cbContext, (DWORD)dwReserved);
1158     return E_NOTIMPL;
1159 }
1160
1161 static const IInternetSecurityManagerEx2Vtbl VT_SecManagerImpl =
1162 {
1163     SecManagerImpl_QueryInterface,
1164     SecManagerImpl_AddRef,
1165     SecManagerImpl_Release,
1166     SecManagerImpl_SetSecuritySite,
1167     SecManagerImpl_GetSecuritySite,
1168     SecManagerImpl_MapUrlToZone,
1169     SecManagerImpl_GetSecurityId,
1170     SecManagerImpl_ProcessUrlAction,
1171     SecManagerImpl_QueryCustomPolicy,
1172     SecManagerImpl_SetZoneMapping,
1173     SecManagerImpl_GetZoneMappings,
1174     SecManagerImpl_ProcessUrlActionEx,
1175     SecManagerImpl_MapUrlToZoneEx2,
1176     SecManagerImpl_ProcessUrlActionEx2,
1177     SecManagerImpl_GetSecurityIdEx2,
1178     SecManagerImpl_QueryCustomPolicyEx2
1179 };
1180
1181 HRESULT SecManagerImpl_Construct(IUnknown *pUnkOuter, LPVOID *ppobj)
1182 {
1183     SecManagerImpl *This;
1184
1185     TRACE("(%p,%p)\n",pUnkOuter,ppobj);
1186     This = heap_alloc(sizeof(*This));
1187
1188     /* Initialize the virtual function table. */
1189     This->IInternetSecurityManagerEx2_iface.lpVtbl = &VT_SecManagerImpl;
1190
1191     This->ref = 1;
1192     This->mgrsite = NULL;
1193     This->custom_manager = NULL;
1194
1195     *ppobj = This;
1196
1197     URLMON_LockModule();
1198
1199     return S_OK;
1200 }
1201
1202 /***********************************************************************
1203  *           InternetZoneManager implementation
1204  *
1205  */
1206 typedef struct {
1207     IInternetZoneManagerEx2 IInternetZoneManagerEx2_iface;
1208     LONG ref;
1209     LPDWORD *zonemaps;
1210     DWORD zonemap_count;
1211 } ZoneMgrImpl;
1212
1213 static inline ZoneMgrImpl *impl_from_IInternetZoneManagerEx2(IInternetZoneManagerEx2 *iface)
1214 {
1215     return CONTAINING_RECORD(iface, ZoneMgrImpl, IInternetZoneManagerEx2_iface);
1216 }
1217
1218
1219 /***********************************************************************
1220  * build_zonemap_from_reg [internal]
1221  *
1222  * Enumerate the Zones in the Registry and return the Zones in a DWORD-array
1223  * The number of the Zones is returned in data[0]
1224  */
1225 static LPDWORD build_zonemap_from_reg(void)
1226 {
1227     WCHAR name[32];
1228     HKEY hkey;
1229     LPDWORD data = NULL;
1230     DWORD allocated = 6; /* space for the zonecount and Zone "0" up to Zone "4" */
1231     DWORD used = 0;
1232     DWORD res;
1233     DWORD len;
1234
1235
1236     res = RegOpenKeyW(HKEY_CURRENT_USER, wszZonesKey, &hkey);
1237     if (res)
1238         return NULL;
1239
1240     data = heap_alloc(allocated * sizeof(DWORD));
1241     if (!data)
1242         goto cleanup;
1243
1244     while (!res) {
1245         name[0] = '\0';
1246         len = sizeof(name) / sizeof(name[0]);
1247         res = RegEnumKeyExW(hkey, used, name, &len, NULL, NULL, NULL, NULL);
1248
1249         if (!res) {
1250             used++;
1251             if (used == allocated) {
1252                 LPDWORD new_data;
1253
1254                 allocated *= 2;
1255                 new_data = heap_realloc_zero(data, allocated * sizeof(DWORD));
1256                 if (!new_data)
1257                     goto cleanup;
1258
1259                 data = new_data;
1260             }
1261             data[used] = atoiW(name);
1262         }
1263     }
1264     if (used) {
1265         RegCloseKey(hkey);
1266         data[0] = used;
1267         return data;
1268     }
1269
1270 cleanup:
1271     /* something failed */
1272     RegCloseKey(hkey);
1273     heap_free(data);
1274     return NULL;
1275 }
1276
1277 /********************************************************************
1278  *      IInternetZoneManager_QueryInterface
1279  */
1280 static HRESULT WINAPI ZoneMgrImpl_QueryInterface(IInternetZoneManagerEx2* iface, REFIID riid, void** ppvObject)
1281 {
1282     ZoneMgrImpl* This = impl_from_IInternetZoneManagerEx2(iface);
1283
1284     TRACE("(%p)->(%s,%p)\n", This, debugstr_guid(riid), ppvObject);
1285
1286     if(!This || !ppvObject)
1287         return E_INVALIDARG;
1288
1289     if(IsEqualIID(&IID_IUnknown, riid)) {
1290         TRACE("(%p)->(IID_IUnknown %p)\n", This, ppvObject);
1291     }else if(IsEqualIID(&IID_IInternetZoneManager, riid)) {
1292         TRACE("(%p)->(IID_InternetZoneManager %p)\n", This, ppvObject);
1293     }else if(IsEqualIID(&IID_IInternetZoneManagerEx, riid)) {
1294         TRACE("(%p)->(IID_InternetZoneManagerEx %p)\n", This, ppvObject);
1295     }else if(IsEqualIID(&IID_IInternetZoneManagerEx2, riid)) {
1296         TRACE("(%p)->(IID_InternetZoneManagerEx2 %p)\n", This, ppvObject);
1297     }
1298     else
1299     {
1300         FIXME("Unknown interface: %s\n", debugstr_guid(riid));
1301         *ppvObject = NULL;
1302         return E_NOINTERFACE;
1303     }
1304
1305     *ppvObject = iface;
1306     IInternetZoneManager_AddRef(iface);
1307     return S_OK;
1308 }
1309
1310 /********************************************************************
1311  *      IInternetZoneManager_AddRef
1312  */
1313 static ULONG WINAPI ZoneMgrImpl_AddRef(IInternetZoneManagerEx2* iface)
1314 {
1315     ZoneMgrImpl* This = impl_from_IInternetZoneManagerEx2(iface);
1316     ULONG refCount = InterlockedIncrement(&This->ref);
1317
1318     TRACE("(%p)->(ref before=%u)\n",This, refCount - 1);
1319
1320     return refCount;
1321 }
1322
1323 /********************************************************************
1324  *      IInternetZoneManager_Release
1325  */
1326 static ULONG WINAPI ZoneMgrImpl_Release(IInternetZoneManagerEx2* iface)
1327 {
1328     ZoneMgrImpl* This = impl_from_IInternetZoneManagerEx2(iface);
1329     ULONG refCount = InterlockedDecrement(&This->ref);
1330
1331     TRACE("(%p)->(ref before=%u)\n",This, refCount + 1);
1332
1333     if(!refCount) {
1334         while (This->zonemap_count) heap_free(This->zonemaps[--This->zonemap_count]);
1335         heap_free(This->zonemaps);
1336         heap_free(This);
1337         URLMON_UnlockModule();
1338     }
1339     
1340     return refCount;
1341 }
1342
1343 /********************************************************************
1344  *      IInternetZoneManager_GetZoneAttributes
1345  */
1346 static HRESULT WINAPI ZoneMgrImpl_GetZoneAttributes(IInternetZoneManagerEx2* iface,
1347                                                     DWORD dwZone,
1348                                                     ZONEATTRIBUTES* pZoneAttributes)
1349 {
1350     ZoneMgrImpl* This = impl_from_IInternetZoneManagerEx2(iface);
1351     HRESULT hr;
1352     HKEY hcu;
1353     HKEY hklm = NULL;
1354
1355     TRACE("(%p)->(%d %p)\n", This, dwZone, pZoneAttributes);
1356
1357     if (!pZoneAttributes)
1358         return E_INVALIDARG;
1359
1360     hr = open_zone_key(HKEY_CURRENT_USER, dwZone, &hcu);
1361     if (FAILED(hr))
1362         return S_OK;  /* IE6 and older returned E_FAIL here */
1363
1364     hr = open_zone_key(HKEY_LOCAL_MACHINE, dwZone, &hklm);
1365     if (FAILED(hr))
1366         TRACE("Zone %d not in HKLM\n", dwZone);
1367
1368     get_string_from_reg(hcu, hklm, displaynameW, pZoneAttributes->szDisplayName, MAX_ZONE_PATH);
1369     get_string_from_reg(hcu, hklm, descriptionW, pZoneAttributes->szDescription, MAX_ZONE_DESCRIPTION);
1370     get_string_from_reg(hcu, hklm, iconW, pZoneAttributes->szIconPath, MAX_ZONE_PATH);
1371     get_dword_from_reg(hcu, hklm, minlevelW, &pZoneAttributes->dwTemplateMinLevel);
1372     get_dword_from_reg(hcu, hklm, currentlevelW, &pZoneAttributes->dwTemplateCurrentLevel);
1373     get_dword_from_reg(hcu, hklm, recommendedlevelW, &pZoneAttributes->dwTemplateRecommended);
1374     get_dword_from_reg(hcu, hklm, flagsW, &pZoneAttributes->dwFlags);
1375
1376     RegCloseKey(hklm);
1377     RegCloseKey(hcu);
1378     return S_OK;
1379 }
1380
1381 /********************************************************************
1382  *      IInternetZoneManager_SetZoneAttributes
1383  */
1384 static HRESULT WINAPI ZoneMgrImpl_SetZoneAttributes(IInternetZoneManagerEx2* iface,
1385                                                     DWORD dwZone,
1386                                                     ZONEATTRIBUTES* pZoneAttributes)
1387 {
1388     ZoneMgrImpl* This = impl_from_IInternetZoneManagerEx2(iface);
1389     HRESULT hr;
1390     HKEY hcu;
1391
1392     TRACE("(%p)->(%d %p)\n", This, dwZone, pZoneAttributes);
1393
1394     if (!pZoneAttributes)
1395         return E_INVALIDARG;
1396
1397     hr = open_zone_key(HKEY_CURRENT_USER, dwZone, &hcu);
1398     if (FAILED(hr))
1399         return S_OK;  /* IE6 returned E_FAIL here */
1400
1401     /* cbSize is ignored */
1402     RegSetValueExW(hcu, displaynameW, 0, REG_SZ, (LPBYTE) pZoneAttributes->szDisplayName,
1403                     (lstrlenW(pZoneAttributes->szDisplayName)+1)* sizeof(WCHAR));
1404
1405     RegSetValueExW(hcu, descriptionW, 0, REG_SZ, (LPBYTE) pZoneAttributes->szDescription,
1406                     (lstrlenW(pZoneAttributes->szDescription)+1)* sizeof(WCHAR));
1407
1408     RegSetValueExW(hcu, iconW, 0, REG_SZ, (LPBYTE) pZoneAttributes->szIconPath,
1409                     (lstrlenW(pZoneAttributes->szIconPath)+1)* sizeof(WCHAR));
1410
1411     RegSetValueExW(hcu, minlevelW, 0, REG_DWORD,
1412                     (const BYTE*) &pZoneAttributes->dwTemplateMinLevel, sizeof(DWORD));
1413
1414     RegSetValueExW(hcu, currentlevelW, 0, REG_DWORD,
1415                     (const BYTE*) &pZoneAttributes->dwTemplateCurrentLevel, sizeof(DWORD));
1416
1417     RegSetValueExW(hcu, recommendedlevelW, 0, REG_DWORD,
1418                     (const BYTE*) &pZoneAttributes->dwTemplateRecommended, sizeof(DWORD));
1419
1420     RegSetValueExW(hcu, flagsW, 0, REG_DWORD, (const BYTE*) &pZoneAttributes->dwFlags, sizeof(DWORD));
1421     RegCloseKey(hcu);
1422     return S_OK;
1423
1424 }
1425
1426 /********************************************************************
1427  *      IInternetZoneManager_GetZoneCustomPolicy
1428  */
1429 static HRESULT WINAPI ZoneMgrImpl_GetZoneCustomPolicy(IInternetZoneManagerEx2* iface,
1430                                                       DWORD dwZone,
1431                                                       REFGUID guidKey,
1432                                                       BYTE** ppPolicy,
1433                                                       DWORD* pcbPolicy,
1434                                                       URLZONEREG ulrZoneReg)
1435 {
1436     FIXME("(%p)->(%08x %s %p %p %08x) stub\n", iface, dwZone, debugstr_guid(guidKey),
1437                                                     ppPolicy, pcbPolicy, ulrZoneReg);
1438     return E_NOTIMPL;
1439 }
1440
1441 /********************************************************************
1442  *      IInternetZoneManager_SetZoneCustomPolicy
1443  */
1444 static HRESULT WINAPI ZoneMgrImpl_SetZoneCustomPolicy(IInternetZoneManagerEx2* iface,
1445                                                       DWORD dwZone,
1446                                                       REFGUID guidKey,
1447                                                       BYTE* ppPolicy,
1448                                                       DWORD cbPolicy,
1449                                                       URLZONEREG ulrZoneReg)
1450 {
1451     FIXME("(%p)->(%08x %s %p %08x %08x) stub\n", iface, dwZone, debugstr_guid(guidKey),
1452                                                     ppPolicy, cbPolicy, ulrZoneReg);
1453     return E_NOTIMPL;
1454 }
1455
1456 /********************************************************************
1457  *      IInternetZoneManager_GetZoneActionPolicy
1458  */
1459 static HRESULT WINAPI ZoneMgrImpl_GetZoneActionPolicy(IInternetZoneManagerEx2* iface,
1460         DWORD dwZone, DWORD dwAction, BYTE* pPolicy, DWORD cbPolicy, URLZONEREG urlZoneReg)
1461 {
1462     TRACE("(%p)->(%d %08x %p %d %d)\n", iface, dwZone, dwAction, pPolicy,
1463             cbPolicy, urlZoneReg);
1464
1465     if(!pPolicy)
1466         return E_INVALIDARG;
1467
1468     return get_action_policy(dwZone, dwAction, pPolicy, cbPolicy, urlZoneReg);
1469 }
1470
1471 /********************************************************************
1472  *      IInternetZoneManager_SetZoneActionPolicy
1473  */
1474 static HRESULT WINAPI ZoneMgrImpl_SetZoneActionPolicy(IInternetZoneManagerEx2* iface,
1475                                                       DWORD dwZone,
1476                                                       DWORD dwAction,
1477                                                       BYTE* pPolicy,
1478                                                       DWORD cbPolicy,
1479                                                       URLZONEREG urlZoneReg)
1480 {
1481     FIXME("(%p)->(%08x %08x %p %08x %08x) stub\n", iface, dwZone, dwAction, pPolicy,
1482                                                        cbPolicy, urlZoneReg);
1483     return E_NOTIMPL;
1484 }
1485
1486 /********************************************************************
1487  *      IInternetZoneManager_PromptAction
1488  */
1489 static HRESULT WINAPI ZoneMgrImpl_PromptAction(IInternetZoneManagerEx2* iface,
1490                                                DWORD dwAction,
1491                                                HWND hwndParent,
1492                                                LPCWSTR pwszUrl,
1493                                                LPCWSTR pwszText,
1494                                                DWORD dwPromptFlags)
1495 {
1496     FIXME("%p %08x %p %s %s %08x\n", iface, dwAction, hwndParent,
1497           debugstr_w(pwszUrl), debugstr_w(pwszText), dwPromptFlags );
1498     return E_NOTIMPL;
1499 }
1500
1501 /********************************************************************
1502  *      IInternetZoneManager_LogAction
1503  */
1504 static HRESULT WINAPI ZoneMgrImpl_LogAction(IInternetZoneManagerEx2* iface,
1505                                             DWORD dwAction,
1506                                             LPCWSTR pwszUrl,
1507                                             LPCWSTR pwszText,
1508                                             DWORD dwLogFlags)
1509 {
1510     FIXME("(%p)->(%08x %s %s %08x) stub\n", iface, dwAction, debugstr_w(pwszUrl),
1511                                               debugstr_w(pwszText), dwLogFlags);
1512     return E_NOTIMPL;
1513 }
1514
1515 /********************************************************************
1516  *      IInternetZoneManager_CreateZoneEnumerator
1517  */
1518 static HRESULT WINAPI ZoneMgrImpl_CreateZoneEnumerator(IInternetZoneManagerEx2* iface,
1519                                                        DWORD* pdwEnum,
1520                                                        DWORD* pdwCount,
1521                                                        DWORD dwFlags)
1522 {
1523     ZoneMgrImpl* This = impl_from_IInternetZoneManagerEx2(iface);
1524     LPDWORD * new_maps;
1525     LPDWORD data;
1526     DWORD i;
1527
1528     TRACE("(%p)->(%p, %p, 0x%08x)\n", This, pdwEnum, pdwCount, dwFlags);
1529     if (!pdwEnum || !pdwCount || (dwFlags != 0))
1530         return E_INVALIDARG;
1531
1532     data = build_zonemap_from_reg();
1533     TRACE("found %d zones\n", data ? data[0] : -1);
1534
1535     if (!data)
1536         return E_FAIL;
1537
1538     for (i = 0; i < This->zonemap_count; i++) {
1539         if (This->zonemaps && !This->zonemaps[i]) {
1540             This->zonemaps[i] = data;
1541             *pdwEnum = i;
1542             *pdwCount = data[0];
1543             return S_OK;
1544         }
1545     }
1546
1547     if (This->zonemaps) {
1548         /* try to double the nr. of pointers in the array */
1549         new_maps = heap_realloc_zero(This->zonemaps, This->zonemap_count * 2 * sizeof(LPDWORD));
1550         if (new_maps)
1551             This->zonemap_count *= 2;
1552     }
1553     else
1554     {
1555         This->zonemap_count = 2;
1556         new_maps = heap_alloc_zero(This->zonemap_count * sizeof(LPDWORD));
1557     }
1558
1559     if (!new_maps) {
1560         heap_free(data);
1561         return E_FAIL;
1562     }
1563     This->zonemaps = new_maps;
1564     This->zonemaps[i] = data;
1565     *pdwEnum = i;
1566     *pdwCount = data[0];
1567     return S_OK;
1568 }
1569
1570 /********************************************************************
1571  *      IInternetZoneManager_GetZoneAt
1572  */
1573 static HRESULT WINAPI ZoneMgrImpl_GetZoneAt(IInternetZoneManagerEx2* iface,
1574                                             DWORD dwEnum,
1575                                             DWORD dwIndex,
1576                                             DWORD* pdwZone)
1577 {
1578     ZoneMgrImpl* This = impl_from_IInternetZoneManagerEx2(iface);
1579     LPDWORD data;
1580
1581     TRACE("(%p)->(0x%08x, %d, %p)\n", This, dwEnum, dwIndex, pdwZone);
1582
1583     /* make sure, that dwEnum and dwIndex are in the valid range */
1584     if (dwEnum < This->zonemap_count) {
1585         if ((data = This->zonemaps[dwEnum])) {
1586             if (dwIndex < data[0]) {
1587                 *pdwZone = data[dwIndex + 1];
1588                 return S_OK;
1589             }
1590         }
1591     }
1592     return E_INVALIDARG;
1593 }
1594
1595 /********************************************************************
1596  *      IInternetZoneManager_DestroyZoneEnumerator
1597  */
1598 static HRESULT WINAPI ZoneMgrImpl_DestroyZoneEnumerator(IInternetZoneManagerEx2* iface,
1599                                                         DWORD dwEnum)
1600 {
1601     ZoneMgrImpl* This = impl_from_IInternetZoneManagerEx2(iface);
1602     LPDWORD data;
1603
1604     TRACE("(%p)->(0x%08x)\n", This, dwEnum);
1605     /* make sure, that dwEnum is valid */
1606     if (dwEnum < This->zonemap_count) {
1607         if ((data = This->zonemaps[dwEnum])) {
1608             This->zonemaps[dwEnum] = NULL;
1609             heap_free(data);
1610             return S_OK;
1611         }
1612     }
1613     return E_INVALIDARG;
1614 }
1615
1616 /********************************************************************
1617  *      IInternetZoneManager_CopyTemplatePoliciesToZone
1618  */
1619 static HRESULT WINAPI ZoneMgrImpl_CopyTemplatePoliciesToZone(IInternetZoneManagerEx2* iface,
1620                                                              DWORD dwTemplate,
1621                                                              DWORD dwZone,
1622                                                              DWORD dwReserved)
1623 {
1624     FIXME("(%p)->(%08x %08x %08x) stub\n", iface, dwTemplate, dwZone, dwReserved);
1625     return E_NOTIMPL;
1626 }
1627
1628 /********************************************************************
1629  *      IInternetZoneManagerEx_GetZoneActionPolicyEx
1630  */
1631 static HRESULT WINAPI ZoneMgrImpl_GetZoneActionPolicyEx(IInternetZoneManagerEx2* iface,
1632                                                         DWORD dwZone,
1633                                                         DWORD dwAction,
1634                                                         BYTE* pPolicy,
1635                                                         DWORD cbPolicy,
1636                                                         URLZONEREG urlZoneReg,
1637                                                         DWORD dwFlags)
1638 {
1639     TRACE("(%p)->(%d, 0x%x, %p, %d, %d, 0x%x)\n", iface, dwZone,
1640             dwAction, pPolicy, cbPolicy, urlZoneReg, dwFlags);
1641
1642     if(!pPolicy)
1643         return E_INVALIDARG;
1644
1645     if (dwFlags)
1646         FIXME("dwFlags 0x%x ignored\n", dwFlags);
1647
1648     return get_action_policy(dwZone, dwAction, pPolicy, cbPolicy, urlZoneReg);
1649 }
1650
1651 /********************************************************************
1652  *      IInternetZoneManagerEx_SetZoneActionPolicyEx
1653  */
1654 static HRESULT WINAPI ZoneMgrImpl_SetZoneActionPolicyEx(IInternetZoneManagerEx2* iface,
1655                                                         DWORD dwZone,
1656                                                         DWORD dwAction,
1657                                                         BYTE* pPolicy,
1658                                                         DWORD cbPolicy,
1659                                                         URLZONEREG urlZoneReg,
1660                                                         DWORD dwFlags)
1661 {
1662     FIXME("(%p)->(%d, 0x%x, %p, %d, %d, 0x%x) stub\n", iface, dwZone, dwAction, pPolicy,
1663                                                        cbPolicy, urlZoneReg, dwFlags);
1664     return E_NOTIMPL;
1665 }
1666
1667 /********************************************************************
1668  *      IInternetZoneManagerEx2_GetZoneAttributesEx
1669  */
1670 static HRESULT WINAPI ZoneMgrImpl_GetZoneAttributesEx(IInternetZoneManagerEx2* iface,
1671                                                       DWORD dwZone,
1672                                                       ZONEATTRIBUTES* pZoneAttributes,
1673                                                       DWORD dwFlags)
1674 {
1675     TRACE("(%p)->(%d, %p, 0x%x)\n", iface, dwZone, pZoneAttributes, dwFlags);
1676
1677     if (dwFlags)
1678         FIXME("dwFlags 0x%x ignored\n", dwFlags);
1679
1680     return IInternetZoneManager_GetZoneAttributes(iface, dwZone, pZoneAttributes);
1681 }
1682
1683
1684 /********************************************************************
1685  *      IInternetZoneManagerEx2_GetZoneSecurityState
1686  */
1687 static HRESULT WINAPI ZoneMgrImpl_GetZoneSecurityState(IInternetZoneManagerEx2* iface,
1688                                                        DWORD dwZoneIndex,
1689                                                        BOOL fRespectPolicy,
1690                                                        LPDWORD pdwState,
1691                                                        BOOL *pfPolicyEncountered)
1692 {
1693     FIXME("(%p)->(%d, %d, %p, %p) stub\n", iface, dwZoneIndex, fRespectPolicy,
1694                                            pdwState, pfPolicyEncountered);
1695
1696     *pdwState = SECURITY_IE_STATE_GREEN;
1697
1698     if (pfPolicyEncountered)
1699         *pfPolicyEncountered = FALSE;
1700
1701     return S_OK;
1702 }
1703
1704 /********************************************************************
1705  *      IInternetZoneManagerEx2_GetIESecurityState
1706  */
1707 static HRESULT WINAPI ZoneMgrImpl_GetIESecurityState(IInternetZoneManagerEx2* iface,
1708                                                      BOOL fRespectPolicy,
1709                                                      LPDWORD pdwState,
1710                                                      BOOL *pfPolicyEncountered,
1711                                                      BOOL fNoCache)
1712 {
1713     FIXME("(%p)->(%d, %p, %p, %d) stub\n", iface, fRespectPolicy, pdwState,
1714                                            pfPolicyEncountered, fNoCache);
1715
1716     *pdwState = SECURITY_IE_STATE_GREEN;
1717
1718     if (pfPolicyEncountered)
1719         *pfPolicyEncountered = FALSE;
1720
1721     return S_OK;
1722 }
1723
1724 /********************************************************************
1725  *      IInternetZoneManagerEx2_FixInsecureSettings
1726  */
1727 static HRESULT WINAPI ZoneMgrImpl_FixInsecureSettings(IInternetZoneManagerEx2* iface)
1728 {
1729     FIXME("(%p) stub\n", iface);
1730     return S_OK;
1731 }
1732
1733 /********************************************************************
1734  *      IInternetZoneManager_Construct
1735  */
1736 static const IInternetZoneManagerEx2Vtbl ZoneMgrImplVtbl = {
1737     ZoneMgrImpl_QueryInterface,
1738     ZoneMgrImpl_AddRef,
1739     ZoneMgrImpl_Release,
1740     /* IInternetZoneManager */
1741     ZoneMgrImpl_GetZoneAttributes,
1742     ZoneMgrImpl_SetZoneAttributes,
1743     ZoneMgrImpl_GetZoneCustomPolicy,
1744     ZoneMgrImpl_SetZoneCustomPolicy,
1745     ZoneMgrImpl_GetZoneActionPolicy,
1746     ZoneMgrImpl_SetZoneActionPolicy,
1747     ZoneMgrImpl_PromptAction,
1748     ZoneMgrImpl_LogAction,
1749     ZoneMgrImpl_CreateZoneEnumerator,
1750     ZoneMgrImpl_GetZoneAt,
1751     ZoneMgrImpl_DestroyZoneEnumerator,
1752     ZoneMgrImpl_CopyTemplatePoliciesToZone,
1753     /* IInternetZoneManagerEx */
1754     ZoneMgrImpl_GetZoneActionPolicyEx,
1755     ZoneMgrImpl_SetZoneActionPolicyEx,
1756     /* IInternetZoneManagerEx2 */
1757     ZoneMgrImpl_GetZoneAttributesEx,
1758     ZoneMgrImpl_GetZoneSecurityState,
1759     ZoneMgrImpl_GetIESecurityState,
1760     ZoneMgrImpl_FixInsecureSettings,
1761 };
1762
1763 HRESULT ZoneMgrImpl_Construct(IUnknown *pUnkOuter, LPVOID *ppobj)
1764 {
1765     ZoneMgrImpl* ret = heap_alloc_zero(sizeof(ZoneMgrImpl));
1766
1767     TRACE("(%p %p)\n", pUnkOuter, ppobj);
1768     ret->IInternetZoneManagerEx2_iface.lpVtbl = &ZoneMgrImplVtbl;
1769     ret->ref = 1;
1770     *ppobj = (IInternetZoneManagerEx*)ret;
1771
1772     URLMON_LockModule();
1773
1774     return S_OK;
1775 }
1776
1777 /***********************************************************************
1778  *           CoInternetCreateSecurityManager (URLMON.@)
1779  *
1780  */
1781 HRESULT WINAPI CoInternetCreateSecurityManager( IServiceProvider *pSP,
1782     IInternetSecurityManager **ppSM, DWORD dwReserved )
1783 {
1784     TRACE("%p %p %d\n", pSP, ppSM, dwReserved );
1785
1786     if(pSP)
1787         FIXME("pSP not supported\n");
1788
1789     return SecManagerImpl_Construct(NULL, (void**) ppSM);
1790 }
1791
1792 /********************************************************************
1793  *      CoInternetCreateZoneManager (URLMON.@)
1794  */
1795 HRESULT WINAPI CoInternetCreateZoneManager(IServiceProvider* pSP, IInternetZoneManager** ppZM, DWORD dwReserved)
1796 {
1797     TRACE("(%p %p %x)\n", pSP, ppZM, dwReserved);
1798     return ZoneMgrImpl_Construct(NULL, (void**)ppZM);
1799 }
1800
1801 static HRESULT parse_security_url(const WCHAR *url, PSUACTION action, WCHAR **result) {
1802     IInternetProtocolInfo *protocol_info;
1803     WCHAR *tmp, *new_url = NULL, *alloc_url = NULL;
1804     DWORD size, new_size;
1805     HRESULT hres = S_OK, parse_hres;
1806
1807     while(1) {
1808         TRACE("parsing %s\n", debugstr_w(url));
1809
1810         protocol_info = get_protocol_info(url);
1811         if(!protocol_info)
1812             break;
1813
1814         size = strlenW(url)+1;
1815         new_url = CoTaskMemAlloc(size*sizeof(WCHAR));
1816         if(!new_url) {
1817             hres = E_OUTOFMEMORY;
1818             break;
1819         }
1820
1821         new_size = 0;
1822         parse_hres = IInternetProtocolInfo_ParseUrl(protocol_info, url, PARSE_SECURITY_URL, 0, new_url, size, &new_size, 0);
1823         if(parse_hres == S_FALSE) {
1824             if(!new_size) {
1825                 hres = E_UNEXPECTED;
1826                 break;
1827             }
1828
1829             tmp = CoTaskMemRealloc(new_url, new_size*sizeof(WCHAR));
1830             if(!tmp) {
1831                 hres = E_OUTOFMEMORY;
1832                 break;
1833             }
1834             new_url = tmp;
1835             parse_hres = IInternetProtocolInfo_ParseUrl(protocol_info, url, PARSE_SECURITY_URL, 0, new_url,
1836                     new_size, &new_size, 0);
1837             if(parse_hres == S_FALSE) {
1838                 hres = E_FAIL;
1839                 break;
1840             }
1841         }
1842
1843         if(parse_hres != S_OK || !strcmpW(url, new_url))
1844             break;
1845
1846         CoTaskMemFree(alloc_url);
1847         url = alloc_url = new_url;
1848         new_url = NULL;
1849     }
1850
1851     CoTaskMemFree(new_url);
1852
1853     if(hres != S_OK) {
1854         WARN("failed: %08x\n", hres);
1855         CoTaskMemFree(alloc_url);
1856         return hres;
1857     }
1858
1859     if(action == PSU_DEFAULT && (protocol_info = get_protocol_info(url))) {
1860         size = strlenW(url)+1;
1861         new_url = CoTaskMemAlloc(size * sizeof(WCHAR));
1862         if(new_url) {
1863             new_size = 0;
1864             parse_hres = IInternetProtocolInfo_ParseUrl(protocol_info, url, PARSE_SECURITY_DOMAIN, 0,
1865                     new_url, size, &new_size, 0);
1866             if(parse_hres == S_FALSE) {
1867                 if(new_size) {
1868                     tmp = CoTaskMemRealloc(new_url, new_size*sizeof(WCHAR));
1869                     if(tmp) {
1870                         new_url = tmp;
1871                         parse_hres = IInternetProtocolInfo_ParseUrl(protocol_info, url, PARSE_SECURITY_DOMAIN, 0, new_url,
1872                                 new_size, &new_size, 0);
1873                         if(parse_hres == S_FALSE)
1874                             hres = E_FAIL;
1875                     }else {
1876                         hres = E_OUTOFMEMORY;
1877                     }
1878                 }else {
1879                     hres = E_UNEXPECTED;
1880                 }
1881             }
1882
1883             if(hres == S_OK && parse_hres == S_OK) {
1884                 CoTaskMemFree(alloc_url);
1885                 url = alloc_url = new_url;
1886                 new_url = NULL;
1887             }
1888
1889             CoTaskMemFree(new_url);
1890         }else {
1891             hres = E_OUTOFMEMORY;
1892         }
1893         IInternetProtocolInfo_Release(protocol_info);
1894     }
1895
1896     if(FAILED(hres)) {
1897         WARN("failed %08x\n", hres);
1898         CoTaskMemFree(alloc_url);
1899         return hres;
1900     }
1901
1902     if(!alloc_url) {
1903         size = strlenW(url)+1;
1904         alloc_url = CoTaskMemAlloc(size * sizeof(WCHAR));
1905         if(!alloc_url)
1906             return E_OUTOFMEMORY;
1907         memcpy(alloc_url, url, size * sizeof(WCHAR));
1908     }
1909
1910     *result = alloc_url;
1911     return S_OK;
1912 }
1913
1914 /********************************************************************
1915  *      CoInternetGetSecurityUrl (URLMON.@)
1916  */
1917 HRESULT WINAPI CoInternetGetSecurityUrl(LPCWSTR pwzUrl, LPWSTR *ppwzSecUrl, PSUACTION psuAction, DWORD dwReserved)
1918 {
1919     WCHAR *secure_url;
1920     HRESULT hres;
1921
1922     TRACE("(%p,%p,%u,%u)\n", pwzUrl, ppwzSecUrl, psuAction, dwReserved);
1923
1924     hres = parse_security_url(pwzUrl, psuAction, &secure_url);
1925     if(FAILED(hres))
1926         return hres;
1927
1928     if(psuAction != PSU_SECURITY_URL_ONLY) {
1929         PARSEDURLW parsed_url = { sizeof(parsed_url) };
1930         DWORD size;
1931
1932         /* FIXME: Use helpers from uri.c */
1933         if(SUCCEEDED(ParseURLW(secure_url, &parsed_url))) {
1934             WCHAR *new_url;
1935
1936             switch(parsed_url.nScheme) {
1937             case URL_SCHEME_FTP:
1938             case URL_SCHEME_HTTP:
1939             case URL_SCHEME_HTTPS:
1940                 size = strlenW(secure_url)+1;
1941                 new_url = CoTaskMemAlloc(size * sizeof(WCHAR));
1942                 if(new_url)
1943                     hres = UrlGetPartW(secure_url, new_url, &size, URL_PART_HOSTNAME, URL_PARTFLAG_KEEPSCHEME);
1944                 else
1945                     hres = E_OUTOFMEMORY;
1946                 CoTaskMemFree(secure_url);
1947                 if(hres != S_OK) {
1948                     WARN("UrlGetPart failed: %08x\n", hres);
1949                     CoTaskMemFree(new_url);
1950                     return FAILED(hres) ? hres : E_FAIL;
1951                 }
1952                 secure_url = new_url;
1953             }
1954         }
1955     }
1956
1957     *ppwzSecUrl = secure_url;
1958     return S_OK;
1959 }
1960
1961 /********************************************************************
1962  *      CoInternetGetSecurityUrlEx (URLMON.@)
1963  */
1964 HRESULT WINAPI CoInternetGetSecurityUrlEx(IUri *pUri, IUri **ppSecUri, PSUACTION psuAction, DWORD_PTR dwReserved)
1965 {
1966     URL_SCHEME scheme_type;
1967     BSTR secure_uri;
1968     WCHAR *ret_url;
1969     HRESULT hres;
1970
1971     TRACE("(%p,%p,%u,%u)\n", pUri, ppSecUri, psuAction, (DWORD)dwReserved);
1972
1973     if(!pUri || !ppSecUri)
1974         return E_INVALIDARG;
1975
1976     hres = IUri_GetDisplayUri(pUri, &secure_uri);
1977     if(FAILED(hres))
1978         return hres;
1979
1980     hres = parse_security_url(secure_uri, psuAction, &ret_url);
1981     SysFreeString(secure_uri);
1982     if(FAILED(hres))
1983         return hres;
1984
1985     /* File URIs have to hierarchical. */
1986     hres = IUri_GetScheme(pUri, (DWORD*)&scheme_type);
1987     if(SUCCEEDED(hres) && scheme_type == URL_SCHEME_FILE) {
1988         const WCHAR *tmp = ret_url;
1989
1990         /* Check and see if a "//" is after the scheme name. */
1991         tmp += sizeof(fileW)/sizeof(WCHAR);
1992         if(*tmp != '/' || *(tmp+1) != '/')
1993             hres = E_INVALIDARG;
1994     }
1995
1996     if(SUCCEEDED(hres))
1997         hres = CreateUri(ret_url, Uri_CREATE_ALLOW_IMPLICIT_WILDCARD_SCHEME, 0, ppSecUri);
1998     CoTaskMemFree(ret_url);
1999     return hres;
2000 }