cryptui: Ensure a certificate's private key is exportable before allowing it to be...
[wine] / dlls / cryptui / main.c
1 /*
2  * Copyright 2008 Juan Lang
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2.1 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with this library; if not, write to the Free Software
16  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
17  */
18
19 #include "config.h"
20
21 #include <stdarg.h>
22
23 #define COBJMACROS
24 #define NONAMELESSUNION
25
26 #include "windef.h"
27 #include "winbase.h"
28 #include "winnls.h"
29 #include "winuser.h"
30 #include "softpub.h"
31 #include "wingdi.h"
32 #include "richedit.h"
33 #include "ole2.h"
34 #include "richole.h"
35 #include "commdlg.h"
36 #include "commctrl.h"
37 #include "cryptuiapi.h"
38 #include "cryptuires.h"
39 #include "urlmon.h"
40 #include "hlink.h"
41 #include "winreg.h"
42 #include "wine/debug.h"
43 #include "wine/unicode.h"
44
45 WINE_DEFAULT_DEBUG_CHANNEL(cryptui);
46
47 static HINSTANCE hInstance;
48
49 BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
50 {
51     TRACE("(0x%p, %d, %p)\n", hinstDLL, fdwReason, lpvReserved);
52
53     switch (fdwReason)
54     {
55         case DLL_WINE_PREATTACH:
56             return FALSE;    /* prefer native version */
57         case DLL_PROCESS_ATTACH:
58             hInstance = hinstDLL;
59             DisableThreadLibraryCalls(hinstDLL);
60             break;
61         case DLL_PROCESS_DETACH:
62             break;
63         default:
64             break;
65     }
66     return TRUE;
67 }
68
69 #define MAX_STRING_LEN 512
70
71 static void add_cert_columns(HWND hwnd)
72 {
73     HWND lv = GetDlgItem(hwnd, IDC_MGR_CERTS);
74     RECT rc;
75     WCHAR buf[MAX_STRING_LEN];
76     LVCOLUMNW column;
77
78     SendMessageW(lv, LVM_SETEXTENDEDLISTVIEWSTYLE, 0, LVS_EX_FULLROWSELECT);
79     GetWindowRect(lv, &rc);
80     LoadStringW(hInstance, IDS_SUBJECT_COLUMN, buf,
81      sizeof(buf) / sizeof(buf[0]));
82     column.mask = LVCF_WIDTH | LVCF_TEXT;
83     column.cx = (rc.right - rc.left) * 29 / 100 - 2;
84     column.pszText = buf;
85     SendMessageW(lv, LVM_INSERTCOLUMNW, 0, (LPARAM)&column);
86     LoadStringW(hInstance, IDS_ISSUER_COLUMN, buf,
87      sizeof(buf) / sizeof(buf[0]));
88     SendMessageW(lv, LVM_INSERTCOLUMNW, 1, (LPARAM)&column);
89     column.cx = (rc.right - rc.left) * 16 / 100 - 2;
90     LoadStringW(hInstance, IDS_EXPIRATION_COLUMN, buf,
91      sizeof(buf) / sizeof(buf[0]));
92     SendMessageW(lv, LVM_INSERTCOLUMNW, 2, (LPARAM)&column);
93     column.cx = (rc.right - rc.left) * 23 / 100 - 1;
94     LoadStringW(hInstance, IDS_FRIENDLY_NAME_COLUMN, buf,
95      sizeof(buf) / sizeof(buf[0]));
96     SendMessageW(lv, LVM_INSERTCOLUMNW, 3, (LPARAM)&column);
97 }
98
99 static void add_cert_to_view(HWND lv, PCCERT_CONTEXT cert, DWORD *allocatedLen,
100  LPWSTR *str)
101 {
102     DWORD len;
103     LVITEMW item;
104     WCHAR dateFmt[80]; /* sufficient for LOCALE_SSHORTDATE */
105     WCHAR date[80];
106     SYSTEMTIME sysTime;
107
108     item.mask = LVIF_IMAGE | LVIF_PARAM | LVIF_TEXT;
109     item.iItem = SendMessageW(lv, LVM_GETITEMCOUNT, 0, 0);
110     item.iSubItem = 0;
111     item.iImage = 0;
112     item.lParam = (LPARAM)CertDuplicateCertificateContext(cert);
113     len = CertGetNameStringW(cert, CERT_NAME_SIMPLE_DISPLAY_TYPE, 0, NULL,
114      NULL, 0);
115     if (len > *allocatedLen)
116     {
117         HeapFree(GetProcessHeap(), 0, *str);
118         *str = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
119         if (*str)
120             *allocatedLen = len;
121     }
122     if (*str)
123     {
124         CertGetNameStringW(cert, CERT_NAME_SIMPLE_DISPLAY_TYPE, 0, NULL,
125          *str, len);
126         item.pszText = *str;
127         SendMessageW(lv, LVM_INSERTITEMW, 0, (LPARAM)&item);
128     }
129
130     item.mask = LVIF_TEXT;
131     len = CertGetNameStringW(cert, CERT_NAME_SIMPLE_DISPLAY_TYPE,
132      CERT_NAME_ISSUER_FLAG, NULL, NULL, 0);
133     if (len > *allocatedLen)
134     {
135         HeapFree(GetProcessHeap(), 0, *str);
136         *str = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
137         if (*str)
138             *allocatedLen = len;
139     }
140     if (*str)
141     {
142         CertGetNameStringW(cert, CERT_NAME_SIMPLE_DISPLAY_TYPE,
143          CERT_NAME_ISSUER_FLAG, NULL, *str, len);
144         item.pszText = *str;
145         item.iSubItem = 1;
146         SendMessageW(lv, LVM_SETITEMTEXTW, item.iItem, (LPARAM)&item);
147     }
148
149     GetLocaleInfoW(LOCALE_SYSTEM_DEFAULT, LOCALE_SSHORTDATE, dateFmt,
150      sizeof(dateFmt) / sizeof(dateFmt[0]));
151     FileTimeToSystemTime(&cert->pCertInfo->NotAfter, &sysTime);
152     GetDateFormatW(LOCALE_SYSTEM_DEFAULT, 0, &sysTime, dateFmt, date,
153      sizeof(date) / sizeof(date[0]));
154     item.pszText = date;
155     item.iSubItem = 2;
156     SendMessageW(lv, LVM_SETITEMTEXTW, item.iItem, (LPARAM)&item);
157
158     len = CertGetNameStringW(cert, CERT_NAME_FRIENDLY_DISPLAY_TYPE, 0, NULL,
159      NULL, 0);
160     if (len > *allocatedLen)
161     {
162         HeapFree(GetProcessHeap(), 0, *str);
163         *str = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
164         if (*str)
165             *allocatedLen = len;
166     }
167     if (*str)
168     {
169         CertGetNameStringW(cert, CERT_NAME_FRIENDLY_DISPLAY_TYPE, 0, NULL,
170          *str, len);
171         item.pszText = *str;
172         item.iSubItem = 3;
173         SendMessageW(lv, LVM_SETITEMTEXTW, item.iItem, (LPARAM)&item);
174     }
175 }
176
177 static LPSTR get_cert_mgr_usages(void)
178 {
179     static const WCHAR keyName[] = { 'S','o','f','t','w','a','r','e','\\','M',
180      'i','c','r','o','s','o','f','t','\\','C','r','y','p','t','o','g','r','a',
181      'p','h','y','\\','U','I','\\','C','e','r','t','m','g','r','\\','P','u',
182      'r','p','o','s','e',0 };
183     LPSTR str = NULL;
184     HKEY key;
185
186     if (!RegCreateKeyExW(HKEY_CURRENT_USER, keyName, 0, NULL, 0, KEY_READ,
187      NULL, &key, NULL))
188     {
189         LONG rc;
190         DWORD type, size;
191
192         rc = RegQueryValueExA(key, "Purpose", NULL, &type, NULL, &size);
193         if ((!rc || rc == ERROR_MORE_DATA) && type == REG_SZ)
194         {
195             str = HeapAlloc(GetProcessHeap(), 0, size);
196             if (str)
197             {
198                 rc = RegQueryValueExA(key, "Purpose", NULL, NULL, (LPBYTE)str,
199                  &size);
200                 if (rc)
201                 {
202                     HeapFree(GetProcessHeap(), 0, str);
203                     str = NULL;
204                 }
205             }
206         }
207         RegCloseKey(key);
208     }
209     return str;
210 }
211
212 typedef enum {
213     PurposeFilterShowAll = 0,
214     PurposeFilterShowAdvanced = 1,
215     PurposeFilterShowOID = 2
216 } PurposeFilter;
217
218 static void initialize_purpose_selection(HWND hwnd)
219 {
220     HWND cb = GetDlgItem(hwnd, IDC_MGR_PURPOSE_SELECTION);
221     WCHAR buf[MAX_STRING_LEN];
222     LPSTR usages;
223     int index;
224
225     LoadStringW(hInstance, IDS_PURPOSE_ALL, buf,
226      sizeof(buf) / sizeof(buf[0]));
227     index = SendMessageW(cb, CB_INSERTSTRING, -1, (LPARAM)buf);
228     SendMessageW(cb, CB_SETITEMDATA, index, (LPARAM)PurposeFilterShowAll);
229     LoadStringW(hInstance, IDS_PURPOSE_ADVANCED, buf,
230      sizeof(buf) / sizeof(buf[0]));
231     index = SendMessageW(cb, CB_INSERTSTRING, -1, (LPARAM)buf);
232     SendMessageW(cb, CB_SETITEMDATA, index, (LPARAM)PurposeFilterShowAdvanced);
233     SendMessageW(cb, CB_SETCURSEL, 0, 0);
234     if ((usages = get_cert_mgr_usages()))
235     {
236         LPSTR ptr, comma;
237
238         for (ptr = usages, comma = strchr(ptr, ','); ptr && *ptr;
239          ptr = comma ? comma + 1 : NULL,
240          comma = ptr ? strchr(ptr, ',') : NULL)
241         {
242             PCCRYPT_OID_INFO info;
243
244             if (comma)
245                 *comma = 0;
246             if ((info = CryptFindOIDInfo(CRYPT_OID_INFO_OID_KEY, ptr, 0)))
247             {
248                 index = SendMessageW(cb, CB_INSERTSTRING, 0,
249                  (LPARAM)info->pwszName);
250                 SendMessageW(cb, CB_SETITEMDATA, index, (LPARAM)info);
251             }
252         }
253         HeapFree(GetProcessHeap(), 0, usages);
254     }
255 }
256
257 extern BOOL WINAPI WTHelperGetKnownUsages(DWORD action,
258  PCCRYPT_OID_INFO **usages);
259
260 static CERT_ENHKEY_USAGE *add_oid_to_usage(CERT_ENHKEY_USAGE *usage, LPSTR oid)
261 {
262     if (!usage->cUsageIdentifier)
263         usage->rgpszUsageIdentifier = HeapAlloc(GetProcessHeap(), 0,
264          sizeof(LPSTR));
265     else
266         usage->rgpszUsageIdentifier = HeapReAlloc(GetProcessHeap(), 0,
267          usage->rgpszUsageIdentifier,
268          (usage->cUsageIdentifier + 1) * sizeof(LPSTR));
269     if (usage->rgpszUsageIdentifier)
270         usage->rgpszUsageIdentifier[usage->cUsageIdentifier++] = oid;
271     else
272     {
273         HeapFree(GetProcessHeap(), 0, usage);
274         usage = NULL;
275     }
276     return usage;
277 }
278
279 static CERT_ENHKEY_USAGE *convert_usages_str_to_usage(LPSTR usageStr)
280 {
281     CERT_ENHKEY_USAGE *usage = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
282      sizeof(CERT_ENHKEY_USAGE));
283
284     if (usage)
285     {
286         LPSTR ptr, comma;
287
288         for (ptr = usageStr, comma = strchr(ptr, ','); usage && ptr && *ptr;
289          ptr = comma ? comma + 1 : NULL,
290          comma = ptr ? strchr(ptr, ',') : NULL)
291         {
292             if (comma)
293                 *comma = 0;
294             add_oid_to_usage(usage, ptr);
295         }
296     }
297     return usage;
298 }
299
300 static CERT_ENHKEY_USAGE *create_advanced_filter(void)
301 {
302     CERT_ENHKEY_USAGE *advancedUsage = HeapAlloc(GetProcessHeap(),
303      HEAP_ZERO_MEMORY, sizeof(CERT_ENHKEY_USAGE));
304
305     if (advancedUsage)
306     {
307         PCCRYPT_OID_INFO *usages;
308
309         if (WTHelperGetKnownUsages(1, &usages))
310         {
311             LPSTR disabledUsagesStr;
312
313             if ((disabledUsagesStr = get_cert_mgr_usages()))
314             {
315                 CERT_ENHKEY_USAGE *disabledUsages =
316                  convert_usages_str_to_usage(disabledUsagesStr);
317
318                 if (disabledUsages)
319                 {
320                     PCCRYPT_OID_INFO *ptr;
321
322                     for (ptr = usages; *ptr; ptr++)
323                     {
324                         DWORD i;
325                         BOOL disabled = FALSE;
326
327                         for (i = 0; !disabled &&
328                          i < disabledUsages->cUsageIdentifier; i++)
329                             if (!strcmp(disabledUsages->rgpszUsageIdentifier[i],
330                              (*ptr)->pszOID))
331                                 disabled = TRUE;
332                         if (!disabled)
333                             add_oid_to_usage(advancedUsage,
334                              (LPSTR)(*ptr)->pszOID);
335                     }
336                     /* The individual strings are pointers to disabledUsagesStr,
337                      * so they're freed when it is.
338                      */
339                     HeapFree(GetProcessHeap(), 0,
340                      disabledUsages->rgpszUsageIdentifier);
341                     HeapFree(GetProcessHeap(), 0, disabledUsages);
342                 }
343                 HeapFree(GetProcessHeap(), 0, disabledUsagesStr);
344             }
345             WTHelperGetKnownUsages(2, &usages);
346         }
347     }
348     return advancedUsage;
349 }
350
351 static void show_store_certs(HWND hwnd, HCERTSTORE store)
352 {
353     HWND lv = GetDlgItem(hwnd, IDC_MGR_CERTS);
354     HWND cb = GetDlgItem(hwnd, IDC_MGR_PURPOSE_SELECTION);
355     PCCERT_CONTEXT cert = NULL;
356     DWORD allocatedLen = 0;
357     LPWSTR str = NULL;
358     int index;
359     PurposeFilter filter = PurposeFilterShowAll;
360     LPCSTR oid = NULL;
361     CERT_ENHKEY_USAGE *advanced = NULL;
362
363     index = SendMessageW(cb, CB_GETCURSEL, 0, 0);
364     if (index >= 0)
365     {
366         INT_PTR data = SendMessageW(cb, CB_GETITEMDATA, index, 0);
367
368         if (!HIWORD(data))
369             filter = data;
370         else
371         {
372             PCCRYPT_OID_INFO info = (PCCRYPT_OID_INFO)data;
373
374             filter = PurposeFilterShowOID;
375             oid = info->pszOID;
376         }
377     }
378     if (filter == PurposeFilterShowAdvanced)
379         advanced = create_advanced_filter();
380     do {
381         cert = CertEnumCertificatesInStore(store, cert);
382         if (cert)
383         {
384             BOOL show = FALSE;
385
386             if (filter == PurposeFilterShowAll)
387                 show = TRUE;
388             else
389             {
390                 int numOIDs;
391                 DWORD cbOIDs = 0;
392
393                 if (CertGetValidUsages(1, &cert, &numOIDs, NULL, &cbOIDs))
394                 {
395                     if (numOIDs == -1)
396                     {
397                         /* -1 implies all usages are valid */
398                         show = TRUE;
399                     }
400                     else
401                     {
402                         LPSTR *oids = HeapAlloc(GetProcessHeap(), 0, cbOIDs);
403
404                         if (oids)
405                         {
406                             if (CertGetValidUsages(1, &cert, &numOIDs, oids,
407                              &cbOIDs))
408                             {
409                                 int i;
410
411                                 if (filter == PurposeFilterShowOID)
412                                 {
413                                     for (i = 0; !show && i < numOIDs; i++)
414                                         if (!strcmp(oids[i], oid))
415                                             show = TRUE;
416                                 }
417                                 else
418                                 {
419                                     for (i = 0; !show && i < numOIDs; i++)
420                                     {
421                                         DWORD j;
422
423                                         for (j = 0; !show &&
424                                          j < advanced->cUsageIdentifier; j++)
425                                             if (!strcmp(oids[i],
426                                              advanced->rgpszUsageIdentifier[j]))
427                                                 show = TRUE;
428                                     }
429                                 }
430                             }
431                             HeapFree(GetProcessHeap(), 0, oids);
432                         }
433                     }
434                 }
435             }
436             if (show)
437                 add_cert_to_view(lv, cert, &allocatedLen, &str);
438         }
439     } while (cert);
440     HeapFree(GetProcessHeap(), 0, str);
441     if (advanced)
442     {
443         HeapFree(GetProcessHeap(), 0, advanced->rgpszUsageIdentifier);
444         HeapFree(GetProcessHeap(), 0, advanced);
445     }
446 }
447
448 static const WCHAR my[] = { 'M','y',0 };
449 static const WCHAR addressBook[] = {
450  'A','d','d','r','e','s','s','B','o','o','k',0 };
451 static const WCHAR ca[] = { 'C','A',0 };
452 static const WCHAR root[] = { 'R','o','o','t',0 };
453 static const WCHAR trustedPublisher[] = {
454  'T','r','u','s','t','e','d','P','u','b','l','i','s','h','e','r',0 };
455 static const WCHAR disallowed[] = { 'D','i','s','a','l','l','o','w','e','d',0 };
456
457 struct CertMgrStoreInfo
458 {
459     LPCWSTR name;
460     int removeWarning;
461     int removePluralWarning;
462 };
463
464 static const struct CertMgrStoreInfo defaultStoreList[] = {
465  { my, IDS_WARN_REMOVE_MY, IDS_WARN_REMOVE_PLURAL_MY },
466  { addressBook, IDS_WARN_REMOVE_ADDRESSBOOK,
467    IDS_WARN_REMOVE_PLURAL_ADDRESSBOOK },
468  { ca, IDS_WARN_REMOVE_CA, IDS_WARN_REMOVE_PLURAL_CA },
469  { root, IDS_WARN_REMOVE_ROOT, IDS_WARN_REMOVE_PLURAL_ROOT },
470  { trustedPublisher, IDS_WARN_REMOVE_TRUSTEDPUBLISHER,
471    IDS_WARN_REMOVE_PLURAL_TRUSTEDPUBLISHER },
472  { disallowed, IDS_WARN_REMOVE_DEFAULT },
473 };
474
475 static const struct CertMgrStoreInfo publisherStoreList[] = {
476  { root, IDS_WARN_REMOVE_ROOT, IDS_WARN_REMOVE_PLURAL_ROOT },
477  { trustedPublisher, IDS_WARN_REMOVE_TRUSTEDPUBLISHER,
478    IDS_WARN_REMOVE_PLURAL_TRUSTEDPUBLISHER },
479  { disallowed, IDS_WARN_REMOVE_PLURAL_DEFAULT },
480 };
481
482 struct CertMgrData
483 {
484     HIMAGELIST imageList;
485     LPCWSTR title;
486     DWORD nStores;
487     const struct CertMgrStoreInfo *stores;
488 };
489
490 static void show_cert_stores(HWND hwnd, DWORD dwFlags, struct CertMgrData *data)
491 {
492     const struct CertMgrStoreInfo *storeList;
493     int cStores, i;
494     HWND tab = GetDlgItem(hwnd, IDC_MGR_STORES);
495
496     if (dwFlags & CRYPTUI_CERT_MGR_PUBLISHER_TAB)
497     {
498         storeList = publisherStoreList;
499         cStores = sizeof(publisherStoreList) / sizeof(publisherStoreList[0]);
500     }
501     else
502     {
503         storeList = defaultStoreList;
504         cStores = sizeof(defaultStoreList) / sizeof(defaultStoreList[0]);
505     }
506     if (dwFlags & CRYPTUI_CERT_MGR_SINGLE_TAB_FLAG)
507         cStores = 1;
508     data->nStores = cStores;
509     data->stores = storeList;
510     for (i = 0; i < cStores; i++)
511     {
512         LPCWSTR name;
513         TCITEMW item;
514         HCERTSTORE store;
515
516         if (!(name = CryptFindLocalizedName(storeList[i].name)))
517             name = storeList[i].name;
518         store = CertOpenStore(CERT_STORE_PROV_SYSTEM_W, 0, 0,
519          CERT_SYSTEM_STORE_CURRENT_USER, storeList[i].name);
520         item.mask = TCIF_TEXT | TCIF_PARAM;
521         item.pszText = (LPWSTR)name;
522         item.lParam = (LPARAM)store;
523         SendMessageW(tab, TCM_INSERTITEMW, i, (LPARAM)&item);
524     }
525 }
526
527 static void free_certs(HWND lv)
528 {
529     LVITEMW item;
530     int items = SendMessageW(lv, LVM_GETITEMCOUNT, 0, 0), i;
531
532     for (i = 0; i < items; i++)
533     {
534         item.mask = LVIF_PARAM;
535         item.iItem = i;
536         item.iSubItem = 0;
537         SendMessageW(lv, LVM_GETITEMW, 0, (LPARAM)&item);
538         CertFreeCertificateContext((PCCERT_CONTEXT)item.lParam);
539     }
540 }
541
542 static HCERTSTORE cert_mgr_index_to_store(HWND tab, int index)
543 {
544     TCITEMW item;
545
546     item.mask = TCIF_PARAM;
547     SendMessageW(tab, TCM_GETITEMW, index, (LPARAM)&item);
548     return (HCERTSTORE)item.lParam;
549 }
550
551 static HCERTSTORE cert_mgr_current_store(HWND hwnd)
552 {
553     HWND tab = GetDlgItem(hwnd, IDC_MGR_STORES);
554
555     return cert_mgr_index_to_store(tab, SendMessageW(tab, TCM_GETCURSEL, 0, 0));
556 }
557
558 static void close_stores(HWND tab)
559 {
560     int i, tabs = SendMessageW(tab, TCM_GETITEMCOUNT, 0, 0);
561
562     for (i = 0; i < tabs; i++)
563         CertCloseStore(cert_mgr_index_to_store(tab, i), 0);
564 }
565
566 static void refresh_store_certs(HWND hwnd)
567 {
568     HWND lv = GetDlgItem(hwnd, IDC_MGR_CERTS);
569
570     free_certs(lv);
571     SendMessageW(lv, LVM_DELETEALLITEMS, 0, 0);
572     show_store_certs(hwnd, cert_mgr_current_store(hwnd));
573 }
574
575 typedef enum {
576     CheckBitmapIndexUnchecked = 1,
577     CheckBitmapIndexChecked = 2,
578     CheckBitmapIndexDisabledUnchecked = 3,
579     CheckBitmapIndexDisabledChecked = 4
580 } CheckBitmapIndex;
581
582 static void add_known_usage(HWND lv, PCCRYPT_OID_INFO info,
583  CheckBitmapIndex state)
584 {
585     LVITEMW item;
586
587     item.mask = LVIF_TEXT | LVIF_STATE | LVIF_PARAM;
588     item.state = INDEXTOSTATEIMAGEMASK(state);
589     item.stateMask = LVIS_STATEIMAGEMASK;
590     item.iItem = SendMessageW(lv, LVM_GETITEMCOUNT, 0, 0);
591     item.iSubItem = 0;
592     item.lParam = (LPARAM)info;
593     item.pszText = (LPWSTR)info->pwszName;
594     SendMessageW(lv, LVM_INSERTITEMW, 0, (LPARAM)&item);
595 }
596
597 static void add_known_usages_to_list(HWND lv, CheckBitmapIndex state)
598 {
599     PCCRYPT_OID_INFO *usages;
600
601     if (WTHelperGetKnownUsages(1, &usages))
602     {
603         PCCRYPT_OID_INFO *ptr;
604
605         for (ptr = usages; *ptr; ptr++)
606             add_known_usage(lv, *ptr, state);
607         WTHelperGetKnownUsages(2, &usages);
608     }
609 }
610
611 static void toggle_usage(HWND hwnd, int iItem)
612 {
613     LVITEMW item;
614     int res;
615     HWND lv = GetDlgItem(hwnd, IDC_CERTIFICATE_USAGES);
616
617     item.mask = LVIF_STATE;
618     item.iItem = iItem;
619     item.iSubItem = 0;
620     item.stateMask = LVIS_STATEIMAGEMASK;
621     res = SendMessageW(lv, LVM_GETITEMW, 0, (LPARAM)&item);
622     if (res)
623     {
624         int state = item.state >> 12;
625
626         item.state = INDEXTOSTATEIMAGEMASK(
627          state == CheckBitmapIndexChecked ? CheckBitmapIndexUnchecked :
628          CheckBitmapIndexChecked);
629         SendMessageW(lv, LVM_SETITEMSTATE, iItem, (LPARAM)&item);
630     }
631 }
632
633 static LONG_PTR find_oid_in_list(HWND lv, LPCSTR oid)
634 {
635     PCCRYPT_OID_INFO oidInfo = CryptFindOIDInfo(CRYPT_OID_INFO_OID_KEY,
636      (void *)oid, CRYPT_ENHKEY_USAGE_OID_GROUP_ID);
637     LONG_PTR ret;
638
639     if (oidInfo)
640     {
641         LVFINDINFOW findInfo;
642
643         findInfo.flags = LVFI_PARAM;
644         findInfo.lParam = (LPARAM)oidInfo;
645         ret = SendMessageW(lv, LVM_FINDITEMW, -1, (LPARAM)&findInfo);
646     }
647     else
648     {
649         LVFINDINFOA findInfo;
650
651         findInfo.flags = LVFI_STRING;
652         findInfo.psz = oid;
653         ret = SendMessageW(lv, LVM_FINDITEMA, -1, (LPARAM)&findInfo);
654     }
655     return ret;
656 }
657
658 static void save_cert_mgr_usages(HWND hwnd)
659 {
660     static const WCHAR keyName[] = { 'S','o','f','t','w','a','r','e','\\','M',
661      'i','c','r','o','s','o','f','t','\\','C','r','y','p','t','o','g','r','a',
662      'p','h','y','\\','U','I','\\','C','e','r','t','m','g','r','\\','P','u',
663      'r','p','o','s','e',0 };
664     HKEY key;
665     HWND lv = GetDlgItem(hwnd, IDC_CERTIFICATE_USAGES);
666     int purposes = SendMessageW(lv, LVM_GETITEMCOUNT, 0, 0), i;
667     LVITEMW item;
668     LPSTR str = NULL;
669
670     item.mask = LVIF_STATE | LVIF_PARAM;
671     item.iSubItem = 0;
672     item.stateMask = LVIS_STATEIMAGEMASK;
673     for (i = 0; i < purposes; i++)
674     {
675         item.iItem = i;
676         if (SendMessageW(lv, LVM_GETITEMW, 0, (LPARAM)&item))
677         {
678             int state = item.state >> 12;
679
680             if (state == CheckBitmapIndexUnchecked)
681             {
682                 CRYPT_OID_INFO *info = (CRYPT_OID_INFO *)item.lParam;
683                 BOOL firstString = TRUE;
684
685                 if (!str)
686                     str = HeapAlloc(GetProcessHeap(), 0,
687                      strlen(info->pszOID) + 1);
688                 else
689                 {
690                     str = HeapReAlloc(GetProcessHeap(), 0, str,
691                      strlen(str) + 1 + strlen(info->pszOID) + 1);
692                     firstString = FALSE;
693                 }
694                 if (str)
695                 {
696                     LPSTR ptr = firstString ? str : str + strlen(str);
697
698                     if (!firstString)
699                         *ptr++ = ',';
700                     strcpy(ptr, info->pszOID);
701                 }
702             }
703         }
704     }
705     if (!RegCreateKeyExW(HKEY_CURRENT_USER, keyName, 0, NULL, 0, KEY_ALL_ACCESS,
706      NULL, &key, NULL))
707     {
708         if (str)
709             RegSetValueExA(key, "Purpose", 0, REG_SZ, (const BYTE *)str,
710              strlen(str) + 1);
711         else
712             RegDeleteValueA(key, "Purpose");
713         RegCloseKey(key);
714     }
715     HeapFree(GetProcessHeap(), 0, str);
716 }
717
718 static LRESULT CALLBACK cert_mgr_advanced_dlg_proc(HWND hwnd, UINT msg,
719  WPARAM wp, LPARAM lp)
720 {
721     switch (msg)
722     {
723     case WM_INITDIALOG:
724     {
725         RECT rc;
726         LVCOLUMNW column;
727         HWND lv = GetDlgItem(hwnd, IDC_CERTIFICATE_USAGES);
728         HIMAGELIST imageList;
729         LPSTR disabledUsages;
730
731         GetWindowRect(lv, &rc);
732         column.mask = LVCF_WIDTH;
733         column.cx = rc.right - rc.left;
734         SendMessageW(lv, LVM_INSERTCOLUMNW, 0, (LPARAM)&column);
735         imageList = ImageList_Create(16, 16, ILC_COLOR4 | ILC_MASK, 4, 0);
736         if (imageList)
737         {
738             HBITMAP bmp;
739             COLORREF backColor = RGB(255, 0, 255);
740
741             bmp = LoadBitmapW(hInstance, MAKEINTRESOURCEW(IDB_CHECKS));
742             ImageList_AddMasked(imageList, bmp, backColor);
743             DeleteObject(bmp);
744             ImageList_SetBkColor(imageList, CLR_NONE);
745             SendMessageW(lv, LVM_SETIMAGELIST, LVSIL_STATE, (LPARAM)imageList);
746             SetWindowLongPtrW(hwnd, DWLP_USER, (LPARAM)imageList);
747         }
748         add_known_usages_to_list(lv, CheckBitmapIndexChecked);
749         if ((disabledUsages = get_cert_mgr_usages()))
750         {
751             LPSTR ptr, comma;
752
753             for (ptr = disabledUsages, comma = strchr(ptr, ','); ptr && *ptr;
754              ptr = comma ? comma + 1 : NULL,
755              comma = ptr ? strchr(ptr, ',') : NULL)
756             {
757                 LONG_PTR index;
758
759                 if (comma)
760                     *comma = 0;
761                 if ((index = find_oid_in_list(lv, ptr)) != -1)
762                     toggle_usage(hwnd, index);
763             }
764             HeapFree(GetProcessHeap(), 0, disabledUsages);
765         }
766         break;
767     }
768     case WM_NOTIFY:
769     {
770         NMHDR *hdr = (NMHDR *)lp;
771         NMITEMACTIVATE *nm;
772
773         switch (hdr->code)
774         {
775         case NM_CLICK:
776             nm = (NMITEMACTIVATE *)lp;
777             toggle_usage(hwnd, nm->iItem);
778             SendMessageW(GetParent(hwnd), PSM_CHANGED, (WPARAM)hwnd, 0);
779             break;
780         }
781         break;
782     }
783     case WM_COMMAND:
784         switch (wp)
785         {
786         case IDOK:
787             save_cert_mgr_usages(hwnd);
788             ImageList_Destroy((HIMAGELIST)GetWindowLongPtrW(hwnd, DWLP_USER));
789             EndDialog(hwnd, IDOK);
790             break;
791         case IDCANCEL:
792             ImageList_Destroy((HIMAGELIST)GetWindowLongPtrW(hwnd, DWLP_USER));
793             EndDialog(hwnd, IDCANCEL);
794             break;
795         }
796         break;
797     }
798     return 0;
799 }
800
801 static void cert_mgr_clear_cert_selection(HWND hwnd)
802 {
803     WCHAR empty[] = { 0 };
804
805     EnableWindow(GetDlgItem(hwnd, IDC_MGR_EXPORT), FALSE);
806     EnableWindow(GetDlgItem(hwnd, IDC_MGR_REMOVE), FALSE);
807     EnableWindow(GetDlgItem(hwnd, IDC_MGR_VIEW), FALSE);
808     SendMessageW(GetDlgItem(hwnd, IDC_MGR_PURPOSES), WM_SETTEXT, 0,
809      (LPARAM)empty);
810     refresh_store_certs(hwnd);
811 }
812
813 static PCCERT_CONTEXT cert_mgr_index_to_cert(HWND hwnd, int index)
814 {
815     PCCERT_CONTEXT cert = NULL;
816     LVITEMW item;
817
818     item.mask = LVIF_PARAM;
819     item.iItem = index;
820     item.iSubItem = 0;
821     if (SendMessageW(GetDlgItem(hwnd, IDC_MGR_CERTS), LVM_GETITEMW, 0,
822      (LPARAM)&item))
823         cert = (PCCERT_CONTEXT)item.lParam;
824     return cert;
825 }
826
827 static void show_selected_cert(HWND hwnd, int index)
828 {
829     PCCERT_CONTEXT cert = cert_mgr_index_to_cert(hwnd, index);
830
831     if (cert)
832     {
833         CRYPTUI_VIEWCERTIFICATE_STRUCTW viewInfo;
834
835         memset(&viewInfo, 0, sizeof(viewInfo));
836         viewInfo.dwSize = sizeof(viewInfo);
837         viewInfo.hwndParent = hwnd;
838         viewInfo.pCertContext = cert;
839         /* FIXME: this should be modal */
840         CryptUIDlgViewCertificateW(&viewInfo, NULL);
841     }
842 }
843
844 static void cert_mgr_show_cert_usages(HWND hwnd, int index)
845 {
846     HWND text = GetDlgItem(hwnd, IDC_MGR_PURPOSES);
847     PCCERT_CONTEXT cert = cert_mgr_index_to_cert(hwnd, index);
848     PCERT_ENHKEY_USAGE usage;
849     DWORD size;
850
851     /* Get enhanced key usage.  Have to check for a property and an extension
852      * separately, because CertGetEnhancedKeyUsage will succeed and return an
853      * empty usage if neither is set.  Unfortunately an empty usage implies
854      * no usage is allowed, so we have to distinguish between the two cases.
855      */
856     if (CertGetEnhancedKeyUsage(cert, CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG,
857      NULL, &size))
858     {
859         usage = HeapAlloc(GetProcessHeap(), 0, size);
860         if (!CertGetEnhancedKeyUsage(cert,
861          CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG, usage, &size))
862         {
863             HeapFree(GetProcessHeap(), 0, usage);
864             usage = NULL;
865         }
866     }
867     else if (CertGetEnhancedKeyUsage(cert, CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG,
868      NULL, &size))
869     {
870         usage = HeapAlloc(GetProcessHeap(), 0, size);
871         if (!CertGetEnhancedKeyUsage(cert,
872          CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG, usage, &size))
873         {
874             HeapFree(GetProcessHeap(), 0, usage);
875             usage = NULL;
876         }
877     }
878     else
879         usage = NULL;
880     if (usage)
881     {
882         if (usage->cUsageIdentifier)
883         {
884             static const WCHAR commaSpace[] = { ',',' ',0 };
885             DWORD i, len = 1;
886             LPWSTR str, ptr;
887
888             for (i = 0; i < usage->cUsageIdentifier; i++)
889             {
890                 PCCRYPT_OID_INFO info =
891                  CryptFindOIDInfo(CRYPT_OID_INFO_OID_KEY,
892                  usage->rgpszUsageIdentifier[i],
893                  CRYPT_ENHKEY_USAGE_OID_GROUP_ID);
894
895                 if (info)
896                     len += strlenW(info->pwszName);
897                 else
898                     len += strlen(usage->rgpszUsageIdentifier[i]);
899                 if (i < usage->cUsageIdentifier - 1)
900                     len += strlenW(commaSpace);
901             }
902             str = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
903             if (str)
904             {
905                 for (i = 0, ptr = str; i < usage->cUsageIdentifier; i++)
906                 {
907                     PCCRYPT_OID_INFO info =
908                      CryptFindOIDInfo(CRYPT_OID_INFO_OID_KEY,
909                      usage->rgpszUsageIdentifier[i],
910                      CRYPT_ENHKEY_USAGE_OID_GROUP_ID);
911
912                     if (info)
913                     {
914                         strcpyW(ptr, info->pwszName);
915                         ptr += strlenW(info->pwszName);
916                     }
917                     else
918                     {
919                         LPCSTR src = usage->rgpszUsageIdentifier[i];
920
921                         for (; *src; ptr++, src++)
922                             *ptr = *src;
923                         *ptr = 0;
924                     }
925                     if (i < usage->cUsageIdentifier - 1)
926                     {
927                         strcpyW(ptr, commaSpace);
928                         ptr += strlenW(commaSpace);
929                     }
930                 }
931                 *ptr = 0;
932                 SendMessageW(text, WM_SETTEXT, 0, (LPARAM)str);
933                 HeapFree(GetProcessHeap(), 0, str);
934             }
935             HeapFree(GetProcessHeap(), 0, usage);
936         }
937         else
938         {
939             WCHAR buf[MAX_STRING_LEN];
940
941             LoadStringW(hInstance, IDS_ALLOWED_PURPOSE_NONE, buf,
942              sizeof(buf) / sizeof(buf[0]));
943             SendMessageW(text, WM_SETTEXT, 0, (LPARAM)buf);
944         }
945     }
946     else
947     {
948         WCHAR buf[MAX_STRING_LEN];
949
950         LoadStringW(hInstance, IDS_ALLOWED_PURPOSE_ALL, buf,
951          sizeof(buf) / sizeof(buf[0]));
952         SendMessageW(text, WM_SETTEXT, 0, (LPARAM)buf);
953     }
954 }
955
956 static void cert_mgr_do_remove(HWND hwnd)
957 {
958     int tabIndex = SendMessageW(GetDlgItem(hwnd, IDC_MGR_STORES),
959      TCM_GETCURSEL, 0, 0);
960     struct CertMgrData *data =
961      (struct CertMgrData *)GetWindowLongPtrW(hwnd, DWLP_USER);
962
963     if (tabIndex < data->nStores)
964     {
965         HWND lv = GetDlgItem(hwnd, IDC_MGR_CERTS);
966         WCHAR warning[MAX_STRING_LEN], title[MAX_STRING_LEN];
967         LPCWSTR pTitle;
968         int warningID;
969
970         if (SendMessageW(lv, LVM_GETSELECTEDCOUNT, 0, 0) > 1)
971             warningID = data->stores[tabIndex].removePluralWarning;
972         else
973             warningID = data->stores[tabIndex].removeWarning;
974         if (data->title)
975             pTitle = data->title;
976         else
977         {
978             LoadStringW(hInstance, IDS_CERT_MGR, title,
979              sizeof(title) / sizeof(title[0]));
980             pTitle = title;
981         }
982         LoadStringW(hInstance, warningID, warning,
983          sizeof(warning) / sizeof(warning[0]));
984         if (MessageBoxW(hwnd, warning, pTitle, MB_YESNO) == IDYES)
985         {
986             int selection = -1;
987
988             do {
989                 selection = SendMessageW(lv, LVM_GETNEXTITEM, selection,
990                  LVNI_SELECTED);
991                 if (selection >= 0)
992                 {
993                     PCCERT_CONTEXT cert = cert_mgr_index_to_cert(hwnd,
994                      selection);
995
996                     CertDeleteCertificateFromStore(cert);
997                 }
998             } while (selection >= 0);
999             cert_mgr_clear_cert_selection(hwnd);
1000         }
1001     }
1002 }
1003
1004 static void cert_mgr_do_export(HWND hwnd)
1005 {
1006     HWND lv = GetDlgItem(hwnd, IDC_MGR_CERTS);
1007     int selectionCount = SendMessageW(lv, LVM_GETSELECTEDCOUNT, 0, 0);
1008
1009     if (selectionCount == 1)
1010     {
1011         int selection = SendMessageW(lv, LVM_GETNEXTITEM, -1,
1012          LVNI_SELECTED);
1013
1014         if (selection >= 0)
1015         {
1016             PCCERT_CONTEXT cert = cert_mgr_index_to_cert(hwnd, selection);
1017
1018             if (cert)
1019             {
1020                 CRYPTUI_WIZ_EXPORT_INFO info;
1021
1022                 info.dwSize = sizeof(info);
1023                 info.pwszExportFileName = NULL;
1024                 info.dwSubjectChoice = CRYPTUI_WIZ_EXPORT_CERT_CONTEXT;
1025                 info.u.pCertContext = cert;
1026                 info.cStores = 0;
1027                 CryptUIWizExport(0, hwnd, NULL, &info, NULL);
1028             }
1029         }
1030     }
1031     else if (selectionCount > 1)
1032     {
1033         HCERTSTORE store = CertOpenStore(CERT_STORE_PROV_MEMORY, 0, 0,
1034          CERT_STORE_CREATE_NEW_FLAG, NULL);
1035
1036         if (store)
1037         {
1038             CRYPTUI_WIZ_EXPORT_INFO info;
1039             int selection = -1;
1040
1041             info.dwSize = sizeof(info);
1042             info.pwszExportFileName = NULL;
1043             info.dwSubjectChoice =
1044              CRYPTUI_WIZ_EXPORT_CERT_STORE_CERTIFICATES_ONLY;
1045             info.u.hCertStore = store;
1046             info.cStores = 0;
1047             do {
1048                 selection = SendMessageW(lv, LVM_GETNEXTITEM, selection,
1049                  LVNI_SELECTED);
1050                 if (selection >= 0)
1051                 {
1052                     PCCERT_CONTEXT cert = cert_mgr_index_to_cert(hwnd,
1053                      selection);
1054
1055                     CertAddCertificateContextToStore(store, cert,
1056                      CERT_STORE_ADD_ALWAYS, NULL);
1057                 }
1058             } while (selection >= 0);
1059             CryptUIWizExport(0, hwnd, NULL, &info, NULL);
1060             CertCloseStore(store, 0);
1061         }
1062     }
1063 }
1064
1065 static LRESULT CALLBACK cert_mgr_dlg_proc(HWND hwnd, UINT msg, WPARAM wp,
1066  LPARAM lp)
1067 {
1068     struct CertMgrData *data;
1069
1070     switch (msg)
1071     {
1072     case WM_INITDIALOG:
1073     {
1074         PCCRYPTUI_CERT_MGR_STRUCT pCryptUICertMgr =
1075          (PCCRYPTUI_CERT_MGR_STRUCT)lp;
1076         HWND tab = GetDlgItem(hwnd, IDC_MGR_STORES);
1077
1078         data = HeapAlloc(GetProcessHeap(), 0, sizeof(struct CertMgrData));
1079         if (!data)
1080             return 0;
1081         data->imageList = ImageList_Create(16, 16, ILC_COLOR4 | ILC_MASK, 2, 0);
1082         if (data->imageList)
1083         {
1084             HBITMAP bmp;
1085             COLORREF backColor = RGB(255, 0, 255);
1086
1087             bmp = LoadBitmapW(hInstance, MAKEINTRESOURCEW(IDB_SMALL_ICONS));
1088             ImageList_AddMasked(data->imageList, bmp, backColor);
1089             DeleteObject(bmp);
1090             ImageList_SetBkColor(data->imageList, CLR_NONE);
1091             SendMessageW(GetDlgItem(hwnd, IDC_MGR_CERTS), LVM_SETIMAGELIST,
1092                          LVSIL_SMALL, (LPARAM)data->imageList);
1093         }
1094         SetWindowLongPtrW(hwnd, DWLP_USER, (LPARAM)data);
1095         data->title = pCryptUICertMgr->pwszTitle;
1096
1097         initialize_purpose_selection(hwnd);
1098         add_cert_columns(hwnd);
1099         if (pCryptUICertMgr->pwszTitle)
1100             SendMessageW(hwnd, WM_SETTEXT, 0,
1101              (LPARAM)pCryptUICertMgr->pwszTitle);
1102         show_cert_stores(hwnd, pCryptUICertMgr->dwFlags, data);
1103         show_store_certs(hwnd, cert_mgr_index_to_store(tab, 0));
1104         break;
1105     }
1106     case WM_NOTIFY:
1107     {
1108         NMHDR *hdr = (NMHDR *)lp;
1109
1110         switch (hdr->code)
1111         {
1112         case TCN_SELCHANGE:
1113             cert_mgr_clear_cert_selection(hwnd);
1114             break;
1115         case LVN_ITEMCHANGED:
1116         {
1117             NMITEMACTIVATE *nm;
1118             HWND lv = GetDlgItem(hwnd, IDC_MGR_CERTS);
1119
1120             nm = (NMITEMACTIVATE*)lp;
1121             if (nm->uNewState & LVN_ITEMACTIVATE)
1122             {
1123                 int numSelected = SendMessageW(lv, LVM_GETSELECTEDCOUNT, 0, 0);
1124
1125                 EnableWindow(GetDlgItem(hwnd, IDC_MGR_EXPORT), numSelected > 0);
1126                 EnableWindow(GetDlgItem(hwnd, IDC_MGR_REMOVE), numSelected > 0);
1127                 EnableWindow(GetDlgItem(hwnd, IDC_MGR_VIEW), numSelected == 1);
1128                 if (numSelected == 1)
1129                     cert_mgr_show_cert_usages(hwnd, nm->iItem);
1130             }
1131             break;
1132         }
1133         case NM_DBLCLK:
1134             show_selected_cert(hwnd, ((NMITEMACTIVATE *)lp)->iItem);
1135             break;
1136         case LVN_KEYDOWN:
1137         {
1138             NMLVKEYDOWN *lvk = (NMLVKEYDOWN *)lp;
1139
1140             if (lvk->wVKey == VK_DELETE)
1141                 cert_mgr_do_remove(hwnd);
1142             break;
1143         }
1144         }
1145         break;
1146     }
1147     case WM_COMMAND:
1148         switch (wp)
1149         {
1150         case ((CBN_SELCHANGE << 16) | IDC_MGR_PURPOSE_SELECTION):
1151             cert_mgr_clear_cert_selection(hwnd);
1152             break;
1153         case IDC_MGR_IMPORT:
1154             if (CryptUIWizImport(0, hwnd, NULL, NULL,
1155              cert_mgr_current_store(hwnd)))
1156                 refresh_store_certs(hwnd);
1157             break;
1158         case IDC_MGR_ADVANCED:
1159             if (DialogBoxW(hInstance, MAKEINTRESOURCEW(IDD_CERT_MGR_ADVANCED),
1160              hwnd, cert_mgr_advanced_dlg_proc) == IDOK)
1161             {
1162                 HWND cb = GetDlgItem(hwnd, IDC_MGR_PURPOSE_SELECTION);
1163                 int index, len;
1164                 LPWSTR curString = NULL;
1165
1166                 index = SendMessageW(cb, CB_GETCURSEL, 0, 0);
1167                 if (index >= 0)
1168                 {
1169                     len = SendMessageW(cb, CB_GETLBTEXTLEN, index, 0);
1170                     curString = HeapAlloc(GetProcessHeap(), 0,
1171                      (len + 1) * sizeof(WCHAR));
1172                     SendMessageW(cb, CB_GETLBTEXT, index, (LPARAM)curString);
1173                 }
1174                 SendMessageW(cb, CB_RESETCONTENT, 0, 0);
1175                 initialize_purpose_selection(hwnd);
1176                 if (curString)
1177                 {
1178                     index = SendMessageW(cb, CB_FINDSTRINGEXACT, -1,
1179                      (LPARAM)curString);
1180                     if (index >= 0)
1181                         SendMessageW(cb, CB_SETCURSEL, index, 0);
1182                     HeapFree(GetProcessHeap(), 0, curString);
1183                 }
1184                 refresh_store_certs(hwnd);
1185             }
1186             break;
1187         case IDC_MGR_VIEW:
1188         {
1189             HWND lv = GetDlgItem(hwnd, IDC_MGR_CERTS);
1190             int selection = SendMessageW(lv, LVM_GETNEXTITEM, -1,
1191              LVNI_SELECTED);
1192
1193             if (selection >= 0)
1194                 show_selected_cert(hwnd, selection);
1195             break;
1196         }
1197         case IDC_MGR_EXPORT:
1198             cert_mgr_do_export(hwnd);
1199             break;
1200         case IDC_MGR_REMOVE:
1201             cert_mgr_do_remove(hwnd);
1202             break;
1203         case IDCANCEL:
1204             free_certs(GetDlgItem(hwnd, IDC_MGR_CERTS));
1205             close_stores(GetDlgItem(hwnd, IDC_MGR_STORES));
1206             close_stores(GetDlgItem(hwnd, IDC_MGR_STORES));
1207             data = (struct CertMgrData *)GetWindowLongPtrW(hwnd, DWLP_USER);
1208             ImageList_Destroy(data->imageList);
1209             HeapFree(GetProcessHeap(), 0, data);
1210             EndDialog(hwnd, IDCANCEL);
1211             break;
1212         }
1213         break;
1214     }
1215     return 0;
1216 }
1217
1218 /***********************************************************************
1219  *              CryptUIDlgCertMgr (CRYPTUI.@)
1220  */
1221 BOOL WINAPI CryptUIDlgCertMgr(PCCRYPTUI_CERT_MGR_STRUCT pCryptUICertMgr)
1222 {
1223     TRACE("(%p)\n", pCryptUICertMgr);
1224
1225     if (pCryptUICertMgr->dwSize != sizeof(CRYPTUI_CERT_MGR_STRUCT))
1226     {
1227         WARN("unexpected size %d\n", pCryptUICertMgr->dwSize);
1228         SetLastError(E_INVALIDARG);
1229         return FALSE;
1230     }
1231     DialogBoxParamW(hInstance, MAKEINTRESOURCEW(IDD_CERT_MGR),
1232      pCryptUICertMgr->hwndParent, cert_mgr_dlg_proc, (LPARAM)pCryptUICertMgr);
1233     return TRUE;
1234 }
1235
1236 /* FIXME: real names are unknown, functions are undocumented */
1237 typedef struct _CRYPTUI_ENUM_SYSTEM_STORE_ARGS
1238 {
1239     DWORD dwFlags;
1240     void *pvSystemStoreLocationPara;
1241 } CRYPTUI_ENUM_SYSTEM_STORE_ARGS, *PCRYPTUI_ENUM_SYSTEM_STORE_ARGS;
1242
1243 typedef struct _CRYPTUI_ENUM_DATA
1244 {
1245     DWORD                           cStores;
1246     HCERTSTORE                     *rghStore;
1247     DWORD                           cEnumArgs;
1248     PCRYPTUI_ENUM_SYSTEM_STORE_ARGS rgEnumArgs;
1249 } CRYPTUI_ENUM_DATA, *PCRYPTUI_ENUM_DATA;
1250
1251 typedef BOOL (WINAPI *PFN_SELECTED_STORE_CB)(HCERTSTORE store, HWND hwnd,
1252  void *pvArg);
1253
1254 /* Values for dwFlags */
1255 #define CRYPTUI_ENABLE_SHOW_PHYSICAL_STORE 0x00000001
1256
1257 typedef struct _CRYPTUI_SELECTSTORE_INFO_A
1258 {
1259     DWORD                 dwSize;
1260     HWND                  parent;
1261     DWORD                 dwFlags;
1262     LPSTR                 pszTitle;
1263     LPSTR                 pszText;
1264     CRYPTUI_ENUM_DATA    *pEnumData;
1265     PFN_SELECTED_STORE_CB pfnSelectedStoreCallback;
1266     void                 *pvArg;
1267 } CRYPTUI_SELECTSTORE_INFO_A, *PCRYPTUI_SELECTSTORE_INFO_A;
1268
1269 typedef struct _CRYPTUI_SELECTSTORE_INFO_W
1270 {
1271     DWORD                 dwSize;
1272     HWND                  parent;
1273     DWORD                 dwFlags;
1274     LPWSTR                pwszTitle;
1275     LPWSTR                pwszText;
1276     CRYPTUI_ENUM_DATA    *pEnumData;
1277     PFN_SELECTED_STORE_CB pfnSelectedStoreCallback;
1278     void                 *pvArg;
1279 } CRYPTUI_SELECTSTORE_INFO_W, *PCRYPTUI_SELECTSTORE_INFO_W;
1280
1281 struct StoreInfo
1282 {
1283     enum {
1284         StoreHandle,
1285         SystemStore
1286     } type;
1287     union {
1288         HCERTSTORE store;
1289         LPWSTR name;
1290     } DUMMYUNIONNAME;
1291 };
1292
1293 static BOOL WINAPI enum_store_callback(const void *pvSystemStore,
1294  DWORD dwFlags, PCERT_SYSTEM_STORE_INFO pStoreInfo, void *pvReserved,
1295  void *pvArg)
1296 {
1297     HWND tree = GetDlgItem(pvArg, IDC_STORE_LIST);
1298     TVINSERTSTRUCTW tvis;
1299     LPCWSTR localizedName;
1300     BOOL ret = TRUE;
1301
1302     tvis.hParent = NULL;
1303     tvis.hInsertAfter = TVI_LAST;
1304     tvis.u.item.mask = TVIF_TEXT;
1305     if ((localizedName = CryptFindLocalizedName(pvSystemStore)))
1306     {
1307         struct StoreInfo *storeInfo = HeapAlloc(GetProcessHeap(), 0,
1308          sizeof(struct StoreInfo));
1309
1310         if (storeInfo)
1311         {
1312             storeInfo->type = SystemStore;
1313             storeInfo->u.name = HeapAlloc(GetProcessHeap(), 0,
1314              (strlenW(pvSystemStore) + 1) * sizeof(WCHAR));
1315             if (storeInfo->u.name)
1316             {
1317                 tvis.u.item.mask |= TVIF_PARAM;
1318                 tvis.u.item.lParam = (LPARAM)storeInfo;
1319                 strcpyW(storeInfo->u.name, pvSystemStore);
1320             }
1321             else
1322             {
1323                 HeapFree(GetProcessHeap(), 0, storeInfo);
1324                 ret = FALSE;
1325             }
1326         }
1327         else
1328             ret = FALSE;
1329         tvis.u.item.pszText = (LPWSTR)localizedName;
1330     }
1331     else
1332         tvis.u.item.pszText = (LPWSTR)pvSystemStore;
1333     /* FIXME: need a folder icon for the store too */
1334     if (ret)
1335         SendMessageW(tree, TVM_INSERTITEMW, 0, (LPARAM)&tvis);
1336     return ret;
1337 }
1338
1339 static void enumerate_stores(HWND hwnd, CRYPTUI_ENUM_DATA *pEnumData)
1340 {
1341     DWORD i;
1342     HWND tree = GetDlgItem(hwnd, IDC_STORE_LIST);
1343
1344     for (i = 0; i < pEnumData->cEnumArgs; i++)
1345         CertEnumSystemStore(pEnumData->rgEnumArgs[i].dwFlags,
1346          pEnumData->rgEnumArgs[i].pvSystemStoreLocationPara,
1347          hwnd, enum_store_callback);
1348     for (i = 0; i < pEnumData->cStores; i++)
1349     {
1350         DWORD size;
1351
1352         if (CertGetStoreProperty(pEnumData->rghStore[i],
1353          CERT_STORE_LOCALIZED_NAME_PROP_ID, NULL, &size))
1354         {
1355             LPWSTR name = HeapAlloc(GetProcessHeap(), 0, size);
1356
1357             if (name)
1358             {
1359                 if (CertGetStoreProperty(pEnumData->rghStore[i],
1360                  CERT_STORE_LOCALIZED_NAME_PROP_ID, name, &size))
1361                 {
1362                     struct StoreInfo *storeInfo = HeapAlloc(GetProcessHeap(),
1363                      0, sizeof(struct StoreInfo));
1364
1365                     if (storeInfo)
1366                     {
1367                         TVINSERTSTRUCTW tvis;
1368
1369                         storeInfo->type = StoreHandle;
1370                         storeInfo->u.store = pEnumData->rghStore[i];
1371                         tvis.hParent = NULL;
1372                         tvis.hInsertAfter = TVI_LAST;
1373                         tvis.u.item.mask = TVIF_TEXT | TVIF_PARAM;
1374                         tvis.u.item.pszText = name;
1375                         tvis.u.item.lParam = (LPARAM)storeInfo;
1376                         SendMessageW(tree, TVM_INSERTITEMW, 0, (LPARAM)&tvis);
1377                     }
1378                 }
1379                 HeapFree(GetProcessHeap(), 0, name);
1380             }
1381         }
1382     }
1383 }
1384
1385 static void free_store_info(HWND tree)
1386 {
1387     HTREEITEM next = (HTREEITEM)SendMessageW(tree, TVM_GETNEXTITEM, TVGN_CHILD,
1388      (LPARAM)NULL);
1389
1390     while (next)
1391     {
1392         TVITEMW item;
1393
1394         memset(&item, 0, sizeof(item));
1395         item.mask = TVIF_HANDLE | TVIF_PARAM;
1396         item.hItem = next;
1397         SendMessageW(tree, TVM_GETITEMW, 0, (LPARAM)&item);
1398         if (item.lParam)
1399         {
1400             struct StoreInfo *storeInfo = (struct StoreInfo *)item.lParam;
1401
1402             if (storeInfo->type == SystemStore)
1403                 HeapFree(GetProcessHeap(), 0, storeInfo->u.name);
1404             HeapFree(GetProcessHeap(), 0, storeInfo);
1405         }
1406         next = (HTREEITEM)SendMessageW(tree, TVM_GETNEXTITEM, TVGN_NEXT,
1407          (LPARAM)next);
1408     }
1409 }
1410
1411 static HCERTSTORE selected_item_to_store(HWND tree, HTREEITEM hItem)
1412 {
1413     WCHAR buf[MAX_STRING_LEN];
1414     TVITEMW item;
1415     HCERTSTORE store;
1416
1417     memset(&item, 0, sizeof(item));
1418     item.mask = TVIF_HANDLE | TVIF_PARAM | TVIF_TEXT;
1419     item.hItem = hItem;
1420     item.cchTextMax = sizeof(buf) / sizeof(buf[0]);
1421     item.pszText = buf;
1422     SendMessageW(tree, TVM_GETITEMW, 0, (LPARAM)&item);
1423     if (item.lParam)
1424     {
1425         struct StoreInfo *storeInfo = (struct StoreInfo *)item.lParam;
1426
1427         if (storeInfo->type == StoreHandle)
1428             store = storeInfo->u.store;
1429         else
1430             store = CertOpenSystemStoreW(0, storeInfo->u.name);
1431     }
1432     else
1433     {
1434         /* It's implicitly a system store */
1435         store = CertOpenSystemStoreW(0, buf);
1436     }
1437     return store;
1438 }
1439
1440 struct SelectStoreInfo
1441 {
1442     PCRYPTUI_SELECTSTORE_INFO_W info;
1443     HCERTSTORE                  store;
1444 };
1445
1446 static LRESULT CALLBACK select_store_dlg_proc(HWND hwnd, UINT msg, WPARAM wp,
1447  LPARAM lp)
1448 {
1449     struct SelectStoreInfo *selectInfo;
1450     LRESULT ret = 0;
1451
1452     switch (msg)
1453     {
1454     case WM_INITDIALOG:
1455     {
1456         selectInfo = (struct SelectStoreInfo *)lp;
1457         SetWindowLongPtrW(hwnd, DWLP_USER, lp);
1458         if (selectInfo->info->pwszTitle)
1459             SendMessageW(hwnd, WM_SETTEXT, 0,
1460              (LPARAM)selectInfo->info->pwszTitle);
1461         if (selectInfo->info->pwszText)
1462             SendMessageW(GetDlgItem(hwnd, IDC_STORE_TEXT), WM_SETTEXT, 0,
1463              (LPARAM)selectInfo->info->pwszText);
1464         if (!(selectInfo->info->dwFlags & CRYPTUI_ENABLE_SHOW_PHYSICAL_STORE))
1465             ShowWindow(GetDlgItem(hwnd, IDC_SHOW_PHYSICAL_STORES), FALSE);
1466         enumerate_stores(hwnd, selectInfo->info->pEnumData);
1467         break;
1468     }
1469     case WM_COMMAND:
1470         switch (wp)
1471         {
1472         case IDOK:
1473         {
1474             HWND tree = GetDlgItem(hwnd, IDC_STORE_LIST);
1475             HTREEITEM selection = (HTREEITEM)SendMessageW(tree,
1476              TVM_GETNEXTITEM, TVGN_CARET, (LPARAM)NULL);
1477
1478             selectInfo = (struct SelectStoreInfo *)GetWindowLongPtrW(hwnd,
1479              DWLP_USER);
1480             if (!selection)
1481             {
1482                 WCHAR title[MAX_STRING_LEN], error[MAX_STRING_LEN], *pTitle;
1483
1484                 if (selectInfo->info->pwszTitle)
1485                     pTitle = selectInfo->info->pwszTitle;
1486                 else
1487                 {
1488                     LoadStringW(hInstance, IDS_SELECT_STORE_TITLE, title,
1489                      sizeof(title) / sizeof(title[0]));
1490                     pTitle = title;
1491                 }
1492                 LoadStringW(hInstance, IDS_SELECT_STORE, error,
1493                  sizeof(error) / sizeof(error[0]));
1494                 MessageBoxW(hwnd, error, pTitle, MB_ICONEXCLAMATION | MB_OK);
1495             }
1496             else
1497             {
1498                 HCERTSTORE store = selected_item_to_store(tree, selection);
1499
1500                 if (!selectInfo->info->pfnSelectedStoreCallback ||
1501                  selectInfo->info->pfnSelectedStoreCallback(store, hwnd,
1502                  selectInfo->info->pvArg))
1503                 {
1504                     selectInfo->store = store;
1505                     free_store_info(tree);
1506                     EndDialog(hwnd, IDOK);
1507                 }
1508                 else
1509                     CertCloseStore(store, 0);
1510             }
1511             ret = TRUE;
1512             break;
1513         }
1514         case IDCANCEL:
1515             free_store_info(GetDlgItem(hwnd, IDC_STORE_LIST));
1516             EndDialog(hwnd, IDCANCEL);
1517             ret = TRUE;
1518             break;
1519         }
1520         break;
1521     }
1522     return ret;
1523 }
1524
1525 /***********************************************************************
1526  *              CryptUIDlgSelectStoreW (CRYPTUI.@)
1527  */
1528 HCERTSTORE WINAPI CryptUIDlgSelectStoreW(PCRYPTUI_SELECTSTORE_INFO_W info)
1529 {
1530     struct SelectStoreInfo selectInfo = { info, NULL };
1531
1532     TRACE("(%p)\n", info);
1533
1534     if (info->dwSize != sizeof(CRYPTUI_SELECTSTORE_INFO_W))
1535     {
1536         WARN("unexpected size %d\n", info->dwSize);
1537         SetLastError(E_INVALIDARG);
1538         return NULL;
1539     }
1540     DialogBoxParamW(hInstance, MAKEINTRESOURCEW(IDD_SELECT_STORE), info->parent,
1541      select_store_dlg_proc, (LPARAM)&selectInfo);
1542     return selectInfo.store;
1543 }
1544
1545 /***********************************************************************
1546  *              CryptUIDlgSelectStoreA (CRYPTUI.@)
1547  */
1548 HCERTSTORE WINAPI CryptUIDlgSelectStoreA(PCRYPTUI_SELECTSTORE_INFO_A info)
1549 {
1550     CRYPTUI_SELECTSTORE_INFO_W infoW;
1551     HCERTSTORE ret;
1552     int len;
1553
1554     TRACE("(%p)\n", info);
1555
1556     if (info->dwSize != sizeof(CRYPTUI_SELECTSTORE_INFO_A))
1557     {
1558         WARN("unexpected size %d\n", info->dwSize);
1559         SetLastError(E_INVALIDARG);
1560         return NULL;
1561     }
1562     memcpy(&infoW, &info, sizeof(info));
1563     if (info->pszTitle)
1564     {
1565         len = MultiByteToWideChar(CP_ACP, 0, info->pszTitle, -1, NULL, 0);
1566         infoW.pwszTitle = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
1567         MultiByteToWideChar(CP_ACP, 0, info->pszTitle, -1, infoW.pwszTitle,
1568          len);
1569     }
1570     if (info->pszText)
1571     {
1572         len = MultiByteToWideChar(CP_ACP, 0, info->pszText, -1, NULL, 0);
1573         infoW.pwszText = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
1574         MultiByteToWideChar(CP_ACP, 0, info->pszText, -1, infoW.pwszText, len);
1575     }
1576     ret = CryptUIDlgSelectStoreW(&infoW);
1577     HeapFree(GetProcessHeap(), 0, infoW.pwszText);
1578     HeapFree(GetProcessHeap(), 0, infoW.pwszTitle);
1579     return ret;
1580 }
1581
1582 /***********************************************************************
1583  *              CryptUIDlgViewCertificateA (CRYPTUI.@)
1584  */
1585 BOOL WINAPI CryptUIDlgViewCertificateA(
1586  PCCRYPTUI_VIEWCERTIFICATE_STRUCTA pCertViewInfo, BOOL *pfPropertiesChanged)
1587 {
1588     CRYPTUI_VIEWCERTIFICATE_STRUCTW viewInfo;
1589     LPWSTR title = NULL;
1590     BOOL ret;
1591
1592     TRACE("(%p, %p)\n", pCertViewInfo, pfPropertiesChanged);
1593
1594     memcpy(&viewInfo, pCertViewInfo, sizeof(viewInfo));
1595     if (pCertViewInfo->szTitle)
1596     {
1597         int len = MultiByteToWideChar(CP_ACP, 0, pCertViewInfo->szTitle, -1,
1598          NULL, 0);
1599
1600         title = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
1601         if (title)
1602         {
1603             MultiByteToWideChar(CP_ACP, 0, pCertViewInfo->szTitle, -1, title,
1604              len);
1605             viewInfo.szTitle = title;
1606         }
1607         else
1608         {
1609             ret = FALSE;
1610             goto error;
1611         }
1612     }
1613     if (pCertViewInfo->cPropSheetPages)
1614     {
1615         FIXME("ignoring additional prop sheet pages\n");
1616         viewInfo.cPropSheetPages = 0;
1617     }
1618     ret = CryptUIDlgViewCertificateW(&viewInfo, pfPropertiesChanged);
1619     HeapFree(GetProcessHeap(), 0, title);
1620 error:
1621     return ret;
1622 }
1623
1624 struct ReadStringStruct
1625 {
1626     LPCWSTR buf;
1627     LONG pos;
1628     LONG len;
1629 };
1630
1631 static DWORD CALLBACK read_text_callback(DWORD_PTR dwCookie, LPBYTE buf,
1632  LONG cb, LONG *pcb)
1633 {
1634     struct ReadStringStruct *string = (struct ReadStringStruct *)dwCookie;
1635     LONG cch = min(cb / sizeof(WCHAR), string->len - string->pos);
1636
1637     TRACE("(%p, %p, %d, %p)\n", string, buf, cb, pcb);
1638
1639     memmove(buf, string->buf + string->pos, cch * sizeof(WCHAR));
1640     string->pos += cch;
1641     *pcb = cch * sizeof(WCHAR);
1642     return 0;
1643 }
1644
1645 static void add_unformatted_text_to_control(HWND hwnd, LPCWSTR text, LONG len)
1646 {
1647     struct ReadStringStruct string;
1648     EDITSTREAM editstream;
1649
1650     TRACE("(%p, %s)\n", hwnd, debugstr_wn(text, len));
1651
1652     string.buf = text;
1653     string.pos = 0;
1654     string.len = len;
1655     editstream.dwCookie = (DWORD_PTR)&string;
1656     editstream.dwError = 0;
1657     editstream.pfnCallback = read_text_callback;
1658     SendMessageW(hwnd, EM_STREAMIN, SF_TEXT | SFF_SELECTION | SF_UNICODE,
1659      (LPARAM)&editstream);
1660 }
1661
1662 static void add_string_resource_to_control(HWND hwnd, int id)
1663 {
1664     LPWSTR str;
1665     LONG len;
1666
1667     len = LoadStringW(hInstance, id, (LPWSTR)&str, 0);
1668     add_unformatted_text_to_control(hwnd, str, len);
1669 }
1670
1671 static void add_text_with_paraformat_to_control(HWND hwnd, LPCWSTR text,
1672  LONG len, const PARAFORMAT2 *fmt)
1673 {
1674     add_unformatted_text_to_control(hwnd, text, len);
1675     SendMessageW(hwnd, EM_SETPARAFORMAT, 0, (LPARAM)fmt);
1676 }
1677
1678 static void add_string_resource_with_paraformat_to_control(HWND hwnd, int id,
1679  const PARAFORMAT2 *fmt)
1680 {
1681     LPWSTR str;
1682     LONG len;
1683
1684     len = LoadStringW(hInstance, id, (LPWSTR)&str, 0);
1685     add_text_with_paraformat_to_control(hwnd, str, len, fmt);
1686 }
1687
1688 static LPWSTR get_cert_name_string(PCCERT_CONTEXT pCertContext, DWORD dwType,
1689  DWORD dwFlags)
1690 {
1691     LPWSTR buf = NULL;
1692     DWORD len;
1693
1694     len = CertGetNameStringW(pCertContext, dwType, dwFlags, NULL, NULL, 0);
1695     if (len)
1696     {
1697         buf = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
1698         if (buf)
1699             CertGetNameStringW(pCertContext, dwType, dwFlags, NULL, buf, len);
1700     }
1701     return buf;
1702 }
1703
1704 static void add_cert_string_to_control(HWND hwnd, PCCERT_CONTEXT pCertContext,
1705  DWORD dwType, DWORD dwFlags)
1706 {
1707     LPWSTR name = get_cert_name_string(pCertContext, dwType, dwFlags);
1708
1709     if (name)
1710     {
1711         /* Don't include NULL-terminator in output */
1712         DWORD len = lstrlenW(name);
1713
1714         add_unformatted_text_to_control(hwnd, name, len);
1715         HeapFree(GetProcessHeap(), 0, name);
1716     }
1717 }
1718
1719 static void add_icon_to_control(HWND hwnd, int id)
1720 {
1721     HRESULT hr;
1722     LPRICHEDITOLE richEditOle = NULL;
1723     LPOLEOBJECT object = NULL;
1724     CLSID clsid;
1725     LPOLECACHE oleCache = NULL;
1726     FORMATETC formatEtc;
1727     DWORD conn;
1728     LPDATAOBJECT dataObject = NULL;
1729     HBITMAP bitmap = NULL;
1730     RECT rect;
1731     STGMEDIUM stgm;
1732     LPOLECLIENTSITE clientSite = NULL;
1733     REOBJECT reObject;
1734
1735     TRACE("(%p, %d)\n", hwnd, id);
1736
1737     SendMessageW(hwnd, EM_GETOLEINTERFACE, 0, (LPARAM)&richEditOle);
1738     if (!richEditOle)
1739         goto end;
1740     hr = OleCreateDefaultHandler(&CLSID_NULL, NULL, &IID_IOleObject,
1741      (void**)&object);
1742     if (FAILED(hr))
1743         goto end;
1744     hr = IOleObject_GetUserClassID(object, &clsid);
1745     if (FAILED(hr))
1746         goto end;
1747     hr = IOleObject_QueryInterface(object, &IID_IOleCache, (void**)&oleCache);
1748     if (FAILED(hr))
1749         goto end;
1750     formatEtc.cfFormat = CF_BITMAP;
1751     formatEtc.ptd = NULL;
1752     formatEtc.dwAspect = DVASPECT_CONTENT;
1753     formatEtc.lindex = -1;
1754     formatEtc.tymed = TYMED_GDI;
1755     hr = IOleCache_Cache(oleCache, &formatEtc, 0, &conn);
1756     if (FAILED(hr))
1757         goto end;
1758     hr = IOleObject_QueryInterface(object, &IID_IDataObject,
1759      (void**)&dataObject);
1760     if (FAILED(hr))
1761         goto end;
1762     hr = IRichEditOle_GetClientSite(richEditOle, &clientSite);
1763     if (FAILED(hr))
1764         goto end;
1765     bitmap = LoadImageW(hInstance, MAKEINTRESOURCEW(id), IMAGE_BITMAP, 0, 0,
1766      LR_DEFAULTSIZE | LR_LOADTRANSPARENT);
1767     if (!bitmap)
1768         goto end;
1769     rect.left = rect.top = 0;
1770     rect.right = GetSystemMetrics(SM_CXICON);
1771     rect.bottom = GetSystemMetrics(SM_CYICON);
1772     stgm.tymed = TYMED_GDI;
1773     stgm.u.hBitmap = bitmap;
1774     stgm.pUnkForRelease = NULL;
1775     hr = IDataObject_SetData(dataObject, &formatEtc, &stgm, TRUE);
1776     if (FAILED(hr))
1777         goto end;
1778
1779     reObject.cbStruct = sizeof(reObject);
1780     reObject.cp = REO_CP_SELECTION;
1781     reObject.clsid = clsid;
1782     reObject.poleobj = object;
1783     reObject.pstg = NULL;
1784     reObject.polesite = clientSite;
1785     reObject.sizel.cx = reObject.sizel.cy = 0;
1786     reObject.dvaspect = DVASPECT_CONTENT;
1787     reObject.dwFlags = 0;
1788     reObject.dwUser = 0;
1789
1790     IRichEditOle_InsertObject(richEditOle, &reObject);
1791
1792 end:
1793     if (clientSite)
1794         IOleClientSite_Release(clientSite);
1795     if (dataObject)
1796         IDataObject_Release(dataObject);
1797     if (oleCache)
1798         IOleCache_Release(oleCache);
1799     if (object)
1800         IOleObject_Release(object);
1801     if (richEditOle)
1802         IRichEditOle_Release(richEditOle);
1803 }
1804
1805 #define MY_INDENT 200
1806
1807 static void add_oid_text_to_control(HWND hwnd, char *oid)
1808 {
1809     WCHAR nl = '\n';
1810     PCCRYPT_OID_INFO oidInfo = CryptFindOIDInfo(CRYPT_OID_INFO_OID_KEY, oid, 0);
1811     PARAFORMAT2 parFmt;
1812
1813     parFmt.cbSize = sizeof(parFmt);
1814     parFmt.dwMask = PFM_STARTINDENT;
1815     parFmt.dxStartIndent = MY_INDENT * 3;
1816     if (oidInfo)
1817     {
1818         add_text_with_paraformat_to_control(hwnd, oidInfo->pwszName,
1819          lstrlenW(oidInfo->pwszName), &parFmt);
1820         add_unformatted_text_to_control(hwnd, &nl, 1);
1821     }
1822 }
1823
1824 struct OIDToString
1825 {
1826     LPCSTR oid;
1827     int    id;
1828 };
1829
1830 /* The following list MUST be lexicographically sorted by OID */
1831 static struct OIDToString oidMap[] = {
1832  /* 1.3.6.1.4.1.311.10.3.1 */
1833  { szOID_KP_CTL_USAGE_SIGNING, IDS_PURPOSE_CTL_USAGE_SIGNING },
1834  /* 1.3.6.1.4.1.311.10.3.4 */
1835  { szOID_KP_EFS, IDS_PURPOSE_EFS },
1836  /* 1.3.6.1.4.1.311.10.3.4.1 */
1837  { szOID_EFS_RECOVERY, IDS_PURPOSE_EFS_RECOVERY },
1838  /* 1.3.6.1.4.1.311.10.3.5 */
1839  { szOID_WHQL_CRYPTO, IDS_PURPOSE_WHQL },
1840  /* 1.3.6.1.4.1.311.10.3.6 */
1841  { szOID_NT5_CRYPTO, IDS_PURPOSE_NT5 },
1842  /* 1.3.6.1.4.1.311.10.3.7 */
1843  { szOID_OEM_WHQL_CRYPTO, IDS_PURPOSE_OEM_WHQL },
1844  /* 1.3.6.1.4.1.311.10.3.8 */
1845  { szOID_EMBEDDED_NT_CRYPTO, IDS_PURPOSE_EMBEDDED_NT },
1846  /* 1.3.6.1.4.1.311.10.3.9 */
1847  { szOID_ROOT_LIST_SIGNER, IDS_PURPOSE_ROOT_LIST_SIGNER },
1848  /* 1.3.6.1.4.1.311.10.3.10 */
1849  { szOID_KP_QUALIFIED_SUBORDINATION, IDS_PURPOSE_QUALIFIED_SUBORDINATION },
1850  /* 1.3.6.1.4.1.311.10.3.11 */
1851  { szOID_KP_KEY_RECOVERY, IDS_PURPOSE_KEY_RECOVERY },
1852  /* 1.3.6.1.4.1.311.10.3.12 */
1853  { szOID_KP_DOCUMENT_SIGNING, IDS_PURPOSE_DOCUMENT_SIGNING },
1854  /* 1.3.6.1.4.1.311.10.3.13 */
1855  { szOID_KP_LIFETIME_SIGNING, IDS_PURPOSE_LIFETIME_SIGNING },
1856  /* 1.3.6.1.4.1.311.10.5.1 */
1857  { szOID_DRM, IDS_PURPOSE_DRM },
1858  /* 1.3.6.1.4.1.311.10.6.1 */
1859  { szOID_LICENSES, IDS_PURPOSE_LICENSES },
1860  /* 1.3.6.1.4.1.311.10.6.2 */
1861  { szOID_LICENSE_SERVER, IDS_PURPOSE_LICENSE_SERVER },
1862  /* 1.3.6.1.4.1.311.20.2.1 */
1863  { szOID_ENROLLMENT_AGENT, IDS_PURPOSE_ENROLLMENT_AGENT },
1864  /* 1.3.6.1.4.1.311.20.2.2 */
1865  { szOID_KP_SMARTCARD_LOGON, IDS_PURPOSE_SMARTCARD_LOGON },
1866  /* 1.3.6.1.4.1.311.21.5 */
1867  { szOID_KP_CA_EXCHANGE, IDS_PURPOSE_CA_EXCHANGE },
1868  /* 1.3.6.1.4.1.311.21.6 */
1869  { szOID_KP_KEY_RECOVERY_AGENT, IDS_PURPOSE_KEY_RECOVERY_AGENT },
1870  /* 1.3.6.1.4.1.311.21.19 */
1871  { szOID_DS_EMAIL_REPLICATION, IDS_PURPOSE_DS_EMAIL_REPLICATION },
1872  /* 1.3.6.1.5.5.7.3.1 */
1873  { szOID_PKIX_KP_SERVER_AUTH, IDS_PURPOSE_SERVER_AUTH },
1874  /* 1.3.6.1.5.5.7.3.2 */
1875  { szOID_PKIX_KP_CLIENT_AUTH, IDS_PURPOSE_CLIENT_AUTH },
1876  /* 1.3.6.1.5.5.7.3.3 */
1877  { szOID_PKIX_KP_CODE_SIGNING, IDS_PURPOSE_CODE_SIGNING },
1878  /* 1.3.6.1.5.5.7.3.4 */
1879  { szOID_PKIX_KP_EMAIL_PROTECTION, IDS_PURPOSE_EMAIL_PROTECTION },
1880  /* 1.3.6.1.5.5.7.3.5 */
1881  { szOID_PKIX_KP_IPSEC_END_SYSTEM, IDS_PURPOSE_IPSEC },
1882  /* 1.3.6.1.5.5.7.3.6 */
1883  { szOID_PKIX_KP_IPSEC_TUNNEL, IDS_PURPOSE_IPSEC },
1884  /* 1.3.6.1.5.5.7.3.7 */
1885  { szOID_PKIX_KP_IPSEC_USER, IDS_PURPOSE_IPSEC },
1886  /* 1.3.6.1.5.5.7.3.8 */
1887  { szOID_PKIX_KP_TIMESTAMP_SIGNING, IDS_PURPOSE_TIMESTAMP_SIGNING },
1888 };
1889
1890 static struct OIDToString *findSupportedOID(LPCSTR oid)
1891 {
1892     int indexHigh = sizeof(oidMap) / sizeof(oidMap[0]) - 1, indexLow = 0, i;
1893     struct OIDToString *ret = NULL;
1894
1895     for (i = (indexLow + indexHigh) / 2; !ret && indexLow <= indexHigh;
1896      i = (indexLow + indexHigh) / 2)
1897     {
1898         int cmp;
1899
1900         cmp = strcmp(oid, oidMap[i].oid);
1901         if (!cmp)
1902             ret = &oidMap[i];
1903         else if (cmp > 0)
1904             indexLow = i + 1;
1905         else
1906             indexHigh = i - 1;
1907     }
1908     return ret;
1909 }
1910
1911 static void add_local_oid_text_to_control(HWND text, LPCSTR oid)
1912 {
1913     struct OIDToString *entry;
1914     WCHAR nl = '\n';
1915     PARAFORMAT2 parFmt;
1916
1917     parFmt.cbSize = sizeof(parFmt);
1918     parFmt.dwMask = PFM_STARTINDENT;
1919     parFmt.dxStartIndent = MY_INDENT * 3;
1920     if ((entry = findSupportedOID(oid)))
1921     {
1922         WCHAR *str, *linebreak, *ptr;
1923         BOOL multiline = FALSE;
1924         int len;
1925
1926         len = LoadStringW(hInstance, entry->id, (LPWSTR)&str, 0);
1927         ptr = str;
1928         do {
1929             if ((linebreak = memchrW(ptr, '\n', len)))
1930             {
1931                 WCHAR copy[MAX_STRING_LEN];
1932
1933                 multiline = TRUE;
1934                 /* The source string contains a newline, which the richedit
1935                  * control won't find since it's interpreted as a paragraph
1936                  * break.  Therefore copy up to the newline.  lstrcpynW always
1937                  * NULL-terminates, so pass one more than the length of the
1938                  * source line so the copy includes the entire line and the
1939                  * NULL-terminator.
1940                  */
1941                 lstrcpynW(copy, ptr, linebreak - ptr + 1);
1942                 add_text_with_paraformat_to_control(text, copy,
1943                  linebreak - ptr, &parFmt);
1944                 ptr = linebreak + 1;
1945                 add_unformatted_text_to_control(text, &nl, 1);
1946             }
1947             else if (multiline && *ptr)
1948             {
1949                 /* Add the last line */
1950                 add_text_with_paraformat_to_control(text, ptr,
1951                  len - (ptr - str), &parFmt);
1952                 add_unformatted_text_to_control(text, &nl, 1);
1953             }
1954         } while (linebreak);
1955         if (!multiline)
1956         {
1957             add_text_with_paraformat_to_control(text, str, len, &parFmt);
1958             add_unformatted_text_to_control(text, &nl, 1);
1959         }
1960     }
1961     else
1962     {
1963         WCHAR *oidW = HeapAlloc(GetProcessHeap(), 0,
1964          (strlen(oid) + 1) * sizeof(WCHAR));
1965
1966         if (oidW)
1967         {
1968             LPCSTR src;
1969             WCHAR *dst;
1970
1971             for (src = oid, dst = oidW; *src; src++, dst++)
1972                 *dst = *src;
1973             *dst = 0;
1974             add_text_with_paraformat_to_control(text, oidW, lstrlenW(oidW),
1975              &parFmt);
1976             add_unformatted_text_to_control(text, &nl, 1);
1977             HeapFree(GetProcessHeap(), 0, oidW);
1978         }
1979     }
1980 }
1981
1982 static void display_app_usages(HWND text, PCCERT_CONTEXT cert,
1983  BOOL *anyUsageAdded)
1984 {
1985     static char any_app_policy[] = szOID_ANY_APPLICATION_POLICY;
1986     WCHAR nl = '\n';
1987     CHARFORMATW charFmt;
1988     PCERT_EXTENSION policyExt;
1989     if (!*anyUsageAdded)
1990     {
1991         PARAFORMAT2 parFmt;
1992
1993         parFmt.cbSize = sizeof(parFmt);
1994         parFmt.dwMask = PFM_STARTINDENT;
1995         parFmt.dxStartIndent = MY_INDENT;
1996         add_string_resource_with_paraformat_to_control(text,
1997          IDS_CERT_INFO_PURPOSES, &parFmt);
1998         add_unformatted_text_to_control(text, &nl, 1);
1999         *anyUsageAdded = TRUE;
2000     }
2001     memset(&charFmt, 0, sizeof(charFmt));
2002     charFmt.cbSize = sizeof(charFmt);
2003     charFmt.dwMask = CFM_BOLD;
2004     charFmt.dwEffects = 0;
2005     SendMessageW(text, EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&charFmt);
2006     if ((policyExt = CertFindExtension(szOID_APPLICATION_CERT_POLICIES,
2007      cert->pCertInfo->cExtension, cert->pCertInfo->rgExtension)))
2008     {
2009         CERT_POLICIES_INFO *policies;
2010         DWORD size;
2011
2012         if (CryptDecodeObjectEx(X509_ASN_ENCODING, X509_CERT_POLICIES,
2013          policyExt->Value.pbData, policyExt->Value.cbData,
2014          CRYPT_DECODE_ALLOC_FLAG, NULL, &policies, &size))
2015         {
2016             DWORD i;
2017
2018             for (i = 0; i < policies->cPolicyInfo; i++)
2019             {
2020                 DWORD j;
2021
2022                 for (j = 0; j < policies->rgPolicyInfo[i].cPolicyQualifier; j++)
2023                     add_local_oid_text_to_control(text,
2024                      policies->rgPolicyInfo[i].rgPolicyQualifier[j].
2025                      pszPolicyQualifierId);
2026             }
2027             LocalFree(policies);
2028         }
2029     }
2030     else
2031         add_oid_text_to_control(text, any_app_policy);
2032 }
2033
2034 static BOOL display_cert_usages(HWND text, PCCERT_CONTEXT cert,
2035  BOOL *anyUsageAdded)
2036 {
2037     WCHAR nl = '\n';
2038     DWORD size;
2039     BOOL badUsages = FALSE;
2040
2041     if (CertGetEnhancedKeyUsage(cert, 0, NULL, &size))
2042     {
2043         CHARFORMATW charFmt;
2044         static char any_cert_policy[] = szOID_ANY_CERT_POLICY;
2045         PCERT_ENHKEY_USAGE usage = HeapAlloc(GetProcessHeap(), 0, size);
2046
2047         if (usage)
2048         {
2049             if (CertGetEnhancedKeyUsage(cert, 0, usage, &size))
2050             {
2051                 DWORD i;
2052
2053                 if (!*anyUsageAdded)
2054                 {
2055                     PARAFORMAT2 parFmt;
2056
2057                     parFmt.cbSize = sizeof(parFmt);
2058                     parFmt.dwMask = PFM_STARTINDENT;
2059                     parFmt.dxStartIndent = MY_INDENT;
2060                     add_string_resource_with_paraformat_to_control(text,
2061                      IDS_CERT_INFO_PURPOSES, &parFmt);
2062                     add_unformatted_text_to_control(text, &nl, 1);
2063                     *anyUsageAdded = TRUE;
2064                 }
2065                 memset(&charFmt, 0, sizeof(charFmt));
2066                 charFmt.cbSize = sizeof(charFmt);
2067                 charFmt.dwMask = CFM_BOLD;
2068                 charFmt.dwEffects = 0;
2069                 SendMessageW(text, EM_SETCHARFORMAT, SCF_SELECTION,
2070                  (LPARAM)&charFmt);
2071                 if (!usage->cUsageIdentifier)
2072                     add_oid_text_to_control(text, any_cert_policy);
2073                 else
2074                     for (i = 0; i < usage->cUsageIdentifier; i++)
2075                         add_local_oid_text_to_control(text,
2076                          usage->rgpszUsageIdentifier[i]);
2077             }
2078             else
2079                 badUsages = TRUE;
2080             HeapFree(GetProcessHeap(), 0, usage);
2081         }
2082         else
2083             badUsages = TRUE;
2084     }
2085     else
2086         badUsages = TRUE;
2087     return badUsages;
2088 }
2089
2090 static void set_policy_text(HWND text,
2091  PCCRYPTUI_VIEWCERTIFICATE_STRUCTW pCertViewInfo)
2092 {
2093     BOOL includeCertUsages = FALSE, includeAppUsages = FALSE;
2094     BOOL badUsages = FALSE, anyUsageAdded = FALSE;
2095
2096     if (pCertViewInfo->cPurposes)
2097     {
2098         DWORD i;
2099
2100         for (i = 0; i < pCertViewInfo->cPurposes; i++)
2101         {
2102             if (!strcmp(pCertViewInfo->rgszPurposes[i], szOID_ANY_CERT_POLICY))
2103                 includeCertUsages = TRUE;
2104             else if (!strcmp(pCertViewInfo->rgszPurposes[i],
2105              szOID_ANY_APPLICATION_POLICY))
2106                 includeAppUsages = TRUE;
2107             else
2108                 badUsages = TRUE;
2109         }
2110     }
2111     else
2112         includeAppUsages = includeCertUsages = TRUE;
2113     if (includeAppUsages)
2114         display_app_usages(text, pCertViewInfo->pCertContext, &anyUsageAdded);
2115     if (includeCertUsages)
2116         badUsages = display_cert_usages(text, pCertViewInfo->pCertContext,
2117          &anyUsageAdded);
2118     if (badUsages)
2119     {
2120         PARAFORMAT2 parFmt;
2121
2122         parFmt.cbSize = sizeof(parFmt);
2123         parFmt.dwMask = PFM_STARTINDENT;
2124         parFmt.dxStartIndent = MY_INDENT;
2125         add_string_resource_with_paraformat_to_control(text,
2126          IDS_CERT_INFO_BAD_PURPOSES, &parFmt);
2127     }
2128 }
2129
2130 static CRYPT_OBJID_BLOB *find_policy_qualifier(CERT_POLICIES_INFO *policies,
2131  LPCSTR policyOid)
2132 {
2133     CRYPT_OBJID_BLOB *ret = NULL;
2134     DWORD i;
2135
2136     for (i = 0; !ret && i < policies->cPolicyInfo; i++)
2137     {
2138         DWORD j;
2139
2140         for (j = 0; !ret && j < policies->rgPolicyInfo[i].cPolicyQualifier; j++)
2141             if (!strcmp(policies->rgPolicyInfo[i].rgPolicyQualifier[j].
2142              pszPolicyQualifierId, policyOid))
2143                 ret = &policies->rgPolicyInfo[i].rgPolicyQualifier[j].
2144                  Qualifier;
2145     }
2146     return ret;
2147 }
2148
2149 static WCHAR *get_cps_str_from_qualifier(CRYPT_OBJID_BLOB *qualifier)
2150 {
2151     LPWSTR qualifierStr = NULL;
2152     CERT_NAME_VALUE *qualifierValue;
2153     DWORD size;
2154
2155     if (CryptDecodeObjectEx(X509_ASN_ENCODING, X509_NAME_VALUE,
2156      qualifier->pbData, qualifier->cbData, CRYPT_DECODE_ALLOC_FLAG, NULL,
2157      &qualifierValue, &size))
2158     {
2159         size = CertRDNValueToStrW(qualifierValue->dwValueType,
2160          &qualifierValue->Value, NULL, 0);
2161         qualifierStr = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
2162         if (qualifierStr)
2163             CertRDNValueToStrW(qualifierValue->dwValueType,
2164              &qualifierValue->Value, qualifierStr, size);
2165         LocalFree(qualifierValue);
2166     }
2167     return qualifierStr;
2168 }
2169
2170 static WCHAR *get_user_notice_from_qualifier(CRYPT_OBJID_BLOB *qualifier)
2171 {
2172     LPWSTR str = NULL;
2173     CERT_POLICY_QUALIFIER_USER_NOTICE *qualifierValue;
2174     DWORD size;
2175
2176     if (CryptDecodeObjectEx(X509_ASN_ENCODING,
2177      X509_PKIX_POLICY_QUALIFIER_USERNOTICE,
2178      qualifier->pbData, qualifier->cbData, CRYPT_DECODE_ALLOC_FLAG, NULL,
2179      &qualifierValue, &size))
2180     {
2181         str = HeapAlloc(GetProcessHeap(), 0,
2182          (strlenW(qualifierValue->pszDisplayText) + 1) * sizeof(WCHAR));
2183         if (str)
2184             strcpyW(str, qualifierValue->pszDisplayText);
2185         LocalFree(qualifierValue);
2186     }
2187     return str;
2188 }
2189
2190 struct IssuerStatement
2191 {
2192     LPWSTR cps;
2193     LPWSTR userNotice;
2194 };
2195
2196 static void set_issuer_statement(HWND hwnd,
2197  PCCRYPTUI_VIEWCERTIFICATE_STRUCTW pCertViewInfo)
2198 {
2199     PCERT_EXTENSION policyExt;
2200
2201     if (!(pCertViewInfo->dwFlags & CRYPTUI_DISABLE_ISSUERSTATEMENT) &&
2202      (policyExt = CertFindExtension(szOID_CERT_POLICIES,
2203      pCertViewInfo->pCertContext->pCertInfo->cExtension,
2204      pCertViewInfo->pCertContext->pCertInfo->rgExtension)))
2205     {
2206         CERT_POLICIES_INFO *policies;
2207         DWORD size;
2208
2209         if (CryptDecodeObjectEx(X509_ASN_ENCODING, policyExt->pszObjId,
2210          policyExt->Value.pbData, policyExt->Value.cbData,
2211          CRYPT_DECODE_ALLOC_FLAG, NULL, &policies, &size))
2212         {
2213             CRYPT_OBJID_BLOB *qualifier;
2214             LPWSTR cps = NULL, userNotice = NULL;
2215
2216             if ((qualifier = find_policy_qualifier(policies,
2217              szOID_PKIX_POLICY_QUALIFIER_CPS)))
2218                 cps = get_cps_str_from_qualifier(qualifier);
2219             if ((qualifier = find_policy_qualifier(policies,
2220              szOID_PKIX_POLICY_QUALIFIER_USERNOTICE)))
2221                 userNotice = get_user_notice_from_qualifier(qualifier);
2222             if (cps || userNotice)
2223             {
2224                 struct IssuerStatement *issuerStatement =
2225                  HeapAlloc(GetProcessHeap(), 0, sizeof(struct IssuerStatement));
2226
2227                 if (issuerStatement)
2228                 {
2229                     issuerStatement->cps = cps;
2230                     issuerStatement->userNotice = userNotice;
2231                     EnableWindow(GetDlgItem(hwnd, IDC_ISSUERSTATEMENT), TRUE);
2232                     SetWindowLongPtrW(hwnd, DWLP_USER,
2233                      (ULONG_PTR)issuerStatement);
2234                 }
2235             }
2236             LocalFree(policies);
2237         }
2238     }
2239 }
2240
2241 static void set_cert_info(HWND hwnd,
2242  PCCRYPTUI_VIEWCERTIFICATE_STRUCTW pCertViewInfo)
2243 {
2244     CHARFORMATW charFmt;
2245     PARAFORMAT2 parFmt;
2246     HWND icon = GetDlgItem(hwnd, IDC_CERTIFICATE_ICON);
2247     HWND text = GetDlgItem(hwnd, IDC_CERTIFICATE_INFO);
2248     CRYPT_PROVIDER_SGNR *provSigner = WTHelperGetProvSignerFromChain(
2249      (CRYPT_PROVIDER_DATA *)pCertViewInfo->u.pCryptProviderData,
2250      pCertViewInfo->idxSigner, pCertViewInfo->fCounterSigner,
2251      pCertViewInfo->idxCounterSigner);
2252     CRYPT_PROVIDER_CERT *root =
2253      &provSigner->pasCertChain[provSigner->csCertChain - 1];
2254
2255     if (!provSigner->pChainContext ||
2256      (provSigner->pChainContext->TrustStatus.dwErrorStatus &
2257      CERT_TRUST_IS_PARTIAL_CHAIN))
2258         add_icon_to_control(icon, IDB_CERT_WARNING);
2259     else if (!root->fTrustedRoot)
2260         add_icon_to_control(icon, IDB_CERT_ERROR);
2261     else
2262         add_icon_to_control(icon, IDB_CERT);
2263
2264     memset(&charFmt, 0, sizeof(charFmt));
2265     charFmt.cbSize = sizeof(charFmt);
2266     charFmt.dwMask = CFM_BOLD;
2267     charFmt.dwEffects = CFE_BOLD;
2268     SendMessageW(text, EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&charFmt);
2269     /* FIXME: vertically center text */
2270     parFmt.cbSize = sizeof(parFmt);
2271     parFmt.dwMask = PFM_STARTINDENT;
2272     parFmt.dxStartIndent = MY_INDENT;
2273     add_string_resource_with_paraformat_to_control(text,
2274      IDS_CERTIFICATEINFORMATION, &parFmt);
2275
2276     text = GetDlgItem(hwnd, IDC_CERTIFICATE_STATUS);
2277     SendMessageW(text, EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&charFmt);
2278     if (provSigner->dwError == TRUST_E_CERT_SIGNATURE)
2279         add_string_resource_with_paraformat_to_control(text,
2280          IDS_CERT_INFO_BAD_SIG, &parFmt);
2281     else if (!provSigner->pChainContext ||
2282      (provSigner->pChainContext->TrustStatus.dwErrorStatus &
2283      CERT_TRUST_IS_PARTIAL_CHAIN))
2284         add_string_resource_with_paraformat_to_control(text,
2285          IDS_CERT_INFO_PARTIAL_CHAIN, &parFmt);
2286     else if (!root->fTrustedRoot)
2287     {
2288         if (provSigner->csCertChain == 1 && root->fSelfSigned)
2289             add_string_resource_with_paraformat_to_control(text,
2290              IDS_CERT_INFO_UNTRUSTED_CA, &parFmt);
2291         else
2292             add_string_resource_with_paraformat_to_control(text,
2293              IDS_CERT_INFO_UNTRUSTED_ROOT, &parFmt);
2294     }
2295     else
2296     {
2297         set_policy_text(text, pCertViewInfo);
2298         set_issuer_statement(hwnd, pCertViewInfo);
2299     }
2300 }
2301
2302 static void set_cert_name_string(HWND hwnd, PCCERT_CONTEXT cert,
2303  DWORD nameFlags, int heading)
2304 {
2305     WCHAR nl = '\n';
2306     HWND text = GetDlgItem(hwnd, IDC_CERTIFICATE_NAMES);
2307     CHARFORMATW charFmt;
2308     PARAFORMAT2 parFmt;
2309
2310     memset(&charFmt, 0, sizeof(charFmt));
2311     charFmt.cbSize = sizeof(charFmt);
2312     charFmt.dwMask = CFM_BOLD;
2313     charFmt.dwEffects = CFE_BOLD;
2314     SendMessageW(text, EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&charFmt);
2315     parFmt.cbSize = sizeof(parFmt);
2316     parFmt.dwMask = PFM_STARTINDENT;
2317     parFmt.dxStartIndent = MY_INDENT * 3;
2318     add_string_resource_with_paraformat_to_control(text, heading, &parFmt);
2319     charFmt.dwEffects = 0;
2320     SendMessageW(text, EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&charFmt);
2321     add_cert_string_to_control(text, cert, CERT_NAME_SIMPLE_DISPLAY_TYPE,
2322      nameFlags);
2323     add_unformatted_text_to_control(text, &nl, 1);
2324     add_unformatted_text_to_control(text, &nl, 1);
2325     add_unformatted_text_to_control(text, &nl, 1);
2326
2327 }
2328
2329 static void add_date_string_to_control(HWND hwnd, const FILETIME *fileTime)
2330 {
2331     WCHAR dateFmt[80]; /* sufficient for all versions of LOCALE_SSHORTDATE */
2332     WCHAR date[80];
2333     SYSTEMTIME sysTime;
2334
2335     GetLocaleInfoW(LOCALE_SYSTEM_DEFAULT, LOCALE_SSHORTDATE, dateFmt,
2336      sizeof(dateFmt) / sizeof(dateFmt[0]));
2337     FileTimeToSystemTime(fileTime, &sysTime);
2338     GetDateFormatW(LOCALE_SYSTEM_DEFAULT, 0, &sysTime, dateFmt, date,
2339      sizeof(date) / sizeof(date[0]));
2340     add_unformatted_text_to_control(hwnd, date, lstrlenW(date));
2341 }
2342
2343 static void set_cert_validity_period(HWND hwnd, PCCERT_CONTEXT cert)
2344 {
2345     WCHAR nl = '\n';
2346     HWND text = GetDlgItem(hwnd, IDC_CERTIFICATE_NAMES);
2347     CHARFORMATW charFmt;
2348     PARAFORMAT2 parFmt;
2349
2350     memset(&charFmt, 0, sizeof(charFmt));
2351     charFmt.cbSize = sizeof(charFmt);
2352     charFmt.dwMask = CFM_BOLD;
2353     charFmt.dwEffects = CFE_BOLD;
2354     SendMessageW(text, EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&charFmt);
2355     parFmt.cbSize = sizeof(parFmt);
2356     parFmt.dwMask = PFM_STARTINDENT;
2357     parFmt.dxStartIndent = MY_INDENT * 3;
2358     add_string_resource_with_paraformat_to_control(text, IDS_VALID_FROM,
2359      &parFmt);
2360     charFmt.dwEffects = 0;
2361     SendMessageW(text, EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&charFmt);
2362     add_date_string_to_control(text, &cert->pCertInfo->NotBefore);
2363     charFmt.dwEffects = CFE_BOLD;
2364     SendMessageW(text, EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&charFmt);
2365     add_string_resource_to_control(text, IDS_VALID_TO);
2366     charFmt.dwEffects = 0;
2367     SendMessageW(text, EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&charFmt);
2368     add_date_string_to_control(text, &cert->pCertInfo->NotAfter);
2369     add_unformatted_text_to_control(text, &nl, 1);
2370 }
2371
2372 static void set_general_info(HWND hwnd,
2373  PCCRYPTUI_VIEWCERTIFICATE_STRUCTW pCertViewInfo)
2374 {
2375     set_cert_info(hwnd, pCertViewInfo);
2376     set_cert_name_string(hwnd, pCertViewInfo->pCertContext, 0,
2377      IDS_SUBJECT_HEADING);
2378     set_cert_name_string(hwnd, pCertViewInfo->pCertContext,
2379      CERT_NAME_ISSUER_FLAG, IDS_ISSUER_HEADING);
2380     set_cert_validity_period(hwnd, pCertViewInfo->pCertContext);
2381 }
2382
2383 static LRESULT CALLBACK user_notice_dlg_proc(HWND hwnd, UINT msg, WPARAM wp,
2384  LPARAM lp)
2385 {
2386     LRESULT ret = 0;
2387     HWND text;
2388     struct IssuerStatement *issuerStatement;
2389
2390     switch (msg)
2391     {
2392     case WM_INITDIALOG:
2393         text = GetDlgItem(hwnd, IDC_USERNOTICE);
2394         issuerStatement = (struct IssuerStatement *)lp;
2395         add_unformatted_text_to_control(text, issuerStatement->userNotice,
2396          strlenW(issuerStatement->userNotice));
2397         if (issuerStatement->cps)
2398             SetWindowLongPtrW(hwnd, DWLP_USER, (LPARAM)issuerStatement->cps);
2399         else
2400             EnableWindow(GetDlgItem(hwnd, IDC_CPS), FALSE);
2401         break;
2402     case WM_COMMAND:
2403         switch (wp)
2404         {
2405         case IDOK:
2406             EndDialog(hwnd, IDOK);
2407             ret = TRUE;
2408             break;
2409         case IDC_CPS:
2410         {
2411             IBindCtx *bctx = NULL;
2412             LPWSTR cps;
2413
2414             CreateBindCtx(0, &bctx);
2415             cps = (LPWSTR)GetWindowLongPtrW(hwnd, DWLP_USER);
2416             HlinkSimpleNavigateToString(cps, NULL, NULL, NULL, bctx, NULL,
2417              HLNF_OPENINNEWWINDOW, 0);
2418             IBindCtx_Release(bctx);
2419             break;
2420         }
2421         }
2422     }
2423     return ret;
2424 }
2425
2426 static void show_user_notice(HWND hwnd, struct IssuerStatement *issuerStatement)
2427 {
2428     DialogBoxParamW(hInstance, MAKEINTRESOURCEW(IDD_USERNOTICE), hwnd,
2429      user_notice_dlg_proc, (LPARAM)issuerStatement);
2430 }
2431
2432 static LRESULT CALLBACK general_dlg_proc(HWND hwnd, UINT msg, WPARAM wp,
2433  LPARAM lp)
2434 {
2435     PROPSHEETPAGEW *page;
2436     PCCRYPTUI_VIEWCERTIFICATE_STRUCTW pCertViewInfo;
2437
2438     TRACE("(%p, %08x, %08lx, %08lx)\n", hwnd, msg, wp, lp);
2439
2440     switch (msg)
2441     {
2442     case WM_INITDIALOG:
2443         page = (PROPSHEETPAGEW *)lp;
2444         pCertViewInfo = (PCCRYPTUI_VIEWCERTIFICATE_STRUCTW)page->lParam;
2445         if (pCertViewInfo->dwFlags & CRYPTUI_DISABLE_ADDTOSTORE)
2446             ShowWindow(GetDlgItem(hwnd, IDC_ADDTOSTORE), FALSE);
2447         EnableWindow(GetDlgItem(hwnd, IDC_ISSUERSTATEMENT), FALSE);
2448         set_general_info(hwnd, pCertViewInfo);
2449         break;
2450     case WM_COMMAND:
2451         switch (wp)
2452         {
2453         case IDC_ADDTOSTORE:
2454             CryptUIWizImport(0, hwnd, NULL, NULL, NULL);
2455             break;
2456         case IDC_ISSUERSTATEMENT:
2457         {
2458             struct IssuerStatement *issuerStatement =
2459              (struct IssuerStatement *)GetWindowLongPtrW(hwnd, DWLP_USER);
2460
2461             if (issuerStatement)
2462             {
2463                 if (issuerStatement->userNotice)
2464                     show_user_notice(hwnd, issuerStatement);
2465                 else if (issuerStatement->cps)
2466                 {
2467                     IBindCtx *bctx = NULL;
2468
2469                     CreateBindCtx(0, &bctx);
2470                     HlinkSimpleNavigateToString(issuerStatement->cps, NULL,
2471                      NULL, NULL, bctx, NULL, HLNF_OPENINNEWWINDOW, 0);
2472                     IBindCtx_Release(bctx);
2473                 }
2474             }
2475             break;
2476         }
2477         }
2478         break;
2479     }
2480     return 0;
2481 }
2482
2483 static UINT CALLBACK general_callback_proc(HWND hwnd, UINT msg,
2484  PROPSHEETPAGEW *page)
2485 {
2486     struct IssuerStatement *issuerStatement;
2487
2488     switch (msg)
2489     {
2490     case PSPCB_RELEASE:
2491         issuerStatement =
2492          (struct IssuerStatement *)GetWindowLongPtrW(hwnd, DWLP_USER);
2493         if (issuerStatement)
2494         {
2495             HeapFree(GetProcessHeap(), 0, issuerStatement->cps);
2496             HeapFree(GetProcessHeap(), 0, issuerStatement->userNotice);
2497             HeapFree(GetProcessHeap(), 0, issuerStatement);
2498         }
2499         break;
2500     }
2501     return 1;
2502 }
2503
2504 static void init_general_page(PCCRYPTUI_VIEWCERTIFICATE_STRUCTW pCertViewInfo,
2505  PROPSHEETPAGEW *page)
2506 {
2507     memset(page, 0, sizeof(PROPSHEETPAGEW));
2508     page->dwSize = sizeof(PROPSHEETPAGEW);
2509     page->dwFlags = PSP_USECALLBACK;
2510     page->pfnCallback = general_callback_proc;
2511     page->hInstance = hInstance;
2512     page->u.pszTemplate = MAKEINTRESOURCEW(IDD_GENERAL);
2513     page->pfnDlgProc = general_dlg_proc;
2514     page->lParam = (LPARAM)pCertViewInfo;
2515 }
2516
2517 typedef WCHAR * (*field_format_func)(PCCERT_CONTEXT cert);
2518
2519 static WCHAR *field_format_version(PCCERT_CONTEXT cert)
2520 {
2521     static const WCHAR fmt[] = { 'V','%','d',0 };
2522     WCHAR *buf = HeapAlloc(GetProcessHeap(), 0, 12 * sizeof(WCHAR));
2523
2524     if (buf)
2525         sprintfW(buf, fmt, cert->pCertInfo->dwVersion);
2526     return buf;
2527 }
2528
2529 static WCHAR *format_hex_string(void *pb, DWORD cb)
2530 {
2531     WCHAR *buf = HeapAlloc(GetProcessHeap(), 0, (cb * 3 + 1) * sizeof(WCHAR));
2532
2533     if (buf)
2534     {
2535         static const WCHAR fmt[] = { '%','0','2','x',' ',0 };
2536         DWORD i;
2537         WCHAR *ptr;
2538
2539         for (i = 0, ptr = buf; i < cb; i++, ptr += 3)
2540             sprintfW(ptr, fmt, ((BYTE *)pb)[i]);
2541     }
2542     return buf;
2543 }
2544
2545 static WCHAR *field_format_serial_number(PCCERT_CONTEXT cert)
2546 {
2547     return format_hex_string(cert->pCertInfo->SerialNumber.pbData,
2548      cert->pCertInfo->SerialNumber.cbData);
2549 }
2550
2551 static WCHAR *field_format_issuer(PCCERT_CONTEXT cert)
2552 {
2553     return get_cert_name_string(cert, CERT_NAME_SIMPLE_DISPLAY_TYPE,
2554      CERT_NAME_ISSUER_FLAG);
2555 }
2556
2557 static WCHAR *field_format_detailed_cert_name(PCERT_NAME_BLOB name)
2558 {
2559     WCHAR *str = NULL;
2560     DWORD len = CertNameToStrW(X509_ASN_ENCODING, name,
2561      CERT_X500_NAME_STR | CERT_NAME_STR_CRLF_FLAG, NULL, 0);
2562
2563     if (len)
2564     {
2565         str = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
2566         if (str)
2567             CertNameToStrW(X509_ASN_ENCODING, name,
2568              CERT_X500_NAME_STR | CERT_NAME_STR_CRLF_FLAG, str, len);
2569     }
2570     return str;
2571 }
2572
2573 static WCHAR *field_format_detailed_issuer(PCCERT_CONTEXT cert, void *param)
2574 {
2575     return field_format_detailed_cert_name(&cert->pCertInfo->Issuer);
2576 }
2577
2578 static WCHAR *field_format_subject(PCCERT_CONTEXT cert)
2579 {
2580     return get_cert_name_string(cert, CERT_NAME_SIMPLE_DISPLAY_TYPE, 0);
2581 }
2582
2583 static WCHAR *field_format_detailed_subject(PCCERT_CONTEXT cert, void *param)
2584 {
2585     return field_format_detailed_cert_name(&cert->pCertInfo->Subject);
2586 }
2587
2588 static WCHAR *format_long_date(const FILETIME *fileTime)
2589 {
2590     WCHAR dateFmt[80]; /* long enough for LOCALE_SLONGDATE */
2591     DWORD len;
2592     WCHAR *buf = NULL;
2593     SYSTEMTIME sysTime;
2594
2595     /* FIXME: format isn't quite right, want time too */
2596     GetLocaleInfoW(LOCALE_SYSTEM_DEFAULT, LOCALE_SLONGDATE, dateFmt,
2597      sizeof(dateFmt) / sizeof(dateFmt[0]));
2598     FileTimeToSystemTime(fileTime, &sysTime);
2599     len = GetDateFormatW(LOCALE_SYSTEM_DEFAULT, 0, &sysTime, dateFmt, NULL, 0);
2600     if (len)
2601     {
2602         buf = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
2603         if (buf)
2604             GetDateFormatW(LOCALE_SYSTEM_DEFAULT, 0, &sysTime, dateFmt, buf,
2605              len);
2606     }
2607     return buf;
2608 }
2609
2610 static WCHAR *field_format_from_date(PCCERT_CONTEXT cert)
2611 {
2612     return format_long_date(&cert->pCertInfo->NotBefore);
2613 }
2614
2615 static WCHAR *field_format_to_date(PCCERT_CONTEXT cert)
2616 {
2617     return format_long_date(&cert->pCertInfo->NotAfter);
2618 }
2619
2620 static WCHAR *field_format_public_key(PCCERT_CONTEXT cert)
2621 {
2622     PCCRYPT_OID_INFO oidInfo;
2623     WCHAR *buf = NULL;
2624
2625     oidInfo = CryptFindOIDInfo(CRYPT_OID_INFO_OID_KEY,
2626      cert->pCertInfo->SubjectPublicKeyInfo.Algorithm.pszObjId, 0);
2627     if (oidInfo)
2628     {
2629         WCHAR fmt[MAX_STRING_LEN];
2630
2631         if (LoadStringW(hInstance, IDS_FIELD_PUBLIC_KEY_FORMAT, fmt,
2632          sizeof(fmt) / sizeof(fmt[0])))
2633         {
2634             /* Allocate the output buffer.  Use the number of bytes in the
2635              * public key as a conservative (high) estimate for the number of
2636              * digits in its output.
2637              * The output is of the form (in English)
2638              * "<public key algorithm> (<public key bit length> bits)".
2639              * Ordinarily having two positional parameters in a string is not a
2640              * good idea, but as this isn't a sentence fragment, it shouldn't
2641              * be word-order dependent.
2642              */
2643             buf = HeapAlloc(GetProcessHeap(), 0,
2644              (strlenW(fmt) + strlenW(oidInfo->pwszName) +
2645              cert->pCertInfo->SubjectPublicKeyInfo.PublicKey.cbData * 8)
2646              * sizeof(WCHAR));
2647             if (buf)
2648                 sprintfW(buf, fmt, oidInfo->pwszName,
2649                  CertGetPublicKeyLength(X509_ASN_ENCODING,
2650                   &cert->pCertInfo->SubjectPublicKeyInfo));
2651         }
2652     }
2653     return buf;
2654 }
2655
2656 static WCHAR *field_format_detailed_public_key(PCCERT_CONTEXT cert, void *param)
2657 {
2658     return format_hex_string(
2659      cert->pCertInfo->SubjectPublicKeyInfo.PublicKey.pbData,
2660      cert->pCertInfo->SubjectPublicKeyInfo.PublicKey.cbData);
2661 }
2662
2663 struct field_value_data;
2664 struct detail_data
2665 {
2666     PCCRYPTUI_VIEWCERTIFICATE_STRUCTW pCertViewInfo;
2667     BOOL *pfPropertiesChanged;
2668     int cFields;
2669     struct field_value_data *fields;
2670 };
2671
2672 typedef void (*add_fields_func)(HWND hwnd, struct detail_data *data);
2673
2674 typedef WCHAR *(*create_detailed_value_func)(PCCERT_CONTEXT cert, void *param);
2675
2676 struct field_value_data
2677 {
2678     create_detailed_value_func create;
2679     LPWSTR detailed_value;
2680     void *param;
2681 };
2682
2683 static void add_field_value_data(struct detail_data *data,
2684  create_detailed_value_func create, void *param)
2685 {
2686     if (data->cFields)
2687         data->fields = HeapReAlloc(GetProcessHeap(), 0, data->fields,
2688          (data->cFields + 1) * sizeof(struct field_value_data));
2689     else
2690         data->fields = HeapAlloc(GetProcessHeap(), 0,
2691          sizeof(struct field_value_data));
2692     if (data->fields)
2693     {
2694         data->fields[data->cFields].create = create;
2695         data->fields[data->cFields].detailed_value = NULL;
2696         data->fields[data->cFields].param = param;
2697         data->cFields++;
2698     }
2699 }
2700
2701 static void add_field_and_value_to_list(HWND hwnd, struct detail_data *data,
2702  LPWSTR field, LPWSTR value, create_detailed_value_func create, void *param)
2703 {
2704     LVITEMW item;
2705     int iItem = SendMessageW(hwnd, LVM_GETITEMCOUNT, 0, 0);
2706
2707     item.mask = LVIF_TEXT | LVIF_PARAM;
2708     item.iItem = iItem;
2709     item.iSubItem = 0;
2710     item.pszText = field;
2711     item.lParam = (LPARAM)data;
2712     SendMessageW(hwnd, LVM_INSERTITEMW, 0, (LPARAM)&item);
2713     if (value)
2714     {
2715         item.pszText = value;
2716         item.iSubItem = 1;
2717         SendMessageW(hwnd, LVM_SETITEMTEXTW, iItem, (LPARAM)&item);
2718     }
2719     add_field_value_data(data, create, param);
2720 }
2721
2722 static void add_string_id_and_value_to_list(HWND hwnd, struct detail_data *data,
2723  int id, LPWSTR value, create_detailed_value_func create, void *param)
2724 {
2725     WCHAR buf[MAX_STRING_LEN];
2726
2727     LoadStringW(hInstance, id, buf, sizeof(buf) / sizeof(buf[0]));
2728     add_field_and_value_to_list(hwnd, data, buf, value, create, param);
2729 }
2730
2731 struct v1_field
2732 {
2733     int id;
2734     field_format_func format;
2735     create_detailed_value_func create_detailed_value;
2736 };
2737
2738 static void add_v1_field(HWND hwnd, struct detail_data *data,
2739  const struct v1_field *field)
2740 {
2741     WCHAR *val = field->format(data->pCertViewInfo->pCertContext);
2742
2743     if (val)
2744     {
2745         add_string_id_and_value_to_list(hwnd, data, field->id, val,
2746          field->create_detailed_value, NULL);
2747         HeapFree(GetProcessHeap(), 0, val);
2748     }
2749 }
2750
2751 static const struct v1_field v1_fields[] = {
2752  { IDS_FIELD_VERSION, field_format_version, NULL },
2753  { IDS_FIELD_SERIAL_NUMBER, field_format_serial_number, NULL },
2754  { IDS_FIELD_ISSUER, field_format_issuer, field_format_detailed_issuer },
2755  { IDS_FIELD_VALID_FROM, field_format_from_date, NULL },
2756  { IDS_FIELD_VALID_TO, field_format_to_date, NULL },
2757  { IDS_FIELD_SUBJECT, field_format_subject, field_format_detailed_subject },
2758  { IDS_FIELD_PUBLIC_KEY, field_format_public_key,
2759    field_format_detailed_public_key }
2760 };
2761
2762 static void add_v1_fields(HWND hwnd, struct detail_data *data)
2763 {
2764     int i;
2765     PCCERT_CONTEXT cert = data->pCertViewInfo->pCertContext;
2766
2767     /* The last item in v1_fields is the public key, which is not in the loop
2768      * because it's a special case.
2769      */
2770     for (i = 0; i < sizeof(v1_fields) / sizeof(v1_fields[0]) - 1; i++)
2771         add_v1_field(hwnd, data, &v1_fields[i]);
2772     if (cert->pCertInfo->SubjectPublicKeyInfo.PublicKey.cbData)
2773         add_v1_field(hwnd, data, &v1_fields[i]);
2774 }
2775
2776 static WCHAR *crypt_format_extension(PCERT_EXTENSION ext, DWORD formatStrType)
2777 {
2778     WCHAR *str = NULL;
2779     DWORD size;
2780
2781     if (CryptFormatObject(X509_ASN_ENCODING, 0, formatStrType, NULL,
2782      ext->pszObjId, ext->Value.pbData, ext->Value.cbData, NULL, &size))
2783     {
2784         str = HeapAlloc(GetProcessHeap(), 0, size);
2785         CryptFormatObject(X509_ASN_ENCODING, 0, formatStrType, NULL,
2786          ext->pszObjId, ext->Value.pbData, ext->Value.cbData, str, &size);
2787     }
2788     return str;
2789 }
2790
2791 static WCHAR *field_format_extension_hex_with_ascii(PCERT_EXTENSION ext)
2792 {
2793     WCHAR *str = NULL;
2794
2795     if (ext->Value.cbData)
2796     {
2797         /* The output is formatted as:
2798          * <hex bytes>  <ascii bytes>\n
2799          * where <hex bytes> is a string of up to 8 bytes, output as %02x,
2800          * and <ascii bytes> is the ASCII equivalent of each byte, or '.' if
2801          * the byte is not printable.
2802          * So, for example, the extension value consisting of the following
2803          * bytes:
2804          *   0x30,0x14,0x31,0x12,0x30,0x10,0x06,0x03,0x55,0x04,0x03,
2805          *   0x13,0x09,0x4a,0x75,0x61,0x6e,0x20,0x4c,0x61,0x6e,0x67
2806          * is output as:
2807          *   30 14 31 12 30 10 06 03  0.1.0...
2808          *   55 04 03 13 09 4a 75 61  U....Jua
2809          *   6e 20 4c 61 6e 67        n Lang
2810          * The allocation size therefore requires:
2811          * - 4 characters per character in an 8-byte line
2812          *   (2 for the hex format, one for the space, one for the ASCII value)
2813          * - 3 more characters per 8-byte line (two spaces and a newline)
2814          * - 1 character for the terminating nul
2815          * FIXME: should use a fixed-width font for this
2816          */
2817         DWORD lines = (ext->Value.cbData + 7) / 8;
2818
2819         str = HeapAlloc(GetProcessHeap(), 0,
2820          (lines * 8 * 4 + lines * 3 + 1) * sizeof(WCHAR));
2821         if (str)
2822         {
2823             static const WCHAR fmt[] = { '%','0','2','x',' ',0 };
2824             DWORD i, j;
2825             WCHAR *ptr;
2826
2827             for (i = 0, ptr = str; i < ext->Value.cbData; i += 8)
2828             {
2829                 /* Output as hex bytes first */
2830                 for (j = i; j < min(i + 8, ext->Value.cbData); j++, ptr += 3)
2831                     sprintfW(ptr, fmt, ext->Value.pbData[j]);
2832                 /* Pad the hex output with spaces for alignment */
2833                 if (j == ext->Value.cbData && j % 8)
2834                 {
2835                     static const WCHAR pad[] = { ' ',' ',' ' };
2836
2837                     for (; j % 8; j++, ptr += sizeof(pad) / sizeof(pad[0]))
2838                         memcpy(ptr, pad, sizeof(pad));
2839                 }
2840                 /* The last sprintfW included a space, so just insert one
2841                  * more space between the hex bytes and the ASCII output
2842                  */
2843                 *ptr++ = ' ';
2844                 /* Output as ASCII bytes */
2845                 for (j = i; j < min(i + 8, ext->Value.cbData); j++, ptr++)
2846                 {
2847                     if (isprintW(ext->Value.pbData[j]) &&
2848                      !isspaceW(ext->Value.pbData[j]))
2849                         *ptr = ext->Value.pbData[j];
2850                     else
2851                         *ptr = '.';
2852                 }
2853                 *ptr++ = '\n';
2854             }
2855             *ptr++ = '\0';
2856         }
2857     }
2858     return str;
2859 }
2860
2861 static WCHAR *field_format_detailed_extension(PCCERT_CONTEXT cert, void *param)
2862 {
2863     PCERT_EXTENSION ext = param;
2864     LPWSTR str = crypt_format_extension(ext,
2865      CRYPT_FORMAT_STR_MULTI_LINE | CRYPT_FORMAT_STR_NO_HEX);
2866
2867     if (!str)
2868         str = field_format_extension_hex_with_ascii(ext);
2869     return str;
2870 }
2871
2872 static void add_cert_extension_detail(HWND hwnd, struct detail_data *data,
2873  PCERT_EXTENSION ext)
2874 {
2875     PCCRYPT_OID_INFO oidInfo = CryptFindOIDInfo(CRYPT_OID_INFO_OID_KEY,
2876      ext->pszObjId, 0);
2877     LPWSTR val = crypt_format_extension(ext, 0);
2878
2879     if (oidInfo)
2880         add_field_and_value_to_list(hwnd, data, (LPWSTR)oidInfo->pwszName,
2881          val, field_format_detailed_extension, ext);
2882     else
2883     {
2884         DWORD len = strlen(ext->pszObjId);
2885         LPWSTR oidW = HeapAlloc(GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR));
2886
2887         if (oidW)
2888         {
2889             DWORD i;
2890
2891             for (i = 0; i <= len; i++)
2892                 oidW[i] = ext->pszObjId[i];
2893             add_field_and_value_to_list(hwnd, data, oidW, val,
2894              field_format_detailed_extension, ext);
2895             HeapFree(GetProcessHeap(), 0, oidW);
2896         }
2897     }
2898     HeapFree(GetProcessHeap(), 0, val);
2899 }
2900
2901 static void add_all_extensions(HWND hwnd, struct detail_data *data)
2902 {
2903     DWORD i;
2904     PCCERT_CONTEXT cert = data->pCertViewInfo->pCertContext;
2905
2906     for (i = 0; i < cert->pCertInfo->cExtension; i++)
2907         add_cert_extension_detail(hwnd, data, &cert->pCertInfo->rgExtension[i]);
2908 }
2909
2910 static void add_critical_extensions(HWND hwnd, struct detail_data *data)
2911 {
2912     DWORD i;
2913     PCCERT_CONTEXT cert = data->pCertViewInfo->pCertContext;
2914
2915     for (i = 0; i < cert->pCertInfo->cExtension; i++)
2916         if (cert->pCertInfo->rgExtension[i].fCritical)
2917             add_cert_extension_detail(hwnd, data,
2918              &cert->pCertInfo->rgExtension[i]);
2919 }
2920
2921 typedef WCHAR * (*prop_to_value_func)(void *pb, DWORD cb);
2922
2923 struct prop_id_to_string_id
2924 {
2925     DWORD prop;
2926     int id;
2927     BOOL prop_is_string;
2928     prop_to_value_func prop_to_value;
2929 };
2930
2931 static WCHAR *format_enhanced_key_usage_value(void *pb, DWORD cb)
2932 {
2933     CERT_EXTENSION ext;
2934
2935     ext.pszObjId = (LPSTR)X509_ENHANCED_KEY_USAGE;
2936     ext.fCritical = FALSE;
2937     ext.Value.pbData = pb;
2938     ext.Value.cbData = cb;
2939     return crypt_format_extension(&ext, 0);
2940 }
2941
2942 /* Logically the access state should also be checked, and IDC_EDITPROPERTIES
2943  * disabled for read-only certificates, but native doesn't appear to do that.
2944  */
2945 static const struct prop_id_to_string_id prop_id_map[] = {
2946  { CERT_HASH_PROP_ID, IDS_PROP_HASH, FALSE, format_hex_string },
2947  { CERT_FRIENDLY_NAME_PROP_ID, IDS_PROP_FRIENDLY_NAME, TRUE, NULL },
2948  { CERT_DESCRIPTION_PROP_ID, IDS_PROP_DESCRIPTION, TRUE, NULL },
2949  { CERT_ENHKEY_USAGE_PROP_ID, IDS_PROP_ENHKEY_USAGE, FALSE,
2950    format_enhanced_key_usage_value },
2951 };
2952
2953 static void add_properties(HWND hwnd, struct detail_data *data)
2954 {
2955     DWORD i;
2956     PCCERT_CONTEXT cert = data->pCertViewInfo->pCertContext;
2957
2958     for (i = 0; i < sizeof(prop_id_map) / sizeof(prop_id_map[0]); i++)
2959     {
2960         DWORD cb;
2961
2962         if (CertGetCertificateContextProperty(cert, prop_id_map[i].prop, NULL,
2963          &cb))
2964         {
2965             BYTE *pb;
2966             WCHAR *val = NULL;
2967
2968             /* FIXME: MS adds a separate value for the signature hash
2969              * algorithm.
2970              */
2971             pb = HeapAlloc(GetProcessHeap(), 0, cb);
2972             if (pb)
2973             {
2974                 if (CertGetCertificateContextProperty(cert,
2975                  prop_id_map[i].prop, pb, &cb))
2976                 {
2977                     if (prop_id_map[i].prop_is_string)
2978                     {
2979                         val = (LPWSTR)pb;
2980                         /* Don't double-free pb */
2981                         pb = NULL;
2982                     }
2983                     else
2984                         val = prop_id_map[i].prop_to_value(pb, cb);
2985                 }
2986                 HeapFree(GetProcessHeap(), 0, pb);
2987             }
2988             add_string_id_and_value_to_list(hwnd, data, prop_id_map[i].id, val,
2989              NULL, NULL);
2990         }
2991     }
2992 }
2993
2994 static void add_all_fields(HWND hwnd, struct detail_data *data)
2995 {
2996     add_v1_fields(hwnd, data);
2997     add_all_extensions(hwnd, data);
2998     add_properties(hwnd, data);
2999 }
3000
3001 struct selection_list_item
3002 {
3003     int id;
3004     add_fields_func add;
3005 };
3006
3007 const struct selection_list_item listItems[] = {
3008  { IDS_FIELDS_ALL, add_all_fields },
3009  { IDS_FIELDS_V1, add_v1_fields },
3010  { IDS_FIELDS_EXTENSIONS, add_all_extensions },
3011  { IDS_FIELDS_CRITICAL_EXTENSIONS, add_critical_extensions },
3012  { IDS_FIELDS_PROPERTIES, add_properties },
3013 };
3014
3015 static void create_show_list(HWND hwnd, struct detail_data *data)
3016 {
3017     HWND cb = GetDlgItem(hwnd, IDC_DETAIL_SELECT);
3018     WCHAR buf[MAX_STRING_LEN];
3019     int i;
3020
3021     for (i = 0; i < sizeof(listItems) / sizeof(listItems[0]); i++)
3022     {
3023         int index;
3024
3025         LoadStringW(hInstance, listItems[i].id, buf,
3026          sizeof(buf) / sizeof(buf[0]));
3027         index = SendMessageW(cb, CB_INSERTSTRING, -1, (LPARAM)buf);
3028         SendMessageW(cb, CB_SETITEMDATA, index, (LPARAM)data);
3029     }
3030     SendMessageW(cb, CB_SETCURSEL, 0, 0);
3031 }
3032
3033 static void create_listview_columns(HWND hwnd)
3034 {
3035     HWND lv = GetDlgItem(hwnd, IDC_DETAIL_LIST);
3036     RECT rc;
3037     WCHAR buf[MAX_STRING_LEN];
3038     LVCOLUMNW column;
3039
3040     SendMessageW(lv, LVM_SETEXTENDEDLISTVIEWSTYLE, 0, LVS_EX_FULLROWSELECT);
3041     GetWindowRect(lv, &rc);
3042     LoadStringW(hInstance, IDS_FIELD, buf, sizeof(buf) / sizeof(buf[0]));
3043     column.mask = LVCF_WIDTH | LVCF_TEXT;
3044     column.cx = (rc.right - rc.left) / 2 - 2;
3045     column.pszText = buf;
3046     SendMessageW(lv, LVM_INSERTCOLUMNW, 0, (LPARAM)&column);
3047     LoadStringW(hInstance, IDS_VALUE, buf, sizeof(buf) / sizeof(buf[0]));
3048     SendMessageW(lv, LVM_INSERTCOLUMNW, 1, (LPARAM)&column);
3049 }
3050
3051 static void set_fields_selection(HWND hwnd, struct detail_data *data, int sel)
3052 {
3053     HWND list = GetDlgItem(hwnd, IDC_DETAIL_LIST);
3054
3055     if (sel >= 0 && sel < sizeof(listItems) / sizeof(listItems[0]))
3056     {
3057         SendMessageW(list, LVM_DELETEALLITEMS, 0, 0);
3058         listItems[sel].add(list, data);
3059     }
3060 }
3061
3062 static void create_cert_details_list(HWND hwnd, struct detail_data *data)
3063 {
3064     create_show_list(hwnd, data);
3065     create_listview_columns(hwnd);
3066     set_fields_selection(hwnd, data, 0);
3067 }
3068
3069 static void add_purpose(HWND hwnd, LPCSTR oid)
3070 {
3071     HWND lv = GetDlgItem(hwnd, IDC_CERTIFICATE_USAGES);
3072     PCRYPT_OID_INFO info = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
3073      sizeof(CRYPT_OID_INFO));
3074
3075     if (info)
3076     {
3077         char *oidCopy = HeapAlloc(GetProcessHeap(), 0, strlen(oid) + 1);
3078
3079         if (oidCopy)
3080         {
3081             LVITEMA item;
3082
3083             strcpy(oidCopy, oid);
3084             info->cbSize = sizeof(CRYPT_OID_INFO);
3085             info->pszOID = oidCopy;
3086             item.mask = LVIF_TEXT | LVIF_STATE | LVIF_PARAM;
3087             item.state = INDEXTOSTATEIMAGEMASK(CheckBitmapIndexChecked);
3088             item.stateMask = LVIS_STATEIMAGEMASK;
3089             item.iItem = SendMessageW(lv, LVM_GETITEMCOUNT, 0, 0);
3090             item.iSubItem = 0;
3091             item.lParam = (LPARAM)info;
3092             item.pszText = oidCopy;
3093             SendMessageA(lv, LVM_INSERTITEMA, 0, (LPARAM)&item);
3094         }
3095         else
3096             HeapFree(GetProcessHeap(), 0, info);
3097     }
3098 }
3099
3100 static BOOL is_valid_oid(LPCSTR oid)
3101 {
3102     BOOL ret;
3103
3104     if (oid[0] != '0' && oid[0] != '1' && oid[0] != '2')
3105         ret = FALSE;
3106     else if (oid[1] != '.')
3107         ret = FALSE;
3108     else if (!oid[2])
3109         ret = FALSE;
3110     else
3111     {
3112         const char *ptr;
3113         BOOL expectNum = TRUE;
3114
3115         for (ptr = oid + 2, ret = TRUE; ret && *ptr; ptr++)
3116         {
3117             if (expectNum)
3118             {
3119                 if (!isdigit(*ptr))
3120                     ret = FALSE;
3121                 else if (*(ptr + 1) == '.')
3122                     expectNum = FALSE;
3123             }
3124             else
3125             {
3126                 if (*ptr != '.')
3127                     ret = FALSE;
3128                 else if (!(*(ptr + 1)))
3129                     ret = FALSE;
3130                 else
3131                     expectNum = TRUE;
3132             }
3133         }
3134     }
3135     return ret;
3136 }
3137
3138 static BOOL is_oid_in_list(HWND hwnd, LPCSTR oid)
3139 {
3140     return find_oid_in_list(GetDlgItem(hwnd, IDC_CERTIFICATE_USAGES), oid)
3141      != -1;
3142 }
3143
3144 #define MAX_PURPOSE 255
3145
3146 static LRESULT CALLBACK add_purpose_dlg_proc(HWND hwnd, UINT msg,
3147  WPARAM wp, LPARAM lp)
3148 {
3149     LRESULT ret = 0;
3150     char buf[MAX_PURPOSE + 1];
3151
3152     switch (msg)
3153     {
3154     case WM_INITDIALOG:
3155         SendMessageW(GetDlgItem(hwnd, IDC_NEW_PURPOSE), EM_SETLIMITTEXT,
3156          MAX_PURPOSE, 0);
3157         ShowScrollBar(GetDlgItem(hwnd, IDC_NEW_PURPOSE), SB_VERT, FALSE);
3158         SetWindowLongPtrW(hwnd, DWLP_USER, lp);
3159         break;
3160     case WM_COMMAND:
3161         switch (HIWORD(wp))
3162         {
3163         case EN_CHANGE:
3164             if (LOWORD(wp) == IDC_NEW_PURPOSE)
3165             {
3166                 /* Show/hide scroll bar on description depending on how much
3167                  * text it has.
3168                  */
3169                 HWND description = GetDlgItem(hwnd, IDC_NEW_PURPOSE);
3170                 int lines = SendMessageW(description, EM_GETLINECOUNT, 0, 0);
3171
3172                 ShowScrollBar(description, SB_VERT, lines > 1);
3173             }
3174             break;
3175         case BN_CLICKED:
3176             switch (LOWORD(wp))
3177             {
3178             case IDOK:
3179                 SendMessageA(GetDlgItem(hwnd, IDC_NEW_PURPOSE), WM_GETTEXT,
3180                  sizeof(buf) / sizeof(buf[0]), (LPARAM)buf);
3181                 if (!buf[0])
3182                 {
3183                     /* An empty purpose is the same as cancelling */
3184                     EndDialog(hwnd, IDCANCEL);
3185                     ret = TRUE;
3186                 }
3187                 else if (!is_valid_oid(buf))
3188                 {
3189                     WCHAR title[MAX_STRING_LEN], error[MAX_STRING_LEN];
3190
3191                     LoadStringW(hInstance, IDS_CERTIFICATE_PURPOSE_ERROR, error,
3192                      sizeof(error) / sizeof(error[0]));
3193                     LoadStringW(hInstance, IDS_CERTIFICATE_PROPERTIES, title,
3194                      sizeof(title) / sizeof(title[0]));
3195                     MessageBoxW(hwnd, error, title, MB_ICONERROR | MB_OK);
3196                 }
3197                 else if (is_oid_in_list(
3198                  (HWND)GetWindowLongPtrW(hwnd, DWLP_USER), buf))
3199                 {
3200                     WCHAR title[MAX_STRING_LEN], error[MAX_STRING_LEN];
3201
3202                     LoadStringW(hInstance, IDS_CERTIFICATE_PURPOSE_EXISTS,
3203                      error, sizeof(error) / sizeof(error[0]));
3204                     LoadStringW(hInstance, IDS_CERTIFICATE_PROPERTIES, title,
3205                      sizeof(title) / sizeof(title[0]));
3206                     MessageBoxW(hwnd, error, title, MB_ICONEXCLAMATION | MB_OK);
3207                 }
3208                 else
3209                 {
3210                     HWND parent = (HWND)GetWindowLongPtrW(hwnd, DWLP_USER);
3211
3212                     add_purpose(parent, buf);
3213                     EndDialog(hwnd, wp);
3214                     ret = TRUE;
3215                 }
3216                 break;
3217             case IDCANCEL:
3218                 EndDialog(hwnd, wp);
3219                 ret = TRUE;
3220                 break;
3221             }
3222             break;
3223         }
3224         break;
3225     }
3226     return ret;
3227 }
3228
3229 static WCHAR *get_cert_property_as_string(PCCERT_CONTEXT cert, DWORD prop)
3230 {
3231     WCHAR *name = NULL;
3232     DWORD cb;
3233
3234     if (CertGetCertificateContextProperty(cert, prop, NULL, &cb))
3235     {
3236         name = HeapAlloc(GetProcessHeap(), 0, cb);
3237         if (name)
3238         {
3239             if (!CertGetCertificateContextProperty(cert, prop, (LPBYTE)name,
3240              &cb))
3241             {
3242                 HeapFree(GetProcessHeap(), 0, name);
3243                 name = NULL;
3244             }
3245         }
3246     }
3247     return name;
3248 }
3249
3250 static void redraw_states(HWND list, BOOL enabled)
3251 {
3252     int items = SendMessageW(list, LVM_GETITEMCOUNT, 0, 0), i;
3253
3254     for (i = 0; i < items; i++)
3255     {
3256         BOOL change = FALSE;
3257         int state;
3258
3259         state = SendMessageW(list, LVM_GETITEMSTATE, i, LVIS_STATEIMAGEMASK);
3260         /* This reverses the INDEXTOSTATEIMAGEMASK shift.  There doesn't appear
3261          * to be a handy macro for it.
3262          */
3263         state >>= 12;
3264         if (enabled)
3265         {
3266             if (state == CheckBitmapIndexDisabledChecked)
3267             {
3268                 state = CheckBitmapIndexChecked;
3269                 change = TRUE;
3270             }
3271             if (state == CheckBitmapIndexDisabledUnchecked)
3272             {
3273                 state = CheckBitmapIndexUnchecked;
3274                 change = TRUE;
3275             }
3276         }
3277         else
3278         {
3279             if (state == CheckBitmapIndexChecked)
3280             {
3281                 state = CheckBitmapIndexDisabledChecked;
3282                 change = TRUE;
3283             }
3284             if (state == CheckBitmapIndexUnchecked)
3285             {
3286                 state = CheckBitmapIndexDisabledUnchecked;
3287                 change = TRUE;
3288             }
3289         }
3290         if (change)
3291         {
3292             LVITEMW item;
3293
3294             item.state = INDEXTOSTATEIMAGEMASK(state);
3295             item.stateMask = LVIS_STATEIMAGEMASK;
3296             SendMessageW(list, LVM_SETITEMSTATE, i, (LPARAM)&item);
3297         }
3298     }
3299 }
3300
3301 typedef enum {
3302     PurposeEnableAll = 0,
3303     PurposeDisableAll,
3304     PurposeEnableSelected
3305 } PurposeSelection;
3306
3307 static void select_purposes(HWND hwnd, PurposeSelection selection)
3308 {
3309     HWND lv = GetDlgItem(hwnd, IDC_CERTIFICATE_USAGES);
3310
3311     switch (selection)
3312     {
3313     case PurposeEnableAll:
3314     case PurposeDisableAll:
3315         EnableWindow(lv, FALSE);
3316         redraw_states(lv, FALSE);
3317         EnableWindow(GetDlgItem(hwnd, IDC_ADD_PURPOSE), FALSE);
3318         break;
3319     case PurposeEnableSelected:
3320         EnableWindow(lv, TRUE);
3321         redraw_states(lv, TRUE);
3322         EnableWindow(GetDlgItem(hwnd, IDC_ADD_PURPOSE), TRUE);
3323     }
3324 }
3325
3326 struct edit_cert_data
3327 {
3328     PCCERT_CONTEXT cert;
3329     BOOL *pfPropertiesChanged;
3330     HIMAGELIST imageList;
3331 };
3332
3333 static void show_cert_usages(HWND hwnd, struct edit_cert_data *data)
3334 {
3335     PCCERT_CONTEXT cert = data->cert;
3336     HWND lv = GetDlgItem(hwnd, IDC_CERTIFICATE_USAGES);
3337     PCERT_ENHKEY_USAGE usage;
3338     DWORD size;
3339     RECT rc;
3340     LVCOLUMNW column;
3341     PurposeSelection purposeSelection;
3342
3343     GetWindowRect(lv, &rc);
3344     column.mask = LVCF_WIDTH;
3345     column.cx = rc.right - rc.left;
3346     SendMessageW(lv, LVM_INSERTCOLUMNW, 0, (LPARAM)&column);
3347     SendMessageW(lv, LVM_SETIMAGELIST, LVSIL_STATE, (LPARAM)data->imageList);
3348
3349     /* Get enhanced key usage.  Have to check for a property and an extension
3350      * separately, because CertGetEnhancedKeyUsage will succeed and return an
3351      * empty usage if neither is set.  Unfortunately an empty usage implies
3352      * no usage is allowed, so we have to distinguish between the two cases.
3353      */
3354     if (CertGetEnhancedKeyUsage(cert, CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG,
3355      NULL, &size))
3356     {
3357         usage = HeapAlloc(GetProcessHeap(), 0, size);
3358         if (!CertGetEnhancedKeyUsage(cert,
3359          CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG, usage, &size))
3360         {
3361             HeapFree(GetProcessHeap(), 0, usage);
3362             usage = NULL;
3363         }
3364         else if (usage->cUsageIdentifier)
3365             purposeSelection = PurposeEnableSelected;
3366         else
3367             purposeSelection = PurposeDisableAll;
3368     }
3369     else if (CertGetEnhancedKeyUsage(cert, CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG,
3370      NULL, &size))
3371     {
3372         usage = HeapAlloc(GetProcessHeap(), 0, size);
3373         if (!CertGetEnhancedKeyUsage(cert,
3374          CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG, usage, &size))
3375         {
3376             HeapFree(GetProcessHeap(), 0, usage);
3377             usage = NULL;
3378         }
3379         else if (usage->cUsageIdentifier)
3380             purposeSelection = PurposeEnableAll;
3381         else
3382             purposeSelection = PurposeDisableAll;
3383     }
3384     else
3385     {
3386         purposeSelection = PurposeEnableAll;
3387         usage = NULL;
3388     }
3389     if (usage)
3390     {
3391         DWORD i;
3392
3393         for (i = 0; i < usage->cUsageIdentifier; i++)
3394         {
3395             PCCRYPT_OID_INFO info = CryptFindOIDInfo(CRYPT_OID_INFO_OID_KEY,
3396              usage->rgpszUsageIdentifier[i], CRYPT_ENHKEY_USAGE_OID_GROUP_ID);
3397
3398             if (info)
3399                 add_known_usage(lv, info, CheckBitmapIndexDisabledChecked);
3400             else
3401                 add_purpose(hwnd, usage->rgpszUsageIdentifier[i]);
3402         }
3403         HeapFree(GetProcessHeap(), 0, usage);
3404     }
3405     else
3406         add_known_usages_to_list(lv, CheckBitmapIndexDisabledChecked);
3407     select_purposes(hwnd, purposeSelection);
3408     SendMessageW(GetDlgItem(hwnd, IDC_ENABLE_ALL_PURPOSES + purposeSelection),
3409      BM_CLICK, 0, 0);
3410 }
3411
3412 static void set_general_cert_properties(HWND hwnd, struct edit_cert_data *data)
3413 {
3414     PCCERT_CONTEXT cert = data->cert;
3415     WCHAR *str;
3416
3417     if ((str = get_cert_property_as_string(cert, CERT_FRIENDLY_NAME_PROP_ID)))
3418     {
3419         SendMessageW(GetDlgItem(hwnd, IDC_FRIENDLY_NAME), WM_SETTEXT, 0,
3420          (LPARAM)str);
3421         HeapFree(GetProcessHeap(), 0, str);
3422     }
3423     if ((str = get_cert_property_as_string(cert, CERT_DESCRIPTION_PROP_ID)))
3424     {
3425         SendMessageW(GetDlgItem(hwnd, IDC_DESCRIPTION), WM_SETTEXT, 0,
3426          (LPARAM)str);
3427         HeapFree(GetProcessHeap(), 0, str);
3428     }
3429     show_cert_usages(hwnd, data);
3430 }
3431
3432 static void set_cert_string_property(PCCERT_CONTEXT cert, DWORD prop,
3433  LPWSTR str)
3434 {
3435     if (str && strlenW(str))
3436     {
3437         CRYPT_DATA_BLOB blob;
3438
3439         blob.pbData = (BYTE *)str;
3440         blob.cbData = (strlenW(str) + 1) * sizeof(WCHAR);
3441         CertSetCertificateContextProperty(cert, prop, 0, &blob);
3442     }
3443     else
3444         CertSetCertificateContextProperty(cert, prop, 0, NULL);
3445 }
3446
3447 #define WM_REFRESH_VIEW WM_USER + 0
3448
3449 static BOOL CALLBACK refresh_propsheet_pages(HWND hwnd, LPARAM lParam)
3450 {
3451     if ((GetClassLongW(hwnd, GCW_ATOM) == WC_DIALOG))
3452         SendMessageW(hwnd, WM_REFRESH_VIEW, 0, 0);
3453     return TRUE;
3454 }
3455
3456 #define MAX_FRIENDLY_NAME 40
3457 #define MAX_DESCRIPTION 255
3458
3459 static void apply_general_changes(HWND hwnd)
3460 {
3461     WCHAR buf[MAX_DESCRIPTION + 1];
3462     struct edit_cert_data *data =
3463      (struct edit_cert_data *)GetWindowLongPtrW(hwnd, DWLP_USER);
3464
3465     SendMessageW(GetDlgItem(hwnd, IDC_FRIENDLY_NAME), WM_GETTEXT,
3466      sizeof(buf) / sizeof(buf[0]), (LPARAM)buf);
3467     set_cert_string_property(data->cert, CERT_FRIENDLY_NAME_PROP_ID, buf);
3468     SendMessageW(GetDlgItem(hwnd, IDC_DESCRIPTION), WM_GETTEXT,
3469      sizeof(buf) / sizeof(buf[0]), (LPARAM)buf);
3470     set_cert_string_property(data->cert, CERT_DESCRIPTION_PROP_ID, buf);
3471     if (IsDlgButtonChecked(hwnd, IDC_ENABLE_ALL_PURPOSES))
3472     {
3473         /* Setting a NULL usage removes the enhanced key usage property. */
3474         CertSetEnhancedKeyUsage(data->cert, NULL);
3475     }
3476     else if (IsDlgButtonChecked(hwnd, IDC_DISABLE_ALL_PURPOSES))
3477     {
3478         CERT_ENHKEY_USAGE usage = { 0, NULL };
3479
3480         CertSetEnhancedKeyUsage(data->cert, &usage);
3481     }
3482     else if (IsDlgButtonChecked(hwnd, IDC_ENABLE_SELECTED_PURPOSES))
3483     {
3484         HWND lv = GetDlgItem(hwnd, IDC_CERTIFICATE_USAGES);
3485         CERT_ENHKEY_USAGE usage = { 0, NULL };
3486         int purposes = SendMessageW(lv, LVM_GETITEMCOUNT, 0, 0), i;
3487         LVITEMW item;
3488
3489         item.mask = LVIF_STATE | LVIF_PARAM;
3490         item.iSubItem = 0;
3491         item.stateMask = LVIS_STATEIMAGEMASK;
3492         for (i = 0; i < purposes; i++)
3493         {
3494             item.iItem = i;
3495             if (SendMessageW(lv, LVM_GETITEMW, 0, (LPARAM)&item))
3496             {
3497                 int state = item.state >> 12;
3498
3499                 if (state == CheckBitmapIndexChecked)
3500                 {
3501                     CRYPT_OID_INFO *info = (CRYPT_OID_INFO *)item.lParam;
3502
3503                     if (usage.cUsageIdentifier)
3504                         usage.rgpszUsageIdentifier =
3505                          HeapReAlloc(GetProcessHeap(), 0,
3506                          usage.rgpszUsageIdentifier,
3507                          (usage.cUsageIdentifier + 1) * sizeof(LPSTR));
3508                     else
3509                         usage.rgpszUsageIdentifier =
3510                          HeapAlloc(GetProcessHeap(), 0, sizeof(LPSTR));
3511                     if (usage.rgpszUsageIdentifier)
3512                         usage.rgpszUsageIdentifier[usage.cUsageIdentifier++] =
3513                          (LPSTR)info->pszOID;
3514                 }
3515             }
3516         }
3517         CertSetEnhancedKeyUsage(data->cert, &usage);
3518         HeapFree(GetProcessHeap(), 0, usage.rgpszUsageIdentifier);
3519     }
3520     EnumChildWindows(GetParent(GetParent(hwnd)), refresh_propsheet_pages, 0);
3521     if (data->pfPropertiesChanged)
3522         *data->pfPropertiesChanged = TRUE;
3523 }
3524
3525 static LRESULT CALLBACK cert_properties_general_dlg_proc(HWND hwnd, UINT msg,
3526  WPARAM wp, LPARAM lp)
3527 {
3528     PROPSHEETPAGEW *page;
3529
3530     TRACE("(%p, %08x, %08lx, %08lx)\n", hwnd, msg, wp, lp);
3531
3532     switch (msg)
3533     {
3534     case WM_INITDIALOG:
3535     {
3536         HWND description = GetDlgItem(hwnd, IDC_DESCRIPTION);
3537         struct detail_data *detailData;
3538         struct edit_cert_data *editData;
3539
3540         page = (PROPSHEETPAGEW *)lp;
3541         detailData = (struct detail_data *)page->lParam;
3542         SendMessageW(GetDlgItem(hwnd, IDC_FRIENDLY_NAME), EM_SETLIMITTEXT,
3543          MAX_FRIENDLY_NAME, 0);
3544         SendMessageW(description, EM_SETLIMITTEXT, MAX_DESCRIPTION, 0);
3545         ShowScrollBar(description, SB_VERT, FALSE);
3546         editData = HeapAlloc(GetProcessHeap(), 0,
3547          sizeof(struct edit_cert_data));
3548         if (editData)
3549         {
3550             editData->imageList = ImageList_Create(16, 16,
3551              ILC_COLOR4 | ILC_MASK, 4, 0);
3552             if (editData->imageList)
3553             {
3554                 HBITMAP bmp;
3555                 COLORREF backColor = RGB(255, 0, 255);
3556
3557                 bmp = LoadBitmapW(hInstance, MAKEINTRESOURCEW(IDB_CHECKS));
3558                 ImageList_AddMasked(editData->imageList, bmp, backColor);
3559                 DeleteObject(bmp);
3560                 ImageList_SetBkColor(editData->imageList, CLR_NONE);
3561             }
3562             editData->cert = detailData->pCertViewInfo->pCertContext;
3563             editData->pfPropertiesChanged = detailData->pfPropertiesChanged;
3564             SetWindowLongPtrW(hwnd, DWLP_USER, (LPARAM)editData);
3565             set_general_cert_properties(hwnd, editData);
3566         }
3567         break;
3568     }
3569     case WM_NOTIFY:
3570     {
3571         NMHDR *hdr = (NMHDR *)lp;
3572         NMITEMACTIVATE *nm;
3573
3574         switch (hdr->code)
3575         {
3576         case NM_CLICK:
3577             nm = (NMITEMACTIVATE *)lp;
3578             toggle_usage(hwnd, nm->iItem);
3579             SendMessageW(GetParent(hwnd), PSM_CHANGED, (WPARAM)hwnd, 0);
3580             break;
3581         case PSN_APPLY:
3582             apply_general_changes(hwnd);
3583             break;
3584         }
3585         break;
3586     }
3587     case WM_COMMAND:
3588         switch (HIWORD(wp))
3589         {
3590         case EN_CHANGE:
3591             SendMessageW(GetParent(hwnd), PSM_CHANGED, (WPARAM)hwnd, 0);
3592             if (LOWORD(wp) == IDC_DESCRIPTION)
3593             {
3594                 /* Show/hide scroll bar on description depending on how much
3595                  * text it has.
3596                  */
3597                 HWND description = GetDlgItem(hwnd, IDC_DESCRIPTION);
3598                 int lines = SendMessageW(description, EM_GETLINECOUNT, 0, 0);
3599
3600                 ShowScrollBar(description, SB_VERT, lines > 1);
3601             }
3602             break;
3603         case BN_CLICKED:
3604             switch (LOWORD(wp))
3605             {
3606             case IDC_ADD_PURPOSE:
3607                 if (DialogBoxParamW(hInstance,
3608                  MAKEINTRESOURCEW(IDD_ADD_CERT_PURPOSE), hwnd,
3609                  add_purpose_dlg_proc, (LPARAM)hwnd) == IDOK)
3610                     SendMessageW(GetParent(hwnd), PSM_CHANGED, (WPARAM)hwnd, 0);
3611                 break;
3612             case IDC_ENABLE_ALL_PURPOSES:
3613             case IDC_DISABLE_ALL_PURPOSES:
3614             case IDC_ENABLE_SELECTED_PURPOSES:
3615                 SendMessageW(GetParent(hwnd), PSM_CHANGED, (WPARAM)hwnd, 0);
3616                 select_purposes(hwnd, LOWORD(wp) - IDC_ENABLE_ALL_PURPOSES);
3617                 break;
3618             }
3619             break;
3620         }
3621         break;
3622     }
3623     return 0;
3624 }
3625
3626 static UINT CALLBACK cert_properties_general_callback(HWND hwnd, UINT msg,
3627  PROPSHEETPAGEW *page)
3628 {
3629     HWND lv;
3630     int cItem, i;
3631     struct edit_cert_data *data;
3632
3633     switch (msg)
3634     {
3635     case PSPCB_RELEASE:
3636         lv = GetDlgItem(hwnd, IDC_CERTIFICATE_USAGES);
3637         cItem = SendMessageW(lv, LVM_GETITEMCOUNT, 0, 0);
3638         for (i = 0; i < cItem; i++)
3639         {
3640             LVITEMW item;
3641
3642             item.mask = LVIF_PARAM;
3643             item.iItem = i;
3644             item.iSubItem = 0;
3645             if (SendMessageW(lv, LVM_GETITEMW, 0, (LPARAM)&item) && item.lParam)
3646             {
3647                 PCRYPT_OID_INFO info = (PCRYPT_OID_INFO)item.lParam;
3648
3649                 if (info->cbSize == sizeof(CRYPT_OID_INFO) && !info->dwGroupId)
3650                 {
3651                     HeapFree(GetProcessHeap(), 0, (LPSTR)info->pszOID);
3652                     HeapFree(GetProcessHeap(), 0, info);
3653                 }
3654             }
3655         }
3656         data = (struct edit_cert_data *)GetWindowLongPtrW(hwnd, DWLP_USER);
3657         if (data)
3658         {
3659             ImageList_Destroy(data->imageList);
3660             HeapFree(GetProcessHeap(), 0, data);
3661         }
3662         break;
3663     }
3664     return 1;
3665 }
3666
3667 static void show_edit_cert_properties_dialog(HWND parent,
3668  struct detail_data *data)
3669 {
3670     PROPSHEETHEADERW hdr;
3671     PROPSHEETPAGEW page; /* FIXME: need to add a cross-certificate page */
3672
3673     TRACE("(%p)\n", data);
3674
3675     memset(&page, 0, sizeof(PROPSHEETPAGEW));
3676     page.dwSize = sizeof(page);
3677     page.dwFlags = PSP_USECALLBACK;
3678     page.pfnCallback = cert_properties_general_callback;
3679     page.hInstance = hInstance;
3680     page.u.pszTemplate = MAKEINTRESOURCEW(IDD_CERT_PROPERTIES_GENERAL);
3681     page.pfnDlgProc = cert_properties_general_dlg_proc;
3682     page.lParam = (LPARAM)data;
3683
3684     memset(&hdr, 0, sizeof(hdr));
3685     hdr.dwSize = sizeof(hdr);
3686     hdr.hwndParent = parent;
3687     hdr.dwFlags = PSH_PROPSHEETPAGE;
3688     hdr.hInstance = hInstance;
3689     hdr.pszCaption = MAKEINTRESOURCEW(IDS_CERTIFICATE_PROPERTIES);
3690     hdr.u3.ppsp = &page;
3691     hdr.nPages = 1;
3692     PropertySheetW(&hdr);
3693 }
3694
3695 static void free_detail_fields(struct detail_data *data)
3696 {
3697     DWORD i;
3698
3699     for (i = 0; i < data->cFields; i++)
3700         HeapFree(GetProcessHeap(), 0, data->fields[i].detailed_value);
3701     HeapFree(GetProcessHeap(), 0, data->fields);
3702     data->fields = NULL;
3703     data->cFields = 0;
3704 }
3705
3706 static void refresh_details_view(HWND hwnd)
3707 {
3708     HWND cb = GetDlgItem(hwnd, IDC_DETAIL_SELECT);
3709     int curSel;
3710     struct detail_data *data;
3711
3712     curSel = SendMessageW(cb, CB_GETCURSEL, 0, 0);
3713     /* Actually, any index will do, since they all store the same data value */
3714     data = (struct detail_data *)SendMessageW(cb, CB_GETITEMDATA, curSel, 0);
3715     free_detail_fields(data);
3716     set_fields_selection(hwnd, data, curSel);
3717 }
3718
3719 static LRESULT CALLBACK detail_dlg_proc(HWND hwnd, UINT msg, WPARAM wp,
3720  LPARAM lp)
3721 {
3722     PROPSHEETPAGEW *page;
3723     struct detail_data *data;
3724
3725     TRACE("(%p, %08x, %08lx, %08lx)\n", hwnd, msg, wp, lp);
3726
3727     switch (msg)
3728     {
3729     case WM_INITDIALOG:
3730         page = (PROPSHEETPAGEW *)lp;
3731         data = (struct detail_data *)page->lParam;
3732         create_cert_details_list(hwnd, data);
3733         if (!(data->pCertViewInfo->dwFlags & CRYPTUI_ENABLE_EDITPROPERTIES))
3734             EnableWindow(GetDlgItem(hwnd, IDC_EDITPROPERTIES), FALSE);
3735         if (data->pCertViewInfo->dwFlags & CRYPTUI_DISABLE_EXPORT)
3736             EnableWindow(GetDlgItem(hwnd, IDC_EXPORT), FALSE);
3737         break;
3738     case WM_NOTIFY:
3739     {
3740         NMITEMACTIVATE *nm;
3741         HWND list = GetDlgItem(hwnd, IDC_DETAIL_LIST);
3742
3743         nm = (NMITEMACTIVATE*)lp;
3744         if (nm->hdr.hwndFrom == list && nm->uNewState & LVN_ITEMACTIVATE
3745          && nm->hdr.code == LVN_ITEMCHANGED)
3746         {
3747             data = (struct detail_data *)nm->lParam;
3748             if (nm->iItem >= 0 && data && nm->iItem < data->cFields)
3749             {
3750                 WCHAR buf[MAX_STRING_LEN], *val = NULL;
3751                 HWND valueCtl = GetDlgItem(hwnd, IDC_DETAIL_VALUE);
3752
3753                 if (data->fields[nm->iItem].create)
3754                     val = data->fields[nm->iItem].create(
3755                      data->pCertViewInfo->pCertContext,
3756                      data->fields[nm->iItem].param);
3757                 else
3758                 {
3759                     LVITEMW item;
3760                     int res;
3761
3762                     item.cchTextMax = sizeof(buf) / sizeof(buf[0]);
3763                     item.mask = LVIF_TEXT;
3764                     item.pszText = buf;
3765                     item.iItem = nm->iItem;
3766                     item.iSubItem = 1;
3767                     res = SendMessageW(list, LVM_GETITEMW, 0, (LPARAM)&item);
3768                     if (res)
3769                         val = buf;
3770                 }
3771                 /* Select all the text in the control, the next update will
3772                  * replace it
3773                  */
3774                 SendMessageW(valueCtl, EM_SETSEL, 0, -1);
3775                 add_unformatted_text_to_control(valueCtl, val,
3776                  val ? strlenW(val) : 0);
3777                 if (val != buf)
3778                     HeapFree(GetProcessHeap(), 0, val);
3779             }
3780         }
3781         break;
3782     }
3783     case WM_COMMAND:
3784         switch (wp)
3785         {
3786         case IDC_EXPORT:
3787         {
3788             HWND cb = GetDlgItem(hwnd, IDC_DETAIL_SELECT);
3789             CRYPTUI_WIZ_EXPORT_INFO info;
3790
3791             data = (struct detail_data *)SendMessageW(cb, CB_GETITEMDATA, 0, 0);
3792             info.dwSize = sizeof(info);
3793             info.pwszExportFileName = NULL;
3794             info.dwSubjectChoice = CRYPTUI_WIZ_EXPORT_CERT_CONTEXT;
3795             info.u.pCertContext = data->pCertViewInfo->pCertContext;
3796             info.cStores = 0;
3797             CryptUIWizExport(0, hwnd, NULL, &info, NULL);
3798             break;
3799         }
3800         case IDC_EDITPROPERTIES:
3801         {
3802             HWND cb = GetDlgItem(hwnd, IDC_DETAIL_SELECT);
3803             int curSel;
3804
3805             curSel = SendMessageW(cb, CB_GETCURSEL, 0, 0);
3806             /* Actually, any index will do, since they all store the same
3807              * data value
3808              */
3809             data = (struct detail_data *)SendMessageW(cb, CB_GETITEMDATA,
3810              curSel, 0);
3811             show_edit_cert_properties_dialog(GetParent(hwnd), data);
3812             break;
3813         }
3814         case ((CBN_SELCHANGE << 16) | IDC_DETAIL_SELECT):
3815             refresh_details_view(hwnd);
3816             break;
3817         }
3818         break;
3819     case WM_REFRESH_VIEW:
3820         refresh_details_view(hwnd);
3821         break;
3822     }
3823     return 0;
3824 }
3825
3826 static UINT CALLBACK detail_callback(HWND hwnd, UINT msg,
3827  PROPSHEETPAGEW *page)
3828 {
3829     struct detail_data *data;
3830
3831     switch (msg)
3832     {
3833     case PSPCB_RELEASE:
3834         data = (struct detail_data *)page->lParam;
3835         free_detail_fields(data);
3836         HeapFree(GetProcessHeap(), 0, data);
3837         break;
3838     }
3839     return 0;
3840 }
3841
3842 static BOOL init_detail_page(PCCRYPTUI_VIEWCERTIFICATE_STRUCTW pCertViewInfo,
3843  BOOL *pfPropertiesChanged, PROPSHEETPAGEW *page)
3844 {
3845     BOOL ret;
3846     struct detail_data *data = HeapAlloc(GetProcessHeap(), 0,
3847      sizeof(struct detail_data));
3848
3849     if (data)
3850     {
3851         data->pCertViewInfo = pCertViewInfo;
3852         data->pfPropertiesChanged = pfPropertiesChanged;
3853         data->cFields = 0;
3854         data->fields = NULL;
3855         memset(page, 0, sizeof(PROPSHEETPAGEW));
3856         page->dwSize = sizeof(PROPSHEETPAGEW);
3857         page->dwFlags = PSP_USECALLBACK;
3858         page->pfnCallback = detail_callback;
3859         page->hInstance = hInstance;
3860         page->u.pszTemplate = MAKEINTRESOURCEW(IDD_DETAIL);
3861         page->pfnDlgProc = detail_dlg_proc;
3862         page->lParam = (LPARAM)data;
3863         ret = TRUE;
3864     }
3865     else
3866         ret = FALSE;
3867     return ret;
3868 }
3869
3870 struct hierarchy_data
3871 {
3872     PCCRYPTUI_VIEWCERTIFICATE_STRUCTW pCertViewInfo;
3873     HIMAGELIST imageList;
3874     DWORD selectedCert;
3875 };
3876
3877 static LPARAM index_to_lparam(struct hierarchy_data *data, DWORD index)
3878 {
3879     CRYPT_PROVIDER_SGNR *provSigner = WTHelperGetProvSignerFromChain(
3880      (CRYPT_PROVIDER_DATA *)data->pCertViewInfo->u.pCryptProviderData,
3881      data->pCertViewInfo->idxSigner, data->pCertViewInfo->fCounterSigner,
3882      data->pCertViewInfo->idxCounterSigner);
3883
3884     /* Takes advantage of the fact that a pointer is 32-bit aligned, and
3885      * therefore always even.
3886      */
3887     if (index == provSigner->csCertChain - 1)
3888         return (LPARAM)data;
3889     return index << 1 | 1;
3890 }
3891
3892 static inline DWORD lparam_to_index(struct hierarchy_data *data, LPARAM lp)
3893 {
3894     CRYPT_PROVIDER_SGNR *provSigner = WTHelperGetProvSignerFromChain(
3895      (CRYPT_PROVIDER_DATA *)data->pCertViewInfo->u.pCryptProviderData,
3896      data->pCertViewInfo->idxSigner, data->pCertViewInfo->fCounterSigner,
3897      data->pCertViewInfo->idxCounterSigner);
3898
3899     if (!(lp & 1))
3900         return provSigner->csCertChain - 1;
3901     return lp >> 1;
3902 }
3903
3904 static struct hierarchy_data *get_hierarchy_data_from_tree_item(HWND tree,
3905  HTREEITEM hItem)
3906 {
3907     struct hierarchy_data *data = NULL;
3908     HTREEITEM root = NULL;
3909
3910     do {
3911         HTREEITEM parent = (HTREEITEM)SendMessageW(tree, TVM_GETNEXTITEM,
3912          TVGN_PARENT, (LPARAM)hItem);
3913
3914         if (!parent)
3915             root = hItem;
3916         hItem = parent;
3917     } while (hItem);
3918     if (root)
3919     {
3920         TVITEMW item;
3921
3922         item.mask = TVIF_PARAM;
3923         item.hItem = root;
3924         SendMessageW(tree, TVM_GETITEMW, 0, (LPARAM)&item);
3925         data = (struct hierarchy_data *)item.lParam;
3926     }
3927     return data;
3928 }
3929
3930 static WCHAR *get_cert_display_name(PCCERT_CONTEXT cert)
3931 {
3932     WCHAR *name = get_cert_property_as_string(cert, CERT_FRIENDLY_NAME_PROP_ID);
3933
3934     if (!name)
3935         name = get_cert_name_string(cert, CERT_NAME_SIMPLE_DISPLAY_TYPE, 0);
3936     return name;
3937 }
3938
3939 static void show_cert_chain(HWND hwnd, struct hierarchy_data *data)
3940 {
3941     HWND tree = GetDlgItem(hwnd, IDC_CERTPATH);
3942     CRYPT_PROVIDER_SGNR *provSigner = WTHelperGetProvSignerFromChain(
3943      (CRYPT_PROVIDER_DATA *)data->pCertViewInfo->u.pCryptProviderData,
3944      data->pCertViewInfo->idxSigner, data->pCertViewInfo->fCounterSigner,
3945      data->pCertViewInfo->idxCounterSigner);
3946     DWORD i;
3947     HTREEITEM parent = NULL;
3948
3949     SendMessageW(tree, TVM_SETIMAGELIST, TVSIL_NORMAL, (LPARAM)data->imageList);
3950     for (i = provSigner->csCertChain; i; i--)
3951     {
3952         LPWSTR name;
3953
3954         name = get_cert_display_name(provSigner->pasCertChain[i - 1].pCert);
3955         if (name)
3956         {
3957             TVINSERTSTRUCTW tvis;
3958
3959             tvis.hParent = parent;
3960             tvis.hInsertAfter = TVI_LAST;
3961             tvis.u.item.mask = TVIF_TEXT | TVIF_STATE | TVIF_IMAGE |
3962              TVIF_SELECTEDIMAGE | TVIF_PARAM;
3963             tvis.u.item.pszText = name;
3964             tvis.u.item.state = TVIS_EXPANDED;
3965             tvis.u.item.stateMask = TVIS_EXPANDED;
3966             if (i == 1 &&
3967              (provSigner->pChainContext->TrustStatus.dwErrorStatus &
3968              CERT_TRUST_IS_PARTIAL_CHAIN))
3969             {
3970                 /* The root of the chain has a special case:  if the chain is
3971                  * a partial chain, the icon is a warning icon rather than an
3972                  * error icon.
3973                  */
3974                 tvis.u.item.iImage = 2;
3975             }
3976             else if (provSigner->pasCertChain[i - 1].pChainElement->TrustStatus.
3977              dwErrorStatus == 0)
3978                 tvis.u.item.iImage = 0;
3979             else
3980                 tvis.u.item.iImage = 1;
3981             tvis.u.item.iSelectedImage = tvis.u.item.iImage;
3982             tvis.u.item.lParam = index_to_lparam(data, i - 1);
3983             parent = (HTREEITEM)SendMessageW(tree, TVM_INSERTITEMW, 0,
3984              (LPARAM)&tvis);
3985             HeapFree(GetProcessHeap(), 0, name);
3986         }
3987     }
3988 }
3989
3990 static void set_certificate_status(HWND hwnd, CRYPT_PROVIDER_CERT *cert)
3991 {
3992     /* Select all the text in the control, the next update will replace it */
3993     SendMessageW(hwnd, EM_SETSEL, 0, -1);
3994     /* Set the highest priority error messages first. */
3995     if (!(cert->dwConfidence & CERT_CONFIDENCE_SIG))
3996         add_string_resource_to_control(hwnd, IDS_CERTIFICATE_BAD_SIGNATURE);
3997     else if (!(cert->dwConfidence & CERT_CONFIDENCE_TIME))
3998         add_string_resource_to_control(hwnd, IDS_CERTIFICATE_BAD_TIME);
3999     else if (!(cert->dwConfidence & CERT_CONFIDENCE_TIMENEST))
4000         add_string_resource_to_control(hwnd, IDS_CERTIFICATE_BAD_TIMENEST);
4001     else if (cert->dwRevokedReason)
4002         add_string_resource_to_control(hwnd, IDS_CERTIFICATE_REVOKED);
4003     else
4004         add_string_resource_to_control(hwnd, IDS_CERTIFICATE_VALID);
4005 }
4006
4007 static void set_certificate_status_for_end_cert(HWND hwnd,
4008  PCCRYPTUI_VIEWCERTIFICATE_STRUCTW pCertViewInfo)
4009 {
4010     HWND status = GetDlgItem(hwnd, IDC_CERTIFICATESTATUSTEXT);
4011     CRYPT_PROVIDER_SGNR *provSigner = WTHelperGetProvSignerFromChain(
4012      (CRYPT_PROVIDER_DATA *)pCertViewInfo->u.pCryptProviderData,
4013      pCertViewInfo->idxSigner, pCertViewInfo->fCounterSigner,
4014      pCertViewInfo->idxCounterSigner);
4015     CRYPT_PROVIDER_CERT *provCert = WTHelperGetProvCertFromChain(provSigner,
4016      pCertViewInfo->idxCert);
4017
4018     set_certificate_status(status, provCert);
4019 }
4020
4021 static void show_cert_hierarchy(HWND hwnd, struct hierarchy_data *data)
4022 {
4023     /* Disable view certificate button until a certificate is selected */
4024     EnableWindow(GetDlgItem(hwnd, IDC_VIEWCERTIFICATE), FALSE);
4025     show_cert_chain(hwnd, data);
4026     set_certificate_status_for_end_cert(hwnd, data->pCertViewInfo);
4027 }
4028
4029 static void show_dialog_for_selected_cert(HWND hwnd)
4030 {
4031     HWND tree = GetDlgItem(hwnd, IDC_CERTPATH);
4032     TVITEMW item;
4033     struct hierarchy_data *data;
4034     DWORD selection;
4035
4036     memset(&item, 0, sizeof(item));
4037     item.mask = TVIF_HANDLE | TVIF_PARAM;
4038     item.hItem = (HTREEITEM)SendMessageW(tree, TVM_GETNEXTITEM, TVGN_CARET,
4039      (LPARAM)NULL);
4040     SendMessageW(tree, TVM_GETITEMW, 0, (LPARAM)&item);
4041     data = get_hierarchy_data_from_tree_item(tree, item.hItem);
4042     selection = lparam_to_index(data, item.lParam);
4043     if (selection != 0)
4044     {
4045         CRYPT_PROVIDER_SGNR *provSigner;
4046         CRYPTUI_VIEWCERTIFICATE_STRUCTW viewInfo;
4047         BOOL changed = FALSE;
4048
4049         provSigner = WTHelperGetProvSignerFromChain(
4050          (CRYPT_PROVIDER_DATA *)data->pCertViewInfo->u.pCryptProviderData,
4051          data->pCertViewInfo->idxSigner,
4052          data->pCertViewInfo->fCounterSigner,
4053          data->pCertViewInfo->idxCounterSigner);
4054         memset(&viewInfo, 0, sizeof(viewInfo));
4055         viewInfo.dwSize = sizeof(viewInfo);
4056         viewInfo.dwFlags = data->pCertViewInfo->dwFlags;
4057         viewInfo.szTitle = data->pCertViewInfo->szTitle;
4058         viewInfo.pCertContext = provSigner->pasCertChain[selection].pCert;
4059         viewInfo.cStores = data->pCertViewInfo->cStores;
4060         viewInfo.rghStores = data->pCertViewInfo->rghStores;
4061         viewInfo.cPropSheetPages = data->pCertViewInfo->cPropSheetPages;
4062         viewInfo.rgPropSheetPages = data->pCertViewInfo->rgPropSheetPages;
4063         viewInfo.nStartPage = data->pCertViewInfo->nStartPage;
4064         CryptUIDlgViewCertificateW(&viewInfo, &changed);
4065         if (changed)
4066         {
4067             /* Delete the contents of the tree */
4068             SendMessageW(tree, TVM_DELETEITEM, 0, (LPARAM)TVI_ROOT);
4069             /* Reinitialize the tree */
4070             show_cert_hierarchy(hwnd, data);
4071         }
4072     }
4073 }
4074
4075 static LRESULT CALLBACK hierarchy_dlg_proc(HWND hwnd, UINT msg, WPARAM wp,
4076  LPARAM lp)
4077 {
4078     PROPSHEETPAGEW *page;
4079     struct hierarchy_data *data;
4080     LRESULT ret = 0;
4081     HWND tree = GetDlgItem(hwnd, IDC_CERTPATH);
4082
4083     TRACE("(%p, %08x, %08lx, %08lx)\n", hwnd, msg, wp, lp);
4084
4085     switch (msg)
4086     {
4087     case WM_INITDIALOG:
4088         page = (PROPSHEETPAGEW *)lp;
4089         data = (struct hierarchy_data *)page->lParam;
4090         show_cert_hierarchy(hwnd, data);
4091         break;
4092     case WM_NOTIFY:
4093     {
4094         NMHDR *hdr;
4095
4096         hdr = (NMHDR *)lp;
4097         switch (hdr->code)
4098         {
4099         case TVN_SELCHANGEDW:
4100         {
4101             NMTREEVIEWW *nm = (NMTREEVIEWW*)lp;
4102             DWORD selection;
4103             CRYPT_PROVIDER_SGNR *provSigner;
4104
4105             data = get_hierarchy_data_from_tree_item(tree, nm->itemNew.hItem);
4106             selection = lparam_to_index(data, nm->itemNew.lParam);
4107             provSigner = WTHelperGetProvSignerFromChain(
4108              (CRYPT_PROVIDER_DATA *)data->pCertViewInfo->u.pCryptProviderData,
4109              data->pCertViewInfo->idxSigner,
4110              data->pCertViewInfo->fCounterSigner,
4111              data->pCertViewInfo->idxCounterSigner);
4112             EnableWindow(GetDlgItem(hwnd, IDC_VIEWCERTIFICATE), selection != 0);
4113             set_certificate_status(GetDlgItem(hwnd, IDC_CERTIFICATESTATUSTEXT),
4114              &provSigner->pasCertChain[selection]);
4115             break;
4116         }
4117         case NM_DBLCLK:
4118             show_dialog_for_selected_cert(hwnd);
4119             SetWindowLongPtrW(hwnd, DWLP_MSGRESULT, 1);
4120             ret = 1;
4121             break;
4122         }
4123         break;
4124     }
4125     case WM_COMMAND:
4126         switch (wp)
4127         {
4128         case IDC_VIEWCERTIFICATE:
4129             show_dialog_for_selected_cert(hwnd);
4130             break;
4131         }
4132         break;
4133     case WM_REFRESH_VIEW:
4134     {
4135         TVITEMW item;
4136
4137         /* Get hierarchy data */
4138         memset(&item, 0, sizeof(item));
4139         item.mask = TVIF_HANDLE | TVIF_PARAM;
4140         item.hItem = (HTREEITEM)SendMessageW(tree, TVM_GETNEXTITEM, TVGN_ROOT,
4141          (LPARAM)NULL);
4142         data = get_hierarchy_data_from_tree_item(tree, item.hItem);
4143         /* Delete the contents of the tree */
4144         SendMessageW(tree, TVM_DELETEITEM, 0, (LPARAM)TVI_ROOT);
4145         /* Reinitialize the tree */
4146         show_cert_hierarchy(hwnd, data);
4147         break;
4148     }
4149     }
4150     return ret;
4151 }
4152
4153 static UINT CALLBACK hierarchy_callback(HWND hwnd, UINT msg,
4154  PROPSHEETPAGEW *page)
4155 {
4156     struct hierarchy_data *data;
4157
4158     switch (msg)
4159     {
4160     case PSPCB_RELEASE:
4161         data = (struct hierarchy_data *)page->lParam;
4162         ImageList_Destroy(data->imageList);
4163         HeapFree(GetProcessHeap(), 0, data);
4164         break;
4165     }
4166     return 0;
4167 }
4168
4169 static BOOL init_hierarchy_page(PCCRYPTUI_VIEWCERTIFICATE_STRUCTW pCertViewInfo,
4170  PROPSHEETPAGEW *page)
4171 {
4172     struct hierarchy_data *data = HeapAlloc(GetProcessHeap(), 0,
4173      sizeof(struct hierarchy_data));
4174     BOOL ret = FALSE;
4175
4176     if (data)
4177     {
4178         data->imageList = ImageList_Create(16, 16, ILC_COLOR4 | ILC_MASK, 2, 0);
4179         if (data->imageList)
4180         {
4181             HBITMAP bmp;
4182             COLORREF backColor = RGB(255, 0, 255);
4183
4184             data->pCertViewInfo = pCertViewInfo;
4185             data->selectedCert = 0xffffffff;
4186
4187             bmp = LoadBitmapW(hInstance, MAKEINTRESOURCEW(IDB_SMALL_ICONS));
4188             ImageList_AddMasked(data->imageList, bmp, backColor);
4189             DeleteObject(bmp);
4190             ImageList_SetBkColor(data->imageList, CLR_NONE);
4191
4192             memset(page, 0, sizeof(PROPSHEETPAGEW));
4193             page->dwSize = sizeof(PROPSHEETPAGEW);
4194             page->dwFlags = PSP_USECALLBACK;
4195             page->hInstance = hInstance;
4196             page->u.pszTemplate = MAKEINTRESOURCEW(IDD_HIERARCHY);
4197             page->pfnDlgProc = hierarchy_dlg_proc;
4198             page->lParam = (LPARAM)data;
4199             page->pfnCallback = hierarchy_callback;
4200             ret = TRUE;
4201         }
4202         else
4203             HeapFree(GetProcessHeap(), 0, data);
4204     }
4205     return ret;
4206 }
4207
4208 static int CALLBACK cert_prop_sheet_proc(HWND hwnd, UINT msg, LPARAM lp)
4209 {
4210     RECT rc;
4211     POINT topLeft;
4212
4213     TRACE("(%p, %08x, %08lx)\n", hwnd, msg, lp);
4214
4215     switch (msg)
4216     {
4217     case PSCB_INITIALIZED:
4218         /* Get cancel button's position.. */
4219         GetWindowRect(GetDlgItem(hwnd, IDCANCEL), &rc);
4220         topLeft.x = rc.left;
4221         topLeft.y = rc.top;
4222         ScreenToClient(hwnd, &topLeft);
4223         /* hide the cancel button.. */
4224         ShowWindow(GetDlgItem(hwnd, IDCANCEL), FALSE);
4225         /* get the OK button's size.. */
4226         GetWindowRect(GetDlgItem(hwnd, IDOK), &rc);
4227         /* and move the OK button to the cancel button's original position. */
4228         MoveWindow(GetDlgItem(hwnd, IDOK), topLeft.x, topLeft.y,
4229          rc.right - rc.left, rc.bottom - rc.top, FALSE);
4230         GetWindowRect(GetDlgItem(hwnd, IDOK), &rc);
4231         break;
4232     }
4233     return 0;
4234 }
4235
4236 static BOOL show_cert_dialog(PCCRYPTUI_VIEWCERTIFICATE_STRUCTW pCertViewInfo,
4237  CRYPT_PROVIDER_CERT *provCert, BOOL *pfPropertiesChanged)
4238 {
4239     static const WCHAR riched[] = { 'r','i','c','h','e','d','2','0',0 };
4240     DWORD nPages;
4241     PROPSHEETPAGEW *pages;
4242     BOOL ret = FALSE;
4243     HMODULE lib = LoadLibraryW(riched);
4244
4245     nPages = pCertViewInfo->cPropSheetPages + 1; /* one for the General tab */
4246     if (!(pCertViewInfo->dwFlags & CRYPTUI_HIDE_DETAILPAGE))
4247         nPages++;
4248     if (!(pCertViewInfo->dwFlags & CRYPTUI_HIDE_HIERARCHYPAGE))
4249         nPages++;
4250     pages = HeapAlloc(GetProcessHeap(), 0, nPages * sizeof(PROPSHEETPAGEW));
4251     if (pages)
4252     {
4253         PROPSHEETHEADERW hdr;
4254         CRYPTUI_INITDIALOG_STRUCT *init = NULL;
4255         DWORD i;
4256
4257         memset(&hdr, 0, sizeof(hdr));
4258         hdr.dwSize = sizeof(hdr);
4259         hdr.dwFlags = PSH_NOAPPLYNOW | PSH_PROPSHEETPAGE | PSH_USECALLBACK;
4260         hdr.hInstance = hInstance;
4261         if (pCertViewInfo->szTitle)
4262             hdr.pszCaption = pCertViewInfo->szTitle;
4263         else
4264             hdr.pszCaption = MAKEINTRESOURCEW(IDS_CERTIFICATE);
4265         init_general_page(pCertViewInfo, &pages[hdr.nPages++]);
4266         if (!(pCertViewInfo->dwFlags & CRYPTUI_HIDE_DETAILPAGE))
4267         {
4268             if (init_detail_page(pCertViewInfo, pfPropertiesChanged,
4269              &pages[hdr.nPages]))
4270                 hdr.nPages++;
4271         }
4272         if (!(pCertViewInfo->dwFlags & CRYPTUI_HIDE_HIERARCHYPAGE))
4273         {
4274             if (init_hierarchy_page(pCertViewInfo, &pages[hdr.nPages]))
4275                 hdr.nPages++;
4276         }
4277         /* Copy each additional page, and create the init dialog struct for it
4278          */
4279         if (pCertViewInfo->cPropSheetPages)
4280         {
4281             init = HeapAlloc(GetProcessHeap(), 0,
4282              pCertViewInfo->cPropSheetPages *
4283              sizeof(CRYPTUI_INITDIALOG_STRUCT));
4284             if (init)
4285             {
4286                 for (i = 0; i < pCertViewInfo->cPropSheetPages; i++)
4287                 {
4288                     memcpy(&pages[hdr.nPages + i],
4289                      &pCertViewInfo->rgPropSheetPages[i],
4290                      sizeof(PROPSHEETPAGEW));
4291                     init[i].lParam = pCertViewInfo->rgPropSheetPages[i].lParam;
4292                     init[i].pCertContext = pCertViewInfo->pCertContext;
4293                     pages[hdr.nPages + i].lParam = (LPARAM)&init[i];
4294                 }
4295                 if (pCertViewInfo->nStartPage & 0x8000)
4296                 {
4297                     /* Start page index is relative to the number of default
4298                      * pages
4299                      */
4300                     hdr.u2.nStartPage = pCertViewInfo->nStartPage + hdr.nPages;
4301                 }
4302                 else
4303                     hdr.u2.nStartPage = pCertViewInfo->nStartPage;
4304                 hdr.nPages = nPages;
4305                 ret = TRUE;
4306             }
4307             else
4308                 SetLastError(ERROR_OUTOFMEMORY);
4309         }
4310         else
4311         {
4312             /* Ignore the relative flag if there aren't any additional pages */
4313             hdr.u2.nStartPage = pCertViewInfo->nStartPage & 0x7fff;
4314             ret = TRUE;
4315         }
4316         if (ret)
4317         {
4318             INT_PTR l;
4319
4320             hdr.u3.ppsp = pages;
4321             hdr.pfnCallback = cert_prop_sheet_proc;
4322             l = PropertySheetW(&hdr);
4323             if (l == 0)
4324             {
4325                 SetLastError(ERROR_CANCELLED);
4326                 ret = FALSE;
4327             }
4328         }
4329         HeapFree(GetProcessHeap(), 0, init);
4330         HeapFree(GetProcessHeap(), 0, pages);
4331     }
4332     else
4333         SetLastError(ERROR_OUTOFMEMORY);
4334     FreeLibrary(lib);
4335     return ret;
4336 }
4337
4338 /***********************************************************************
4339  *              CryptUIDlgViewCertificateW (CRYPTUI.@)
4340  */
4341 BOOL WINAPI CryptUIDlgViewCertificateW(
4342  PCCRYPTUI_VIEWCERTIFICATE_STRUCTW pCertViewInfo, BOOL *pfPropertiesChanged)
4343 {
4344     static GUID generic_cert_verify = WINTRUST_ACTION_GENERIC_CERT_VERIFY;
4345     CRYPTUI_VIEWCERTIFICATE_STRUCTW viewInfo;
4346     WINTRUST_DATA wvt;
4347     WINTRUST_CERT_INFO cert;
4348     BOOL ret = FALSE;
4349     CRYPT_PROVIDER_SGNR *signer;
4350     CRYPT_PROVIDER_CERT *provCert = NULL;
4351
4352     TRACE("(%p, %p)\n", pCertViewInfo, pfPropertiesChanged);
4353
4354     if (pCertViewInfo->dwSize != sizeof(CRYPTUI_VIEWCERTIFICATE_STRUCTW))
4355     {
4356         SetLastError(ERROR_INVALID_PARAMETER);
4357         return FALSE;
4358     }
4359     /* Make a local copy in case we have to call WinVerifyTrust ourselves */
4360     memcpy(&viewInfo, pCertViewInfo, sizeof(viewInfo));
4361     if (!viewInfo.u.hWVTStateData)
4362     {
4363         memset(&wvt, 0, sizeof(wvt));
4364         wvt.cbStruct = sizeof(wvt);
4365         wvt.dwUIChoice = WTD_UI_NONE;
4366         if (viewInfo.dwFlags &
4367          CRYPTUI_ENABLE_REVOCATION_CHECK_CHAIN_EXCLUDE_ROOT)
4368             wvt.fdwRevocationChecks |= WTD_REVOCATION_CHECK_CHAIN_EXCLUDE_ROOT;
4369         if (viewInfo.dwFlags & CRYPTUI_ENABLE_REVOCATION_CHECK_END_CERT)
4370             wvt.fdwRevocationChecks |= WTD_REVOCATION_CHECK_END_CERT;
4371         if (viewInfo.dwFlags & CRYPTUI_ENABLE_REVOCATION_CHECK_CHAIN)
4372             wvt.fdwRevocationChecks |= WTD_REVOCATION_CHECK_CHAIN;
4373         wvt.dwUnionChoice = WTD_CHOICE_CERT;
4374         memset(&cert, 0, sizeof(cert));
4375         cert.cbStruct = sizeof(cert);
4376         cert.psCertContext = (CERT_CONTEXT *)viewInfo.pCertContext;
4377         cert.chStores = viewInfo.cStores;
4378         cert.pahStores = viewInfo.rghStores;
4379         wvt.u.pCert = &cert;
4380         wvt.dwStateAction = WTD_STATEACTION_VERIFY;
4381         WinVerifyTrust(NULL, &generic_cert_verify, &wvt);
4382         viewInfo.u.pCryptProviderData =
4383          WTHelperProvDataFromStateData(wvt.hWVTStateData);
4384         signer = WTHelperGetProvSignerFromChain(
4385          (CRYPT_PROVIDER_DATA *)viewInfo.u.pCryptProviderData, 0, FALSE, 0);
4386         provCert = WTHelperGetProvCertFromChain(signer, 0);
4387         ret = TRUE;
4388     }
4389     else
4390     {
4391         viewInfo.u.pCryptProviderData =
4392          WTHelperProvDataFromStateData(viewInfo.u.hWVTStateData);
4393         signer = WTHelperGetProvSignerFromChain(
4394          (CRYPT_PROVIDER_DATA *)viewInfo.u.pCryptProviderData,
4395          viewInfo.idxSigner, viewInfo.fCounterSigner,
4396          viewInfo.idxCounterSigner);
4397         provCert = WTHelperGetProvCertFromChain(signer, viewInfo.idxCert);
4398         ret = TRUE;
4399     }
4400     if (ret)
4401     {
4402         ret = show_cert_dialog(&viewInfo, provCert, pfPropertiesChanged);
4403         if (!viewInfo.u.hWVTStateData)
4404         {
4405             wvt.dwStateAction = WTD_STATEACTION_CLOSE;
4406             WinVerifyTrust(NULL, &generic_cert_verify, &wvt);
4407         }
4408     }
4409     return ret;
4410 }
4411
4412 /***********************************************************************
4413  *              CryptUIDlgViewContext (CRYPTUI.@)
4414  */
4415 BOOL WINAPI CryptUIDlgViewContext(DWORD dwContextType, LPVOID pvContext,
4416  HWND hwnd, LPCWSTR pwszTitle, DWORD dwFlags, LPVOID pvReserved)
4417 {
4418     BOOL ret;
4419
4420     TRACE("(%d, %p, %p, %s, %08x, %p)\n", dwContextType, pvContext, hwnd,
4421      debugstr_w(pwszTitle), dwFlags, pvReserved);
4422
4423     switch (dwContextType)
4424     {
4425     case CERT_STORE_CERTIFICATE_CONTEXT:
4426     {
4427         CRYPTUI_VIEWCERTIFICATE_STRUCTW viewInfo;
4428
4429         memset(&viewInfo, 0, sizeof(viewInfo));
4430         viewInfo.dwSize = sizeof(viewInfo);
4431         viewInfo.hwndParent = hwnd;
4432         viewInfo.szTitle = pwszTitle;
4433         viewInfo.pCertContext = pvContext;
4434         ret = CryptUIDlgViewCertificateW(&viewInfo, NULL);
4435         break;
4436     }
4437     default:
4438         FIXME("unimplemented for context type %d\n", dwContextType);
4439         SetLastError(E_INVALIDARG);
4440         ret = FALSE;
4441     }
4442     return ret;
4443 }
4444
4445 /* Decodes a cert's basic constraints extension (either szOID_BASIC_CONSTRAINTS
4446  * or szOID_BASIC_CONSTRAINTS2, whichever is present) to determine if it
4447  * should be a CA.  If neither extension is present, returns
4448  * defaultIfNotSpecified.
4449  */
4450 static BOOL is_ca_cert(PCCERT_CONTEXT cert, BOOL defaultIfNotSpecified)
4451 {
4452     BOOL isCA = defaultIfNotSpecified;
4453     PCERT_EXTENSION ext = CertFindExtension(szOID_BASIC_CONSTRAINTS,
4454      cert->pCertInfo->cExtension, cert->pCertInfo->rgExtension);
4455
4456     if (ext)
4457     {
4458         CERT_BASIC_CONSTRAINTS_INFO *info;
4459         DWORD size = 0;
4460
4461         if (CryptDecodeObjectEx(X509_ASN_ENCODING, szOID_BASIC_CONSTRAINTS,
4462          ext->Value.pbData, ext->Value.cbData, CRYPT_DECODE_ALLOC_FLAG,
4463          NULL, (LPBYTE)&info, &size))
4464         {
4465             if (info->SubjectType.cbData == 1)
4466                 isCA = info->SubjectType.pbData[0] & CERT_CA_SUBJECT_FLAG;
4467             LocalFree(info);
4468         }
4469     }
4470     else
4471     {
4472         ext = CertFindExtension(szOID_BASIC_CONSTRAINTS2,
4473          cert->pCertInfo->cExtension, cert->pCertInfo->rgExtension);
4474         if (ext)
4475         {
4476             CERT_BASIC_CONSTRAINTS2_INFO info;
4477             DWORD size = sizeof(CERT_BASIC_CONSTRAINTS2_INFO);
4478
4479             if (CryptDecodeObjectEx(X509_ASN_ENCODING,
4480              szOID_BASIC_CONSTRAINTS2, ext->Value.pbData, ext->Value.cbData,
4481              0, NULL, &info, &size))
4482                 isCA = info.fCA;
4483         }
4484     }
4485     return isCA;
4486 }
4487
4488 static HCERTSTORE choose_store_for_cert(PCCERT_CONTEXT cert)
4489 {
4490     LPCWSTR storeName;
4491
4492     if (is_ca_cert(cert, TRUE))
4493         storeName = ca;
4494     else
4495         storeName = addressBook;
4496     return CertOpenStore(CERT_STORE_PROV_SYSTEM_W, 0, 0,
4497      CERT_SYSTEM_STORE_CURRENT_USER, storeName);
4498 }
4499
4500 static BOOL import_cert(PCCERT_CONTEXT cert, HCERTSTORE hDestCertStore)
4501 {
4502     HCERTSTORE store;
4503     BOOL ret;
4504
4505     if (!cert)
4506     {
4507         SetLastError(E_INVALIDARG);
4508         return FALSE;
4509     }
4510     if (hDestCertStore) store = hDestCertStore;
4511     else
4512     {
4513         if (!(store = choose_store_for_cert(cert)))
4514         {
4515             WARN("unable to open certificate store\n");
4516             return FALSE;
4517         }
4518     }
4519     ret = CertAddCertificateContextToStore(store, cert,
4520      CERT_STORE_ADD_REPLACE_EXISTING_INHERIT_PROPERTIES, NULL);
4521     if (!hDestCertStore) CertCloseStore(store, 0);
4522     return ret;
4523 }
4524
4525 static BOOL import_crl(PCCRL_CONTEXT crl, HCERTSTORE hDestCertStore)
4526 {
4527     HCERTSTORE store;
4528     BOOL ret;
4529
4530     if (!crl)
4531     {
4532         SetLastError(E_INVALIDARG);
4533         return FALSE;
4534     }
4535     if (hDestCertStore) store = hDestCertStore;
4536     else
4537     {
4538         if (!(store = CertOpenStore(CERT_STORE_PROV_SYSTEM_W, 0, 0,
4539          CERT_SYSTEM_STORE_CURRENT_USER, ca)))
4540         {
4541             WARN("unable to open certificate store\n");
4542             return FALSE;
4543         }
4544     }
4545     ret = CertAddCRLContextToStore(store, crl,
4546      CERT_STORE_ADD_REPLACE_EXISTING_INHERIT_PROPERTIES, NULL);
4547     if (!hDestCertStore) CertCloseStore(store, 0);
4548     return ret;
4549 }
4550
4551 static BOOL import_ctl(PCCTL_CONTEXT ctl, HCERTSTORE hDestCertStore)
4552 {
4553     HCERTSTORE store;
4554     BOOL ret;
4555
4556     if (!ctl)
4557     {
4558         SetLastError(E_INVALIDARG);
4559         return FALSE;
4560     }
4561     if (hDestCertStore) store = hDestCertStore;
4562     else
4563     {
4564         static const WCHAR trust[] = { 'T','r','u','s','t',0 };
4565
4566         if (!(store = CertOpenStore(CERT_STORE_PROV_SYSTEM_W, 0, 0,
4567          CERT_SYSTEM_STORE_CURRENT_USER, trust)))
4568         {
4569             WARN("unable to open certificate store\n");
4570             return FALSE;
4571         }
4572     }
4573     ret = CertAddCTLContextToStore(store, ctl,
4574      CERT_STORE_ADD_REPLACE_EXISTING_INHERIT_PROPERTIES, NULL);
4575     if (!hDestCertStore) CertCloseStore(store, 0);
4576     return ret;
4577 }
4578
4579 /* Checks type, a type such as CERT_QUERY_CONTENT_CERT returned by
4580  * CryptQueryObject, against the allowed types.  Returns TRUE if the
4581  * type is allowed, FALSE otherwise.
4582  */
4583 static BOOL check_context_type(DWORD dwFlags, DWORD type)
4584 {
4585     BOOL ret;
4586
4587     if (dwFlags &
4588      (CRYPTUI_WIZ_IMPORT_ALLOW_CERT | CRYPTUI_WIZ_IMPORT_ALLOW_CRL |
4589      CRYPTUI_WIZ_IMPORT_ALLOW_CTL))
4590     {
4591         switch (type)
4592         {
4593         case CERT_QUERY_CONTENT_CERT:
4594         case CERT_QUERY_CONTENT_SERIALIZED_CERT:
4595             ret = dwFlags & CRYPTUI_WIZ_IMPORT_ALLOW_CERT;
4596             break;
4597         case CERT_QUERY_CONTENT_CRL:
4598         case CERT_QUERY_CONTENT_SERIALIZED_CRL:
4599             ret = dwFlags & CRYPTUI_WIZ_IMPORT_ALLOW_CRL;
4600             break;
4601         case CERT_QUERY_CONTENT_CTL:
4602         case CERT_QUERY_CONTENT_SERIALIZED_CTL:
4603             ret = dwFlags & CRYPTUI_WIZ_IMPORT_ALLOW_CTL;
4604             break;
4605         default:
4606             /* The remaining types contain more than one type, so allow
4607              * any combination.
4608              */
4609             ret = TRUE;
4610         }
4611     }
4612     else
4613     {
4614         /* No allowed types specified, so any type is allowed */
4615         ret = TRUE;
4616     }
4617     if (!ret)
4618         SetLastError(E_INVALIDARG);
4619     return ret;
4620 }
4621
4622
4623 static void import_warning(DWORD dwFlags, HWND hwnd, LPCWSTR szTitle,
4624  int warningID)
4625 {
4626     if (!(dwFlags & CRYPTUI_WIZ_NO_UI))
4627     {
4628         WCHAR title[MAX_STRING_LEN], error[MAX_STRING_LEN];
4629         LPCWSTR pTitle;
4630
4631         if (szTitle)
4632             pTitle = szTitle;
4633         else
4634         {
4635             LoadStringW(hInstance, IDS_IMPORT_WIZARD, title,
4636              sizeof(title) / sizeof(title[0]));
4637             pTitle = title;
4638         }
4639         LoadStringW(hInstance, warningID, error,
4640          sizeof(error) / sizeof(error[0]));
4641         MessageBoxW(hwnd, error, pTitle, MB_ICONERROR | MB_OK);
4642     }
4643 }
4644
4645 static void import_warn_type_mismatch(DWORD dwFlags, HWND hwnd, LPCWSTR szTitle)
4646 {
4647     import_warning(dwFlags, hwnd, szTitle, IDS_IMPORT_TYPE_MISMATCH);
4648 }
4649
4650 static BOOL check_store_context_type(DWORD dwFlags, HCERTSTORE store)
4651 {
4652     BOOL ret;
4653
4654     if (dwFlags &
4655      (CRYPTUI_WIZ_IMPORT_ALLOW_CERT | CRYPTUI_WIZ_IMPORT_ALLOW_CRL |
4656      CRYPTUI_WIZ_IMPORT_ALLOW_CTL))
4657     {
4658         PCCERT_CONTEXT cert;
4659         PCCRL_CONTEXT crl;
4660         PCCTL_CONTEXT ctl;
4661
4662         ret = TRUE;
4663         if ((cert = CertEnumCertificatesInStore(store, NULL)))
4664         {
4665             CertFreeCertificateContext(cert);
4666             if (!(dwFlags & CRYPTUI_WIZ_IMPORT_ALLOW_CERT))
4667                 ret = FALSE;
4668         }
4669         if (ret && (crl = CertEnumCRLsInStore(store, NULL)))
4670         {
4671             CertFreeCRLContext(crl);
4672             if (!(dwFlags & CRYPTUI_WIZ_IMPORT_ALLOW_CRL))
4673                 ret = FALSE;
4674         }
4675         if (ret && (ctl = CertEnumCTLsInStore(store, NULL)))
4676         {
4677             CertFreeCTLContext(ctl);
4678             if (!(dwFlags & CRYPTUI_WIZ_IMPORT_ALLOW_CTL))
4679                 ret = FALSE;
4680         }
4681     }
4682     else
4683         ret = TRUE;
4684     if (!ret)
4685         SetLastError(E_INVALIDARG);
4686     return ret;
4687 }
4688
4689 static BOOL import_store(DWORD dwFlags, HWND hwnd, LPCWSTR szTitle,
4690  HCERTSTORE source, HCERTSTORE dest)
4691 {
4692     BOOL ret;
4693
4694     if ((ret = check_store_context_type(dwFlags, source)))
4695     {
4696         PCCERT_CONTEXT cert = NULL;
4697         PCCRL_CONTEXT crl = NULL;
4698         PCCTL_CONTEXT ctl = NULL;
4699
4700         do {
4701             cert = CertEnumCertificatesInStore(source, cert);
4702             if (cert)
4703                 ret = import_cert(cert, dest);
4704         } while (ret && cert);
4705         do {
4706             crl = CertEnumCRLsInStore(source, crl);
4707             if (crl)
4708                 ret = import_crl(crl, dest);
4709         } while (ret && crl);
4710         do {
4711             ctl = CertEnumCTLsInStore(source, ctl);
4712             if (ctl)
4713                 ret = import_ctl(ctl, dest);
4714         } while (ret && ctl);
4715     }
4716     else
4717         import_warn_type_mismatch(dwFlags, hwnd, szTitle);
4718     return ret;
4719 }
4720
4721 static HCERTSTORE open_store_from_file(DWORD dwFlags, LPCWSTR fileName,
4722  DWORD *pContentType)
4723 {
4724     HCERTSTORE store = NULL;
4725     DWORD contentType = 0, expectedContentTypeFlags;
4726
4727     if (dwFlags &
4728      (CRYPTUI_WIZ_IMPORT_ALLOW_CERT | CRYPTUI_WIZ_IMPORT_ALLOW_CRL |
4729      CRYPTUI_WIZ_IMPORT_ALLOW_CTL))
4730     {
4731         expectedContentTypeFlags =
4732          CERT_QUERY_CONTENT_FLAG_SERIALIZED_STORE |
4733          CERT_QUERY_CONTENT_FLAG_PKCS7_SIGNED |
4734          CERT_QUERY_CONTENT_FLAG_PFX;
4735         if (dwFlags & CRYPTUI_WIZ_IMPORT_ALLOW_CERT)
4736             expectedContentTypeFlags |=
4737              CERT_QUERY_CONTENT_FLAG_CERT |
4738              CERT_QUERY_CONTENT_FLAG_SERIALIZED_CERT;
4739         if (dwFlags & CRYPTUI_WIZ_IMPORT_ALLOW_CRL)
4740             expectedContentTypeFlags |=
4741              CERT_QUERY_CONTENT_FLAG_SERIALIZED_CRL |
4742              CERT_QUERY_CONTENT_FLAG_CRL;
4743         if (dwFlags & CRYPTUI_WIZ_IMPORT_ALLOW_CTL)
4744             expectedContentTypeFlags |=
4745              CERT_QUERY_CONTENT_FLAG_CTL |
4746              CERT_QUERY_CONTENT_FLAG_SERIALIZED_CTL;
4747     }
4748     else
4749         expectedContentTypeFlags =
4750          CERT_QUERY_CONTENT_FLAG_CERT |
4751          CERT_QUERY_CONTENT_FLAG_CTL |
4752          CERT_QUERY_CONTENT_FLAG_CRL |
4753          CERT_QUERY_CONTENT_FLAG_SERIALIZED_STORE |
4754          CERT_QUERY_CONTENT_FLAG_SERIALIZED_CERT |
4755          CERT_QUERY_CONTENT_FLAG_SERIALIZED_CTL |
4756          CERT_QUERY_CONTENT_FLAG_SERIALIZED_CRL |
4757          CERT_QUERY_CONTENT_FLAG_PKCS7_SIGNED |
4758          CERT_QUERY_CONTENT_FLAG_PFX;
4759
4760     CryptQueryObject(CERT_QUERY_OBJECT_FILE, fileName,
4761      expectedContentTypeFlags, CERT_QUERY_FORMAT_FLAG_ALL, 0, NULL,
4762      &contentType, NULL, &store, NULL, NULL);
4763     if (pContentType)
4764         *pContentType = contentType;
4765     return store;
4766 }
4767
4768 static BOOL import_file(DWORD dwFlags, HWND hwnd, LPCWSTR szTitle,
4769  LPCWSTR fileName, HCERTSTORE dest)
4770 {
4771     HCERTSTORE source;
4772     BOOL ret;
4773
4774     if ((source = open_store_from_file(dwFlags, fileName, NULL)))
4775     {
4776         ret = import_store(dwFlags, hwnd, szTitle, source, dest);
4777         CertCloseStore(source, 0);
4778     }
4779     else
4780         ret = FALSE;
4781     return ret;
4782 }
4783
4784 struct ImportWizData
4785 {
4786     HFONT titleFont;
4787     DWORD dwFlags;
4788     LPCWSTR pwszWizardTitle;
4789     CRYPTUI_WIZ_IMPORT_SRC_INFO importSrc;
4790     LPWSTR fileName;
4791     DWORD contentType;
4792     BOOL freeSource;
4793     HCERTSTORE hDestCertStore;
4794     BOOL freeDest;
4795     BOOL autoDest;
4796     BOOL success;
4797 };
4798
4799 static LRESULT CALLBACK import_welcome_dlg_proc(HWND hwnd, UINT msg, WPARAM wp,
4800  LPARAM lp)
4801 {
4802     LRESULT ret = 0;
4803
4804     switch (msg)
4805     {
4806     case WM_INITDIALOG:
4807     {
4808         struct ImportWizData *data;
4809         PROPSHEETPAGEW *page = (PROPSHEETPAGEW *)lp;
4810         WCHAR fontFace[MAX_STRING_LEN];
4811         HDC hDC = GetDC(hwnd);
4812         int height;
4813
4814         data = (struct ImportWizData *)page->lParam;
4815         LoadStringW(hInstance, IDS_WIZARD_TITLE_FONT, fontFace,
4816          sizeof(fontFace) / sizeof(fontFace[0]));
4817         height = -MulDiv(12, GetDeviceCaps(hDC, LOGPIXELSY), 72);
4818         data->titleFont = CreateFontW(height, 0, 0, 0, FW_BOLD, 0, 0, 0,
4819          DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS,
4820          DEFAULT_QUALITY, DEFAULT_PITCH | FF_DONTCARE, fontFace);
4821         SendMessageW(GetDlgItem(hwnd, IDC_IMPORT_TITLE), WM_SETFONT,
4822          (WPARAM)data->titleFont, TRUE);
4823         ReleaseDC(hwnd, hDC);
4824         break;
4825     }
4826     case WM_NOTIFY:
4827     {
4828         NMHDR *hdr = (NMHDR *)lp;
4829
4830         switch (hdr->code)
4831         {
4832         case PSN_SETACTIVE:
4833             PostMessageW(GetParent(hwnd), PSM_SETWIZBUTTONS, 0, PSWIZB_NEXT);
4834             ret = TRUE;
4835             break;
4836         }
4837         break;
4838     }
4839     }
4840     return ret;
4841 }
4842
4843 static const WCHAR filter_cert[] = { '*','.','c','e','r',';','*','.',
4844  'c','r','t',0 };
4845 static const WCHAR filter_pfx[] = { '*','.','p','f','x',';','*','.',
4846  'p','1','2',0 };
4847 static const WCHAR filter_crl[] = { '*','.','c','r','l',0 };
4848 static const WCHAR filter_ctl[] = { '*','.','s','t','l',0 };
4849 static const WCHAR filter_serialized_store[] = { '*','.','s','s','t',0 };
4850 static const WCHAR filter_cms[] = { '*','.','s','p','c',';','*','.',
4851  'p','7','b',0 };
4852 static const WCHAR filter_all[] = { '*','.','*',0 };
4853
4854 struct StringToFilter
4855 {
4856     int     id;
4857     DWORD   allowFlags;
4858     LPCWSTR filter;
4859 } import_filters[] = {
4860  { IDS_IMPORT_FILTER_CERT, CRYPTUI_WIZ_IMPORT_ALLOW_CERT, filter_cert },
4861  { IDS_IMPORT_FILTER_PFX, 0, filter_pfx },
4862  { IDS_IMPORT_FILTER_CRL, CRYPTUI_WIZ_IMPORT_ALLOW_CRL, filter_crl },
4863  { IDS_IMPORT_FILTER_CTL, CRYPTUI_WIZ_IMPORT_ALLOW_CTL, filter_ctl },
4864  { IDS_IMPORT_FILTER_SERIALIZED_STORE, 0, filter_serialized_store },
4865  { IDS_IMPORT_FILTER_CMS, 0, filter_cms },
4866  { IDS_IMPORT_FILTER_ALL, 0, filter_all },
4867 };
4868
4869 static WCHAR *make_import_file_filter(DWORD dwFlags)
4870 {
4871     DWORD i;
4872     int len, totalLen = 2;
4873     LPWSTR filter = NULL, str;
4874
4875     for (i = 0; i < sizeof(import_filters) / sizeof(import_filters[0]); i++)
4876     {
4877         if (!import_filters[i].allowFlags || !dwFlags ||
4878          (dwFlags & import_filters[i].allowFlags))
4879         {
4880             len = LoadStringW(hInstance, import_filters[i].id, (LPWSTR)&str, 0);
4881             totalLen += len + strlenW(import_filters[i].filter) + 2;
4882         }
4883     }
4884     filter = HeapAlloc(GetProcessHeap(), 0, totalLen * sizeof(WCHAR));
4885     if (filter)
4886     {
4887         LPWSTR ptr;
4888
4889         ptr = filter;
4890         for (i = 0; i < sizeof(import_filters) / sizeof(import_filters[0]); i++)
4891         {
4892             if (!import_filters[i].allowFlags || !dwFlags ||
4893              (dwFlags & import_filters[i].allowFlags))
4894             {
4895                 len = LoadStringW(hInstance, import_filters[i].id,
4896                  (LPWSTR)&str, 0);
4897                 memcpy(ptr, str, len * sizeof(WCHAR));
4898                 ptr += len;
4899                 *ptr++ = 0;
4900                 strcpyW(ptr, import_filters[i].filter);
4901                 ptr += strlenW(import_filters[i].filter) + 1;
4902             }
4903         }
4904         *ptr++ = 0;
4905     }
4906     return filter;
4907 }
4908
4909 static BOOL import_validate_filename(HWND hwnd, struct ImportWizData *data,
4910  LPCWSTR fileName)
4911 {
4912     HANDLE file;
4913     BOOL ret = FALSE;
4914
4915     file = CreateFileW(fileName, GENERIC_READ, FILE_SHARE_READ, NULL,
4916      OPEN_EXISTING, 0, NULL);
4917     if (file != INVALID_HANDLE_VALUE)
4918     {
4919         HCERTSTORE source = open_store_from_file(data->dwFlags, fileName,
4920          &data->contentType);
4921         int warningID = 0;
4922
4923         if (!source)
4924             warningID = IDS_IMPORT_BAD_FORMAT;
4925         else if (!check_store_context_type(data->dwFlags, source))
4926             warningID = IDS_IMPORT_TYPE_MISMATCH;
4927         else
4928         {
4929             data->importSrc.dwSubjectChoice =
4930              CRYPTUI_WIZ_IMPORT_SUBJECT_CERT_STORE;
4931             data->importSrc.u.hCertStore = source;
4932             data->freeSource = TRUE;
4933             ret = TRUE;
4934         }
4935         if (warningID)
4936         {
4937             import_warning(data->dwFlags, hwnd, data->pwszWizardTitle,
4938              warningID);
4939         }
4940         CloseHandle(file);
4941     }
4942     else
4943     {
4944         WCHAR title[MAX_STRING_LEN], error[MAX_STRING_LEN];
4945         LPCWSTR pTitle;
4946         LPWSTR msgBuf, fullError;
4947
4948         if (data->pwszWizardTitle)
4949             pTitle = data->pwszWizardTitle;
4950         else
4951         {
4952             LoadStringW(hInstance, IDS_IMPORT_WIZARD, title,
4953              sizeof(title) / sizeof(title[0]));
4954             pTitle = title;
4955         }
4956         LoadStringW(hInstance, IDS_IMPORT_OPEN_FAILED, error,
4957          sizeof(error) / sizeof(error[0]));
4958         FormatMessageW(
4959          FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, NULL,
4960          GetLastError(), 0, (LPWSTR) &msgBuf, 0, NULL);
4961         fullError = HeapAlloc(GetProcessHeap(), 0,
4962          (strlenW(error) + strlenW(fileName) + strlenW(msgBuf) + 3)
4963          * sizeof(WCHAR));
4964         if (fullError)
4965         {
4966             LPWSTR ptr = fullError;
4967
4968             strcpyW(ptr, error);
4969             ptr += strlenW(error);
4970             strcpyW(ptr, fileName);
4971             ptr += strlenW(fileName);
4972             *ptr++ = ':';
4973             *ptr++ = '\n';
4974             strcpyW(ptr, msgBuf);
4975             MessageBoxW(hwnd, fullError, pTitle, MB_ICONERROR | MB_OK);
4976             HeapFree(GetProcessHeap(), 0, fullError);
4977         }
4978         LocalFree(msgBuf);
4979     }
4980     return ret;
4981 }
4982
4983 static LRESULT CALLBACK import_file_dlg_proc(HWND hwnd, UINT msg, WPARAM wp,
4984  LPARAM lp)
4985 {
4986     LRESULT ret = 0;
4987     struct ImportWizData *data;
4988
4989     switch (msg)
4990     {
4991     case WM_INITDIALOG:
4992     {
4993         PROPSHEETPAGEW *page = (PROPSHEETPAGEW *)lp;
4994
4995         data = (struct ImportWizData *)page->lParam;
4996         SetWindowLongPtrW(hwnd, DWLP_USER, (LPARAM)data);
4997         break;
4998     }
4999     case WM_NOTIFY:
5000     {
5001         NMHDR *hdr = (NMHDR *)lp;
5002
5003         switch (hdr->code)
5004         {
5005         case PSN_SETACTIVE:
5006             PostMessageW(GetParent(hwnd), PSM_SETWIZBUTTONS, 0,
5007              PSWIZB_BACK | PSWIZB_NEXT);
5008             ret = TRUE;
5009             break;
5010         case PSN_WIZNEXT:
5011         {
5012             HWND fileNameEdit = GetDlgItem(hwnd, IDC_IMPORT_FILENAME);
5013             DWORD len = SendMessageW(fileNameEdit, WM_GETTEXTLENGTH, 0, 0);
5014
5015             data = (struct ImportWizData *)GetWindowLongPtrW(hwnd, DWLP_USER);
5016             if (!len)
5017             {
5018                 import_warning(data->dwFlags, hwnd, data->pwszWizardTitle,
5019                  IDS_IMPORT_EMPTY_FILE);
5020                 SetWindowLongPtrW(hwnd, DWLP_MSGRESULT, 1);
5021                 ret = 1;
5022             }
5023             else
5024             {
5025                 LPWSTR fileName = HeapAlloc(GetProcessHeap(), 0,
5026                  (len + 1) * sizeof(WCHAR));
5027
5028                 if (fileName)
5029                 {
5030                     SendMessageW(fileNameEdit, WM_GETTEXT, len + 1,
5031                      (LPARAM)fileName);
5032                     if (!import_validate_filename(hwnd, data, fileName))
5033                     {
5034                         HeapFree(GetProcessHeap(), 0, fileName);
5035                         SetWindowLongPtrW(hwnd, DWLP_MSGRESULT, 1);
5036                         ret = 1;
5037                     }
5038                     else
5039                         data->fileName = fileName;
5040                 }
5041             }
5042             break;
5043         }
5044         }
5045         break;
5046     }
5047     case WM_COMMAND:
5048         switch (wp)
5049         {
5050         case IDC_IMPORT_BROWSE_FILE:
5051         {
5052             OPENFILENAMEW ofn;
5053             WCHAR fileBuf[MAX_PATH];
5054
5055             data = (struct ImportWizData *)GetWindowLongPtrW(hwnd, DWLP_USER);
5056             memset(&ofn, 0, sizeof(ofn));
5057             ofn.lStructSize = sizeof(ofn);
5058             ofn.hwndOwner = hwnd;
5059             ofn.lpstrFilter = make_import_file_filter(data->dwFlags);
5060             ofn.lpstrFile = fileBuf;
5061             ofn.nMaxFile = sizeof(fileBuf) / sizeof(fileBuf[0]);
5062             fileBuf[0] = 0;
5063             if (GetOpenFileNameW(&ofn))
5064                 SendMessageW(GetDlgItem(hwnd, IDC_IMPORT_FILENAME), WM_SETTEXT,
5065                  0, (LPARAM)ofn.lpstrFile);
5066             HeapFree(GetProcessHeap(), 0, (LPWSTR)ofn.lpstrFilter);
5067             break;
5068         }
5069         }
5070         break;
5071     }
5072     return ret;
5073 }
5074
5075 static LRESULT CALLBACK import_store_dlg_proc(HWND hwnd, UINT msg, WPARAM wp,
5076  LPARAM lp)
5077 {
5078     LRESULT ret = 0;
5079     struct ImportWizData *data;
5080
5081     switch (msg)
5082     {
5083     case WM_INITDIALOG:
5084     {
5085         PROPSHEETPAGEW *page = (PROPSHEETPAGEW *)lp;
5086
5087         data = (struct ImportWizData *)page->lParam;
5088         SetWindowLongPtrW(hwnd, DWLP_USER, (LPARAM)data);
5089         if (!data->hDestCertStore)
5090         {
5091             SendMessageW(GetDlgItem(hwnd, IDC_IMPORT_AUTO_STORE), BM_CLICK,
5092              0, 0);
5093             EnableWindow(GetDlgItem(hwnd, IDC_IMPORT_STORE), FALSE);
5094             EnableWindow(GetDlgItem(hwnd, IDC_IMPORT_BROWSE_STORE), FALSE);
5095             EnableWindow(GetDlgItem(hwnd, IDC_IMPORT_SPECIFY_STORE), FALSE);
5096         }
5097         else
5098         {
5099             WCHAR storeTitle[MAX_STRING_LEN];
5100
5101             SendMessageW(GetDlgItem(hwnd, IDC_IMPORT_SPECIFY_STORE), BM_CLICK,
5102              0, 0);
5103             EnableWindow(GetDlgItem(hwnd, IDC_IMPORT_STORE), TRUE);
5104             EnableWindow(GetDlgItem(hwnd, IDC_IMPORT_BROWSE_STORE), TRUE);
5105             EnableWindow(GetDlgItem(hwnd, IDC_IMPORT_SPECIFY_STORE),
5106              !(data->dwFlags & CRYPTUI_WIZ_IMPORT_NO_CHANGE_DEST_STORE));
5107             LoadStringW(hInstance, IDS_IMPORT_DEST_DETERMINED,
5108              storeTitle, sizeof(storeTitle) / sizeof(storeTitle[0]));
5109             SendMessageW(GetDlgItem(hwnd, IDC_IMPORT_STORE), WM_SETTEXT,
5110              0, (LPARAM)storeTitle);
5111         }
5112         break;
5113     }
5114     case WM_NOTIFY:
5115     {
5116         NMHDR *hdr = (NMHDR *)lp;
5117
5118         switch (hdr->code)
5119         {
5120         case PSN_SETACTIVE:
5121             PostMessageW(GetParent(hwnd), PSM_SETWIZBUTTONS, 0,
5122              PSWIZB_BACK | PSWIZB_NEXT);
5123             ret = TRUE;
5124             break;
5125         case PSN_WIZNEXT:
5126         {
5127             data = (struct ImportWizData *)GetWindowLongPtrW(hwnd, DWLP_USER);
5128             if (IsDlgButtonChecked(hwnd, IDC_IMPORT_SPECIFY_STORE) &&
5129              !data->hDestCertStore)
5130             {
5131                 import_warning(data->dwFlags, hwnd, data->pwszWizardTitle,
5132                  IDS_IMPORT_SELECT_STORE);
5133                 SetWindowLongPtrW(hwnd, DWLP_MSGRESULT, 1);
5134                 ret = 1;
5135             }
5136             break;
5137         }
5138         }
5139         break;
5140     }
5141     case WM_COMMAND:
5142         switch (wp)
5143         {
5144         case IDC_IMPORT_AUTO_STORE:
5145             data = (struct ImportWizData *)GetWindowLongPtrW(hwnd, DWLP_USER);
5146             data->autoDest = TRUE;
5147             EnableWindow(GetDlgItem(hwnd, IDC_IMPORT_STORE), FALSE);
5148             EnableWindow(GetDlgItem(hwnd, IDC_IMPORT_BROWSE_STORE), FALSE);
5149             break;
5150         case IDC_IMPORT_SPECIFY_STORE:
5151             data = (struct ImportWizData *)GetWindowLongPtrW(hwnd, DWLP_USER);
5152             data->autoDest = FALSE;
5153             EnableWindow(GetDlgItem(hwnd, IDC_IMPORT_STORE), TRUE);
5154             EnableWindow(GetDlgItem(hwnd, IDC_IMPORT_BROWSE_STORE), TRUE);
5155             break;
5156         case IDC_IMPORT_BROWSE_STORE:
5157         {
5158             CRYPTUI_ENUM_SYSTEM_STORE_ARGS enumArgs = {
5159              CERT_SYSTEM_STORE_CURRENT_USER, NULL };
5160             CRYPTUI_ENUM_DATA enumData = { 0, NULL, 1, &enumArgs };
5161             CRYPTUI_SELECTSTORE_INFO_W selectInfo;
5162             HCERTSTORE store;
5163
5164             data = (struct ImportWizData *)GetWindowLongPtrW(hwnd, DWLP_USER);
5165             selectInfo.dwSize = sizeof(selectInfo);
5166             selectInfo.parent = hwnd;
5167             selectInfo.dwFlags = CRYPTUI_ENABLE_SHOW_PHYSICAL_STORE;
5168             selectInfo.pwszTitle = selectInfo.pwszTitle = NULL;
5169             selectInfo.pEnumData = &enumData;
5170             selectInfo.pfnSelectedStoreCallback = NULL;
5171             if ((store = CryptUIDlgSelectStoreW(&selectInfo)))
5172             {
5173                 WCHAR storeTitle[MAX_STRING_LEN];
5174
5175                 LoadStringW(hInstance, IDS_IMPORT_DEST_DETERMINED,
5176                  storeTitle, sizeof(storeTitle) / sizeof(storeTitle[0]));
5177                 SendMessageW(GetDlgItem(hwnd, IDC_IMPORT_STORE), WM_SETTEXT,
5178                  0, (LPARAM)storeTitle);
5179                 data->hDestCertStore = store;
5180                 data->freeDest = TRUE;
5181             }
5182             break;
5183         }
5184         }
5185         break;
5186     }
5187     return ret;
5188 }
5189
5190 static void show_import_details(HWND lv, struct ImportWizData *data)
5191 {
5192     WCHAR text[MAX_STRING_LEN];
5193     LVITEMW item;
5194     int contentID;
5195
5196     item.mask = LVIF_TEXT;
5197     item.iItem = SendMessageW(lv, LVM_GETITEMCOUNT, 0, 0);
5198     item.iSubItem = 0;
5199     LoadStringW(hInstance, IDS_IMPORT_STORE_SELECTION, text,
5200      sizeof(text)/ sizeof(text[0]));
5201     item.pszText = text;
5202     SendMessageW(lv, LVM_INSERTITEMW, 0, (LPARAM)&item);
5203     item.iSubItem = 1;
5204     if (data->autoDest)
5205         LoadStringW(hInstance, IDS_IMPORT_DEST_AUTOMATIC, text,
5206          sizeof(text)/ sizeof(text[0]));
5207     else
5208         LoadStringW(hInstance, IDS_IMPORT_DEST_DETERMINED, text,
5209          sizeof(text)/ sizeof(text[0]));
5210     SendMessageW(lv, LVM_SETITEMTEXTW, item.iItem, (LPARAM)&item);
5211     item.iItem = SendMessageW(lv, LVM_GETITEMCOUNT, 0, 0);
5212     item.iSubItem = 0;
5213     LoadStringW(hInstance, IDS_IMPORT_CONTENT, text,
5214      sizeof(text)/ sizeof(text[0]));
5215     SendMessageW(lv, LVM_INSERTITEMW, 0, (LPARAM)&item);
5216     switch (data->contentType)
5217     {
5218     case CERT_QUERY_CONTENT_CERT:
5219     case CERT_QUERY_CONTENT_SERIALIZED_CERT:
5220         contentID = IDS_IMPORT_CONTENT_CERT;
5221         break;
5222     case CERT_QUERY_CONTENT_CRL:
5223     case CERT_QUERY_CONTENT_SERIALIZED_CRL:
5224         contentID = IDS_IMPORT_CONTENT_CRL;
5225         break;
5226     case CERT_QUERY_CONTENT_CTL:
5227     case CERT_QUERY_CONTENT_SERIALIZED_CTL:
5228         contentID = IDS_IMPORT_CONTENT_CTL;
5229         break;
5230     case CERT_QUERY_CONTENT_PKCS7_SIGNED:
5231         contentID = IDS_IMPORT_CONTENT_CMS;
5232         break;
5233     case CERT_QUERY_CONTENT_FLAG_PFX:
5234         contentID = IDS_IMPORT_CONTENT_PFX;
5235         break;
5236     default:
5237         contentID = IDS_IMPORT_CONTENT_STORE;
5238         break;
5239     }
5240     LoadStringW(hInstance, contentID, text, sizeof(text)/ sizeof(text[0]));
5241     item.iSubItem = 1;
5242     SendMessageW(lv, LVM_SETITEMTEXTW, item.iItem, (LPARAM)&item);
5243     if (data->fileName)
5244     {
5245         item.iItem = SendMessageW(lv, LVM_GETITEMCOUNT, 0, 0);
5246         item.iSubItem = 0;
5247         LoadStringW(hInstance, IDS_IMPORT_FILE, text,
5248          sizeof(text)/ sizeof(text[0]));
5249         SendMessageW(lv, LVM_INSERTITEMW, 0, (LPARAM)&item);
5250         item.iSubItem = 1;
5251         item.pszText = data->fileName;
5252         SendMessageW(lv, LVM_SETITEMTEXTW, item.iItem, (LPARAM)&item);
5253     }
5254 }
5255
5256 static BOOL do_import(DWORD dwFlags, HWND hwndParent, LPCWSTR pwszWizardTitle,
5257  PCCRYPTUI_WIZ_IMPORT_SRC_INFO pImportSrc, HCERTSTORE hDestCertStore)
5258 {
5259     BOOL ret;
5260
5261     switch (pImportSrc->dwSubjectChoice)
5262     {
5263     case CRYPTUI_WIZ_IMPORT_SUBJECT_FILE:
5264         ret = import_file(dwFlags, hwndParent, pwszWizardTitle,
5265          pImportSrc->u.pwszFileName, hDestCertStore);
5266         break;
5267     case CRYPTUI_WIZ_IMPORT_SUBJECT_CERT_CONTEXT:
5268         if ((ret = check_context_type(dwFlags, CERT_QUERY_CONTENT_CERT)))
5269             ret = import_cert(pImportSrc->u.pCertContext, hDestCertStore);
5270         else
5271             import_warn_type_mismatch(dwFlags, hwndParent, pwszWizardTitle);
5272         break;
5273     case CRYPTUI_WIZ_IMPORT_SUBJECT_CRL_CONTEXT:
5274         if ((ret = check_context_type(dwFlags, CERT_QUERY_CONTENT_CRL)))
5275             ret = import_crl(pImportSrc->u.pCRLContext, hDestCertStore);
5276         else
5277             import_warn_type_mismatch(dwFlags, hwndParent, pwszWizardTitle);
5278         break;
5279     case CRYPTUI_WIZ_IMPORT_SUBJECT_CTL_CONTEXT:
5280         if ((ret = check_context_type(dwFlags, CERT_QUERY_CONTENT_CTL)))
5281             ret = import_ctl(pImportSrc->u.pCTLContext, hDestCertStore);
5282         else
5283             import_warn_type_mismatch(dwFlags, hwndParent, pwszWizardTitle);
5284         break;
5285     case CRYPTUI_WIZ_IMPORT_SUBJECT_CERT_STORE:
5286         ret = import_store(dwFlags, hwndParent, pwszWizardTitle,
5287          pImportSrc->u.hCertStore, hDestCertStore);
5288         break;
5289     default:
5290         WARN("unknown source type: %u\n", pImportSrc->dwSubjectChoice);
5291         SetLastError(E_INVALIDARG);
5292         ret = FALSE;
5293     }
5294     return ret;
5295 }
5296
5297 static LRESULT CALLBACK import_finish_dlg_proc(HWND hwnd, UINT msg, WPARAM wp,
5298  LPARAM lp)
5299 {
5300     LRESULT ret = 0;
5301     struct ImportWizData *data;
5302
5303     switch (msg)
5304     {
5305     case WM_INITDIALOG:
5306     {
5307         PROPSHEETPAGEW *page = (PROPSHEETPAGEW *)lp;
5308         HWND lv = GetDlgItem(hwnd, IDC_IMPORT_SETTINGS);
5309         RECT rc;
5310         LVCOLUMNW column;
5311
5312         data = (struct ImportWizData *)page->lParam;
5313         SetWindowLongPtrW(hwnd, DWLP_USER, (LPARAM)data);
5314         SendMessageW(GetDlgItem(hwnd, IDC_IMPORT_TITLE), WM_SETFONT,
5315          (WPARAM)data->titleFont, TRUE);
5316         GetWindowRect(lv, &rc);
5317         column.mask = LVCF_WIDTH;
5318         column.cx = (rc.right - rc.left) / 2 - 2;
5319         SendMessageW(lv, LVM_INSERTCOLUMNW, 0, (LPARAM)&column);
5320         SendMessageW(lv, LVM_INSERTCOLUMNW, 1, (LPARAM)&column);
5321         show_import_details(lv, data);
5322         break;
5323     }
5324     case WM_NOTIFY:
5325     {
5326         NMHDR *hdr = (NMHDR *)lp;
5327
5328         switch (hdr->code)
5329         {
5330         case PSN_SETACTIVE:
5331         {
5332             HWND lv = GetDlgItem(hwnd, IDC_IMPORT_SETTINGS);
5333
5334             data = (struct ImportWizData *)GetWindowLongPtrW(hwnd, DWLP_USER);
5335             SendMessageW(lv, LVM_DELETEALLITEMS, 0, 0);
5336             show_import_details(lv, data);
5337             PostMessageW(GetParent(hwnd), PSM_SETWIZBUTTONS, 0,
5338              PSWIZB_BACK | PSWIZB_FINISH);
5339             ret = TRUE;
5340             break;
5341         }
5342         case PSN_WIZFINISH:
5343         {
5344             data = (struct ImportWizData *)GetWindowLongPtrW(hwnd, DWLP_USER);
5345             if ((data->success = do_import(data->dwFlags, hwnd,
5346              data->pwszWizardTitle, &data->importSrc, data->hDestCertStore)))
5347             {
5348                 WCHAR title[MAX_STRING_LEN], message[MAX_STRING_LEN];
5349                 LPCWSTR pTitle;
5350
5351                 if (data->pwszWizardTitle)
5352                     pTitle = data->pwszWizardTitle;
5353                 else
5354                 {
5355                     LoadStringW(hInstance, IDS_IMPORT_WIZARD, title,
5356                      sizeof(title) / sizeof(title[0]));
5357                     pTitle = title;
5358                 }
5359                 LoadStringW(hInstance, IDS_IMPORT_SUCCEEDED, message,
5360                  sizeof(message) / sizeof(message[0]));
5361                 MessageBoxW(hwnd, message, pTitle, MB_OK);
5362             }
5363             else
5364                 import_warning(data->dwFlags, hwnd, data->pwszWizardTitle,
5365                  IDS_IMPORT_FAILED);
5366             break;
5367         }
5368         }
5369         break;
5370     }
5371     }
5372     return ret;
5373 }
5374
5375 static BOOL show_import_ui(DWORD dwFlags, HWND hwndParent,
5376  LPCWSTR pwszWizardTitle, PCCRYPTUI_WIZ_IMPORT_SRC_INFO pImportSrc,
5377  HCERTSTORE hDestCertStore)
5378 {
5379     PROPSHEETHEADERW hdr;
5380     PROPSHEETPAGEW pages[4];
5381     struct ImportWizData data;
5382     int nPages = 0;
5383
5384     data.dwFlags = dwFlags;
5385     data.pwszWizardTitle = pwszWizardTitle;
5386     if (pImportSrc)
5387         memcpy(&data.importSrc, pImportSrc, sizeof(data.importSrc));
5388     else
5389         memset(&data.importSrc, 0, sizeof(data.importSrc));
5390     data.fileName = NULL;
5391     data.freeSource = FALSE;
5392     data.hDestCertStore = hDestCertStore;
5393     data.freeDest = FALSE;
5394     data.autoDest = TRUE;
5395     data.success = TRUE;
5396
5397     memset(&pages, 0, sizeof(pages));
5398
5399     pages[nPages].dwSize = sizeof(pages[0]);
5400     pages[nPages].hInstance = hInstance;
5401     pages[nPages].u.pszTemplate = MAKEINTRESOURCEW(IDD_IMPORT_WELCOME);
5402     pages[nPages].pfnDlgProc = import_welcome_dlg_proc;
5403     pages[nPages].dwFlags = PSP_HIDEHEADER;
5404     pages[nPages].lParam = (LPARAM)&data;
5405     nPages++;
5406
5407     if (!pImportSrc ||
5408      pImportSrc->dwSubjectChoice == CRYPTUI_WIZ_IMPORT_SUBJECT_FILE)
5409     {
5410         pages[nPages].dwSize = sizeof(pages[0]);
5411         pages[nPages].hInstance = hInstance;
5412         pages[nPages].u.pszTemplate = MAKEINTRESOURCEW(IDD_IMPORT_FILE);
5413         pages[nPages].pfnDlgProc = import_file_dlg_proc;
5414         pages[nPages].dwFlags = PSP_USEHEADERTITLE | PSP_USEHEADERSUBTITLE;
5415         pages[nPages].pszHeaderTitle = MAKEINTRESOURCEW(IDS_IMPORT_FILE_TITLE);
5416         pages[nPages].pszHeaderSubTitle =
5417          MAKEINTRESOURCEW(IDS_IMPORT_FILE_SUBTITLE);
5418         pages[nPages].lParam = (LPARAM)&data;
5419         nPages++;
5420     }
5421     else
5422     {
5423         switch (pImportSrc->dwSubjectChoice)
5424         {
5425         case CRYPTUI_WIZ_IMPORT_SUBJECT_CERT_CONTEXT:
5426             data.contentType = CERT_QUERY_CONTENT_CERT;
5427             break;
5428         case CRYPTUI_WIZ_IMPORT_SUBJECT_CRL_CONTEXT:
5429             data.contentType = CERT_QUERY_CONTENT_CRL;
5430             break;
5431         case CRYPTUI_WIZ_IMPORT_SUBJECT_CTL_CONTEXT:
5432             data.contentType = CERT_QUERY_CONTENT_CTL;
5433             break;
5434         case CRYPTUI_WIZ_IMPORT_SUBJECT_CERT_STORE:
5435             data.contentType = CERT_QUERY_CONTENT_SERIALIZED_STORE;
5436             break;
5437         }
5438     }
5439
5440     pages[nPages].dwSize = sizeof(pages[0]);
5441     pages[nPages].hInstance = hInstance;
5442     pages[nPages].u.pszTemplate = MAKEINTRESOURCEW(IDD_IMPORT_STORE);
5443     pages[nPages].pfnDlgProc = import_store_dlg_proc;
5444     pages[nPages].dwFlags = PSP_USEHEADERTITLE | PSP_USEHEADERSUBTITLE;
5445     pages[nPages].pszHeaderTitle = MAKEINTRESOURCEW(IDS_IMPORT_STORE_TITLE);
5446     pages[nPages].pszHeaderSubTitle =
5447      MAKEINTRESOURCEW(IDS_IMPORT_STORE_SUBTITLE);
5448     pages[nPages].lParam = (LPARAM)&data;
5449     nPages++;
5450
5451     pages[nPages].dwSize = sizeof(pages[0]);
5452     pages[nPages].hInstance = hInstance;
5453     pages[nPages].u.pszTemplate = MAKEINTRESOURCEW(IDD_IMPORT_FINISH);
5454     pages[nPages].pfnDlgProc = import_finish_dlg_proc;
5455     pages[nPages].dwFlags = PSP_HIDEHEADER;
5456     pages[nPages].lParam = (LPARAM)&data;
5457     nPages++;
5458
5459     memset(&hdr, 0, sizeof(hdr));
5460     hdr.dwSize = sizeof(hdr);
5461     hdr.hwndParent = hwndParent;
5462     hdr.dwFlags = PSH_PROPSHEETPAGE | PSH_WIZARD97_NEW | PSH_HEADER |
5463      PSH_WATERMARK;
5464     hdr.hInstance = hInstance;
5465     if (pwszWizardTitle)
5466         hdr.pszCaption = pwszWizardTitle;
5467     else
5468         hdr.pszCaption = MAKEINTRESOURCEW(IDS_IMPORT_WIZARD);
5469     hdr.u3.ppsp = pages;
5470     hdr.nPages = nPages;
5471     hdr.u4.pszbmWatermark = MAKEINTRESOURCEW(IDB_CERT_WATERMARK);
5472     hdr.u5.pszbmHeader = MAKEINTRESOURCEW(IDB_CERT_HEADER);
5473     PropertySheetW(&hdr);
5474     HeapFree(GetProcessHeap(), 0, data.fileName);
5475     if (data.freeSource &&
5476      data.importSrc.dwSubjectChoice == CRYPTUI_WIZ_IMPORT_SUBJECT_CERT_STORE)
5477         CertCloseStore(data.importSrc.u.hCertStore, 0);
5478     DeleteObject(data.titleFont);
5479     return data.success;
5480 }
5481
5482 BOOL WINAPI CryptUIWizImport(DWORD dwFlags, HWND hwndParent, LPCWSTR pwszWizardTitle,
5483                              PCCRYPTUI_WIZ_IMPORT_SRC_INFO pImportSrc, HCERTSTORE hDestCertStore)
5484 {
5485     BOOL ret;
5486
5487     TRACE("(0x%08x, %p, %s, %p, %p)\n", dwFlags, hwndParent, debugstr_w(pwszWizardTitle),
5488           pImportSrc, hDestCertStore);
5489
5490     if (pImportSrc &&
5491      pImportSrc->dwSize != sizeof(CRYPTUI_WIZ_IMPORT_SRC_INFO))
5492     {
5493         SetLastError(E_INVALIDARG);
5494         return FALSE;
5495     }
5496
5497     if (!(dwFlags & CRYPTUI_WIZ_NO_UI))
5498         ret = show_import_ui(dwFlags, hwndParent, pwszWizardTitle, pImportSrc,
5499          hDestCertStore);
5500     else if (pImportSrc)
5501         ret = do_import(dwFlags, hwndParent, pwszWizardTitle, pImportSrc,
5502          hDestCertStore);
5503     else
5504     {
5505         /* Can't have no UI without specifying source */
5506         SetLastError(E_INVALIDARG);
5507         ret = FALSE;
5508     }
5509
5510     return ret;
5511 }
5512
5513 struct ExportWizData
5514 {
5515     HFONT titleFont;
5516     DWORD dwFlags;
5517     LPCWSTR pwszWizardTitle;
5518     CRYPTUI_WIZ_EXPORT_INFO exportInfo;
5519     CRYPTUI_WIZ_EXPORT_CERTCONTEXT_INFO contextInfo;
5520     BOOL freePassword;
5521     PCRYPT_KEY_PROV_INFO keyProvInfo;
5522     LPWSTR fileName;
5523     HANDLE file;
5524     BOOL success;
5525 };
5526
5527 static LRESULT CALLBACK export_welcome_dlg_proc(HWND hwnd, UINT msg, WPARAM wp,
5528  LPARAM lp)
5529 {
5530     LRESULT ret = 0;
5531
5532     switch (msg)
5533     {
5534     case WM_INITDIALOG:
5535     {
5536         struct ExportWizData *data;
5537         PROPSHEETPAGEW *page = (PROPSHEETPAGEW *)lp;
5538         WCHAR fontFace[MAX_STRING_LEN];
5539         HDC hDC = GetDC(hwnd);
5540         int height;
5541
5542         data = (struct ExportWizData *)page->lParam;
5543         LoadStringW(hInstance, IDS_WIZARD_TITLE_FONT, fontFace,
5544          sizeof(fontFace) / sizeof(fontFace[0]));
5545         height = -MulDiv(12, GetDeviceCaps(hDC, LOGPIXELSY), 72);
5546         data->titleFont = CreateFontW(height, 0, 0, 0, FW_BOLD, 0, 0, 0,
5547          DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS,
5548          DEFAULT_QUALITY, DEFAULT_PITCH | FF_DONTCARE, fontFace);
5549         SendMessageW(GetDlgItem(hwnd, IDC_EXPORT_TITLE), WM_SETFONT,
5550          (WPARAM)data->titleFont, TRUE);
5551         ReleaseDC(hwnd, hDC);
5552         break;
5553     }
5554     case WM_NOTIFY:
5555     {
5556         NMHDR *hdr = (NMHDR *)lp;
5557
5558         switch (hdr->code)
5559         {
5560         case PSN_SETACTIVE:
5561             PostMessageW(GetParent(hwnd), PSM_SETWIZBUTTONS, 0, PSWIZB_NEXT);
5562             ret = TRUE;
5563             break;
5564         }
5565         break;
5566     }
5567     }
5568     return ret;
5569 }
5570
5571 static PCRYPT_KEY_PROV_INFO export_get_private_key_info(PCCERT_CONTEXT cert)
5572 {
5573     PCRYPT_KEY_PROV_INFO info = NULL;
5574     DWORD size;
5575
5576     if (CertGetCertificateContextProperty(cert, CERT_KEY_PROV_INFO_PROP_ID,
5577      NULL, &size))
5578     {
5579         info = HeapAlloc(GetProcessHeap(), 0, size);
5580         if (info)
5581         {
5582             if (!CertGetCertificateContextProperty(cert,
5583              CERT_KEY_PROV_INFO_PROP_ID, info, &size))
5584             {
5585                 HeapFree(GetProcessHeap(), 0, info);
5586                 info = NULL;
5587             }
5588         }
5589     }
5590     return info;
5591 }
5592
5593 static BOOL export_acquire_private_key(PCRYPT_KEY_PROV_INFO info,
5594  HCRYPTPROV *phProv)
5595 {
5596     BOOL ret;
5597
5598     ret = CryptAcquireContextW(phProv, info->pwszContainerName,
5599      info->pwszProvName, info->dwProvType, 0);
5600     if (ret)
5601     {
5602         DWORD i;
5603
5604         for (i = 0; i < info->cProvParam; i++)
5605             CryptSetProvParam(*phProv, info->rgProvParam[i].dwParam,
5606              info->rgProvParam[i].pbData, info->rgProvParam[i].dwFlags);
5607     }
5608     return ret;
5609 }
5610
5611 static BOOL export_is_key_exportable(HCRYPTPROV hProv, DWORD keySpec)
5612 {
5613     BOOL ret;
5614     HCRYPTKEY key;
5615
5616     if ((ret = CryptGetUserKey(hProv, keySpec, &key)))
5617     {
5618         DWORD permissions, size = sizeof(permissions);
5619
5620         if ((ret = CryptGetKeyParam(key, KP_PERMISSIONS, (BYTE *)&permissions,
5621          &size, 0)) && !(permissions & CRYPT_EXPORT))
5622             ret = FALSE;
5623         CryptDestroyKey(key);
5624     }
5625     return ret;
5626 }
5627
5628 static LRESULT CALLBACK export_private_key_dlg_proc(HWND hwnd, UINT msg,
5629  WPARAM wp, LPARAM lp)
5630 {
5631     LRESULT ret = 0;
5632     struct ExportWizData *data;
5633
5634     switch (msg)
5635     {
5636     case WM_INITDIALOG:
5637     {
5638         PROPSHEETPAGEW *page = (PROPSHEETPAGEW *)lp;
5639         PCRYPT_KEY_PROV_INFO info;
5640         HCRYPTPROV hProv = 0;
5641         int errorID = 0;
5642
5643         data = (struct ExportWizData *)page->lParam;
5644         SetWindowLongPtrW(hwnd, DWLP_USER, (LPARAM)data);
5645         /* Get enough information about a key to see whether it's exportable.
5646          */
5647         if (!(info = export_get_private_key_info(
5648          data->exportInfo.u.pCertContext)))
5649             errorID = IDS_EXPORT_PRIVATE_KEY_UNAVAILABLE;
5650         else if (!export_acquire_private_key(info, &hProv))
5651             errorID = IDS_EXPORT_PRIVATE_KEY_UNAVAILABLE;
5652         else if (!export_is_key_exportable(hProv, info->dwKeySpec))
5653             errorID = IDS_EXPORT_PRIVATE_KEY_NON_EXPORTABLE;
5654
5655         if (errorID)
5656         {
5657             WCHAR error[MAX_STRING_LEN];
5658
5659             LoadStringW(hInstance, errorID, error,
5660              sizeof(error) / sizeof(error[0]));
5661             SendMessageW(GetDlgItem(hwnd, IDC_EXPORT_PRIVATE_KEY_UNAVAILABLE),
5662              WM_SETTEXT, 0, (LPARAM)error);
5663             EnableWindow(GetDlgItem(hwnd, IDC_EXPORT_PRIVATE_KEY_YES), FALSE);
5664         }
5665         else
5666             data->keyProvInfo = info;
5667         if (hProv)
5668             CryptReleaseContext(hProv, 0);
5669         SendMessageW(GetDlgItem(hwnd, IDC_EXPORT_PRIVATE_KEY_NO), BM_CLICK,
5670          0, 0);
5671         break;
5672     }
5673     case WM_NOTIFY:
5674     {
5675         NMHDR *hdr = (NMHDR *)lp;
5676
5677         switch (hdr->code)
5678         {
5679         case PSN_SETACTIVE:
5680             PostMessageW(GetParent(hwnd), PSM_SETWIZBUTTONS, 0,
5681              PSWIZB_BACK | PSWIZB_NEXT);
5682             ret = TRUE;
5683             break;
5684         case PSN_WIZNEXT:
5685             data = (struct ExportWizData *)GetWindowLongPtrW(hwnd, DWLP_USER);
5686             if (IsDlgButtonChecked(hwnd, IDC_EXPORT_PRIVATE_KEY_NO))
5687             {
5688                 data->contextInfo.dwExportFormat =
5689                  CRYPTUI_WIZ_EXPORT_FORMAT_DER;
5690                 data->contextInfo.fExportPrivateKeys = FALSE;
5691             }
5692             else
5693             {
5694                 data->contextInfo.dwExportFormat =
5695                  CRYPTUI_WIZ_EXPORT_FORMAT_PFX;
5696                 data->contextInfo.fExportPrivateKeys = TRUE;
5697             }
5698             break;
5699         }
5700         break;
5701     }
5702     }
5703     return ret;
5704 }
5705
5706 static BOOL export_info_has_private_key(PCCRYPTUI_WIZ_EXPORT_INFO pExportInfo)
5707 {
5708     BOOL ret = FALSE;
5709
5710     if (pExportInfo->dwSubjectChoice == CRYPTUI_WIZ_EXPORT_CERT_CONTEXT)
5711     {
5712         DWORD size;
5713
5714         /* If there's a CRYPT_KEY_PROV_INFO set for this cert, assume the
5715          * cert has a private key.
5716          */
5717         if (CertGetCertificateContextProperty(pExportInfo->u.pCertContext,
5718          CERT_KEY_PROV_INFO_PROP_ID, NULL, &size))
5719             ret = TRUE;
5720     }
5721     return ret;
5722 }
5723
5724 static void export_format_enable_controls(HWND hwnd, struct ExportWizData *data)
5725 {
5726     int defaultFormatID;
5727
5728     switch (data->contextInfo.dwExportFormat)
5729     {
5730     case CRYPTUI_WIZ_EXPORT_FORMAT_BASE64:
5731         defaultFormatID = IDC_EXPORT_FORMAT_BASE64;
5732         break;
5733     case CRYPTUI_WIZ_EXPORT_FORMAT_PKCS7:
5734         defaultFormatID = IDC_EXPORT_FORMAT_CMS;
5735         break;
5736     case CRYPTUI_WIZ_EXPORT_FORMAT_PFX:
5737         defaultFormatID = IDC_EXPORT_FORMAT_PFX;
5738         break;
5739     default:
5740         defaultFormatID = IDC_EXPORT_FORMAT_DER;
5741     }
5742     SendMessageW(GetDlgItem(hwnd, defaultFormatID), BM_CLICK, 0, 0);
5743     if (defaultFormatID == IDC_EXPORT_FORMAT_PFX)
5744     {
5745         EnableWindow(GetDlgItem(hwnd, IDC_EXPORT_FORMAT_DER), FALSE);
5746         EnableWindow(GetDlgItem(hwnd, IDC_EXPORT_FORMAT_BASE64), FALSE);
5747         EnableWindow(GetDlgItem(hwnd, IDC_EXPORT_FORMAT_CMS), FALSE);
5748         EnableWindow(GetDlgItem(hwnd, IDC_EXPORT_FORMAT_PFX), TRUE);
5749     }
5750     else
5751     {
5752         EnableWindow(GetDlgItem(hwnd, IDC_EXPORT_FORMAT_DER), TRUE);
5753         EnableWindow(GetDlgItem(hwnd, IDC_EXPORT_FORMAT_BASE64), TRUE);
5754         EnableWindow(GetDlgItem(hwnd, IDC_EXPORT_FORMAT_CMS), TRUE);
5755         EnableWindow(GetDlgItem(hwnd, IDC_EXPORT_FORMAT_PFX), FALSE);
5756     }
5757 }
5758
5759 static LRESULT CALLBACK export_format_dlg_proc(HWND hwnd, UINT msg, WPARAM wp,
5760  LPARAM lp)
5761 {
5762     LRESULT ret = 0;
5763     struct ExportWizData *data;
5764
5765     switch (msg)
5766     {
5767     case WM_INITDIALOG:
5768     {
5769         PROPSHEETPAGEW *page = (PROPSHEETPAGEW *)lp;
5770
5771         data = (struct ExportWizData *)page->lParam;
5772         SetWindowLongPtrW(hwnd, DWLP_USER, (LPARAM)data);
5773         export_format_enable_controls(hwnd, data);
5774         break;
5775     }
5776     case WM_NOTIFY:
5777     {
5778         NMHDR *hdr = (NMHDR *)lp;
5779
5780         switch (hdr->code)
5781         {
5782         case PSN_SETACTIVE:
5783             PostMessageW(GetParent(hwnd), PSM_SETWIZBUTTONS, 0,
5784              PSWIZB_BACK | PSWIZB_NEXT);
5785             data = (struct ExportWizData *)GetWindowLongPtrW(hwnd, DWLP_USER);
5786             export_format_enable_controls(hwnd, data);
5787             ret = TRUE;
5788             break;
5789         case PSN_WIZNEXT:
5790         {
5791             BOOL skipPasswordPage = TRUE;
5792
5793             data = (struct ExportWizData *)GetWindowLongPtrW(hwnd, DWLP_USER);
5794             if (IsDlgButtonChecked(hwnd, IDC_EXPORT_FORMAT_DER))
5795                 data->contextInfo.dwExportFormat =
5796                  CRYPTUI_WIZ_EXPORT_FORMAT_DER;
5797             else if (IsDlgButtonChecked(hwnd, IDC_EXPORT_FORMAT_BASE64))
5798                 data->contextInfo.dwExportFormat =
5799                  CRYPTUI_WIZ_EXPORT_FORMAT_BASE64;
5800             else if (IsDlgButtonChecked(hwnd, IDC_EXPORT_FORMAT_CMS))
5801             {
5802                 data->contextInfo.dwExportFormat =
5803                  CRYPTUI_WIZ_EXPORT_FORMAT_PKCS7;
5804                 if (IsDlgButtonChecked(hwnd, IDC_EXPORT_CMS_INCLUDE_CHAIN))
5805                     data->contextInfo.fExportChain =
5806                      CRYPTUI_WIZ_EXPORT_FORMAT_PKCS7;
5807             }
5808             else
5809             {
5810                 data->contextInfo.dwExportFormat =
5811                  CRYPTUI_WIZ_EXPORT_FORMAT_PFX;
5812                 if (IsDlgButtonChecked(hwnd, IDC_EXPORT_PFX_INCLUDE_CHAIN))
5813                     data->contextInfo.fExportChain = TRUE;
5814                 if (IsDlgButtonChecked(hwnd, IDC_EXPORT_PFX_STRONG_ENCRYPTION))
5815                     data->contextInfo.fStrongEncryption = TRUE;
5816                 if (IsDlgButtonChecked(hwnd, IDC_EXPORT_PFX_DELETE_PRIVATE_KEY))
5817                     data->contextInfo.fExportPrivateKeys = TRUE;
5818                 skipPasswordPage = FALSE;
5819             }
5820             SetWindowLongPtrW(hwnd, DWLP_MSGRESULT,
5821              skipPasswordPage ? IDD_EXPORT_FILE : 0);
5822             ret = 1;
5823             break;
5824         }
5825         }
5826         break;
5827     }
5828     case WM_COMMAND:
5829         switch (HIWORD(wp))
5830         {
5831         case BN_CLICKED:
5832             switch (LOWORD(wp))
5833             {
5834             case IDC_EXPORT_FORMAT_DER:
5835             case IDC_EXPORT_FORMAT_BASE64:
5836                 EnableWindow(GetDlgItem(hwnd, IDC_EXPORT_CMS_INCLUDE_CHAIN),
5837                  FALSE);
5838                 EnableWindow(GetDlgItem(hwnd, IDC_EXPORT_PFX_INCLUDE_CHAIN),
5839                  FALSE);
5840                 EnableWindow(GetDlgItem(hwnd, IDC_EXPORT_PFX_STRONG_ENCRYPTION),
5841                  FALSE);
5842                 EnableWindow(GetDlgItem(hwnd,
5843                  IDC_EXPORT_PFX_DELETE_PRIVATE_KEY), FALSE);
5844                 break;
5845             case IDC_EXPORT_FORMAT_CMS:
5846                 EnableWindow(GetDlgItem(hwnd, IDC_EXPORT_CMS_INCLUDE_CHAIN),
5847                  TRUE);
5848                 break;
5849             case IDC_EXPORT_FORMAT_PFX:
5850                 EnableWindow(GetDlgItem(hwnd, IDC_EXPORT_PFX_INCLUDE_CHAIN),
5851                  TRUE);
5852                 EnableWindow(GetDlgItem(hwnd, IDC_EXPORT_PFX_STRONG_ENCRYPTION),
5853                  TRUE);
5854                 EnableWindow(GetDlgItem(hwnd,
5855                  IDC_EXPORT_PFX_DELETE_PRIVATE_KEY), TRUE);
5856                 break;
5857             }
5858             break;
5859         }
5860         break;
5861     }
5862     return ret;
5863 }
5864
5865 static void export_password_mismatch(HWND hwnd, struct ExportWizData *data)
5866 {
5867     WCHAR title[MAX_STRING_LEN], error[MAX_STRING_LEN];
5868     LPCWSTR pTitle;
5869
5870     if (data->pwszWizardTitle)
5871         pTitle = data->pwszWizardTitle;
5872     else
5873     {
5874         LoadStringW(hInstance, IDS_EXPORT_WIZARD, title,
5875          sizeof(title) / sizeof(title[0]));
5876         pTitle = title;
5877     }
5878     LoadStringW(hInstance, IDS_EXPORT_PASSWORD_MISMATCH, error,
5879      sizeof(error) / sizeof(error[0]));
5880     MessageBoxW(hwnd, error, pTitle, MB_ICONERROR | MB_OK);
5881     SetFocus(GetDlgItem(hwnd, IDC_EXPORT_PASSWORD));
5882 }
5883
5884 static LRESULT CALLBACK export_password_dlg_proc(HWND hwnd, UINT msg,
5885  WPARAM wp, LPARAM lp)
5886 {
5887     LRESULT ret = 0;
5888     struct ExportWizData *data;
5889
5890     switch (msg)
5891     {
5892     case WM_INITDIALOG:
5893     {
5894         PROPSHEETPAGEW *page = (PROPSHEETPAGEW *)lp;
5895
5896         data = (struct ExportWizData *)page->lParam;
5897         SetWindowLongPtrW(hwnd, DWLP_USER, (LPARAM)data);
5898         break;
5899     }
5900     case WM_NOTIFY:
5901     {
5902         NMHDR *hdr = (NMHDR *)lp;
5903
5904         switch (hdr->code)
5905         {
5906         case PSN_SETACTIVE:
5907             PostMessageW(GetParent(hwnd), PSM_SETWIZBUTTONS, 0,
5908              PSWIZB_BACK | PSWIZB_NEXT);
5909             ret = TRUE;
5910             break;
5911         case PSN_WIZNEXT:
5912         {
5913             HWND passwordEdit = GetDlgItem(hwnd, IDC_EXPORT_PASSWORD);
5914             HWND passwordConfirmEdit = GetDlgItem(hwnd,
5915              IDC_EXPORT_PASSWORD_CONFIRM);
5916             DWORD passwordLen = SendMessageW(passwordEdit, WM_GETTEXTLENGTH,
5917              0, 0);
5918             DWORD passwordConfirmLen = SendMessageW(passwordConfirmEdit,
5919              WM_GETTEXTLENGTH, 0, 0);
5920
5921             data = (struct ExportWizData *)GetWindowLongPtrW(hwnd, DWLP_USER);
5922             if (!passwordLen && !passwordConfirmLen)
5923                 data->contextInfo.pwszPassword = NULL;
5924             else if (passwordLen != passwordConfirmLen)
5925             {
5926                 export_password_mismatch(hwnd, data);
5927                 SetWindowLongPtrW(hwnd, DWLP_MSGRESULT, 1);
5928                 ret = 1;
5929             }
5930             else
5931             {
5932                 LPWSTR password = HeapAlloc(GetProcessHeap(), 0,
5933                  (passwordLen + 1) * sizeof(WCHAR));
5934                 LPWSTR passwordConfirm = HeapAlloc(GetProcessHeap(), 0,
5935                  (passwordConfirmLen + 1) * sizeof(WCHAR));
5936                 BOOL freePassword = TRUE;
5937
5938                 if (password && passwordConfirm)
5939                 {
5940                     SendMessageW(passwordEdit, WM_GETTEXT, passwordLen + 1,
5941                      (LPARAM)password);
5942                     SendMessageW(passwordConfirmEdit, WM_GETTEXT,
5943                      passwordConfirmLen + 1, (LPARAM)passwordConfirm);
5944                     if (strcmpW(password, passwordConfirm))
5945                     {
5946                         export_password_mismatch(hwnd, data);
5947                         SetWindowLongPtrW(hwnd, DWLP_MSGRESULT, 1);
5948                         ret = 1;
5949                     }
5950                     else
5951                     {
5952                         data->contextInfo.pwszPassword = password;
5953                         freePassword = FALSE;
5954                         data->freePassword = TRUE;
5955                     }
5956                 }
5957                 if (freePassword)
5958                     HeapFree(GetProcessHeap(), 0, password);
5959                 HeapFree(GetProcessHeap(), 0, passwordConfirm);
5960             }
5961             break;
5962         }
5963         }
5964         break;
5965     }
5966     }
5967     return ret;
5968 }
5969
5970 static LPWSTR export_append_extension(struct ExportWizData *data,
5971  LPWSTR fileName)
5972 {
5973     static const WCHAR cer[] = { '.','c','e','r',0 };
5974     static const WCHAR crl[] = { '.','c','r','l',0 };
5975     static const WCHAR ctl[] = { '.','c','t','l',0 };
5976     static const WCHAR p7b[] = { '.','p','7','b',0 };
5977     static const WCHAR pfx[] = { '.','p','f','x',0 };
5978     static const WCHAR sst[] = { '.','s','s','t',0 };
5979     LPCWSTR extension;
5980     LPWSTR dot;
5981     BOOL appendExtension;
5982
5983     switch (data->contextInfo.dwExportFormat)
5984     {
5985     case CRYPTUI_WIZ_EXPORT_FORMAT_PKCS7:
5986         extension = p7b;
5987         break;
5988     case CRYPTUI_WIZ_EXPORT_FORMAT_PFX:
5989         extension = pfx;
5990         break;
5991     default:
5992         switch (data->exportInfo.dwSubjectChoice)
5993         {
5994         case CRYPTUI_WIZ_EXPORT_CRL_CONTEXT:
5995             extension = crl;
5996             break;
5997         case CRYPTUI_WIZ_EXPORT_CTL_CONTEXT:
5998             extension = ctl;
5999             break;
6000         case CRYPTUI_WIZ_EXPORT_CERT_STORE:
6001             extension = sst;
6002             break;
6003         default:
6004             extension = cer;
6005         }
6006     }
6007     dot = strrchrW(fileName, '.');
6008     if (dot)
6009         appendExtension = strcmpiW(dot, extension) != 0;
6010     else
6011         appendExtension = TRUE;
6012     if (appendExtension)
6013     {
6014         fileName = HeapReAlloc(GetProcessHeap(), 0, fileName,
6015          (strlenW(fileName) + strlenW(extension) + 1) * sizeof(WCHAR));
6016         if (fileName)
6017             strcatW(fileName, extension);
6018     }
6019     return fileName;
6020 }
6021
6022 static BOOL export_validate_filename(HWND hwnd, struct ExportWizData *data,
6023  LPCWSTR fileName)
6024 {
6025     HANDLE file;
6026     BOOL tryCreate = TRUE, forceCreate = FALSE, ret = FALSE;
6027
6028     file = CreateFileW(fileName, GENERIC_WRITE,
6029      FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
6030     if (file != INVALID_HANDLE_VALUE)
6031     {
6032         WCHAR warning[MAX_STRING_LEN], title[MAX_STRING_LEN];
6033         LPCWSTR pTitle;
6034
6035         if (data->pwszWizardTitle)
6036             pTitle = data->pwszWizardTitle;
6037         else
6038         {
6039             LoadStringW(hInstance, IDS_EXPORT_WIZARD, title,
6040              sizeof(title) / sizeof(title[0]));
6041             pTitle = title;
6042         }
6043         LoadStringW(hInstance, IDS_EXPORT_FILE_EXISTS, warning,
6044          sizeof(warning) / sizeof(warning[0]));
6045         if (MessageBoxW(hwnd, warning, pTitle, MB_YESNO) == IDYES)
6046             forceCreate = TRUE;
6047         else
6048             tryCreate = FALSE;
6049         CloseHandle(file);
6050     }
6051     if (tryCreate)
6052     {
6053         file = CreateFileW(fileName, GENERIC_WRITE,
6054          FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
6055          forceCreate ? CREATE_ALWAYS : CREATE_NEW,
6056          0, NULL);
6057         if (file != INVALID_HANDLE_VALUE)
6058         {
6059             data->file = file;
6060             ret = TRUE;
6061         }
6062         else
6063         {
6064             WCHAR title[MAX_STRING_LEN], error[MAX_STRING_LEN];
6065             LPCWSTR pTitle;
6066             LPWSTR msgBuf, fullError;
6067
6068             if (data->pwszWizardTitle)
6069                 pTitle = data->pwszWizardTitle;
6070             else
6071             {
6072                 LoadStringW(hInstance, IDS_EXPORT_WIZARD, title,
6073                  sizeof(title) / sizeof(title[0]));
6074                 pTitle = title;
6075             }
6076             LoadStringW(hInstance, IDS_IMPORT_OPEN_FAILED, error,
6077              sizeof(error) / sizeof(error[0]));
6078             FormatMessageW(
6079              FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, NULL,
6080              GetLastError(), 0, (LPWSTR) &msgBuf, 0, NULL);
6081             fullError = HeapAlloc(GetProcessHeap(), 0,
6082              (strlenW(error) + strlenW(fileName) + strlenW(msgBuf) + 3)
6083              * sizeof(WCHAR));
6084             if (fullError)
6085             {
6086                 LPWSTR ptr = fullError;
6087
6088                 strcpyW(ptr, error);
6089                 ptr += strlenW(error);
6090                 strcpyW(ptr, fileName);
6091                 ptr += strlenW(fileName);
6092                 *ptr++ = ':';
6093                 *ptr++ = '\n';
6094                 strcpyW(ptr, msgBuf);
6095                 MessageBoxW(hwnd, fullError, pTitle, MB_ICONERROR | MB_OK);
6096                 HeapFree(GetProcessHeap(), 0, fullError);
6097             }
6098             LocalFree(msgBuf);
6099         }
6100     }
6101     return ret;
6102 }
6103
6104 static const WCHAR export_filter_cert[] = { '*','.','c','e','r',0 };
6105 static const WCHAR export_filter_crl[] = { '*','.','c','r','l',0 };
6106 static const WCHAR export_filter_ctl[] = { '*','.','s','t','l',0 };
6107 static const WCHAR export_filter_cms[] = { '*','.','p','7','b',0 };
6108 static const WCHAR export_filter_pfx[] = { '*','.','p','f','x',0 };
6109 static const WCHAR export_filter_sst[] = { '*','.','s','s','t',0 };
6110
6111 static WCHAR *make_export_file_filter(DWORD exportFormat, DWORD subjectChoice)
6112 {
6113     int baseLen, allLen, totalLen = 2, baseID;
6114     LPWSTR filter = NULL, baseFilter, all;
6115     LPCWSTR filterStr;
6116
6117     switch (exportFormat)
6118     {
6119     case CRYPTUI_WIZ_EXPORT_FORMAT_BASE64:
6120         baseID = IDS_EXPORT_FILTER_BASE64_CERT;
6121         filterStr = export_filter_cert;
6122         break;
6123     case CRYPTUI_WIZ_EXPORT_FORMAT_PFX:
6124         baseID = IDS_EXPORT_FILTER_PFX;
6125         filterStr = export_filter_pfx;
6126         break;
6127     case CRYPTUI_WIZ_EXPORT_FORMAT_PKCS7:
6128         baseID = IDS_EXPORT_FILTER_CMS;
6129         filterStr = export_filter_cms;
6130         break;
6131     default:
6132         switch (subjectChoice)
6133         {
6134         case CRYPTUI_WIZ_EXPORT_CRL_CONTEXT:
6135             baseID = IDS_EXPORT_FILTER_CRL;
6136             filterStr = export_filter_crl;
6137             break;
6138         case CRYPTUI_WIZ_EXPORT_CTL_CONTEXT:
6139             baseID = IDS_EXPORT_FILTER_CTL;
6140             filterStr = export_filter_ctl;
6141             break;
6142         case CRYPTUI_WIZ_EXPORT_CERT_STORE:
6143             baseID = IDS_EXPORT_FILTER_SERIALIZED_CERT_STORE;
6144             filterStr = export_filter_sst;
6145             break;
6146         default:
6147             baseID = IDS_EXPORT_FILTER_CERT;
6148             filterStr = export_filter_cert;
6149             break;
6150         }
6151     }
6152     baseLen = LoadStringW(hInstance, baseID, (LPWSTR)&baseFilter, 0);
6153     totalLen += baseLen + strlenW(filterStr) + 2;
6154     allLen = LoadStringW(hInstance, IDS_IMPORT_FILTER_ALL, (LPWSTR)&all, 0);
6155     totalLen += allLen + strlenW(filter_all) + 2;
6156     filter = HeapAlloc(GetProcessHeap(), 0, totalLen * sizeof(WCHAR));
6157     if (filter)
6158     {
6159         LPWSTR ptr;
6160
6161         ptr = filter;
6162         memcpy(ptr, baseFilter, baseLen * sizeof(WCHAR));
6163         ptr += baseLen;
6164         *ptr++ = 0;
6165         strcpyW(ptr, filterStr);
6166         ptr += strlenW(filterStr) + 1;
6167         memcpy(ptr, all, allLen * sizeof(WCHAR));
6168         ptr += allLen;
6169         *ptr++ = 0;
6170         strcpyW(ptr, filter_all);
6171         ptr += strlenW(filter_all) + 1;
6172         *ptr++ = 0;
6173     }
6174     return filter;
6175 }
6176
6177 static LRESULT CALLBACK export_file_dlg_proc(HWND hwnd, UINT msg, WPARAM wp,
6178  LPARAM lp)
6179 {
6180     LRESULT ret = 0;
6181     struct ExportWizData *data;
6182
6183     switch (msg)
6184     {
6185     case WM_INITDIALOG:
6186     {
6187         PROPSHEETPAGEW *page = (PROPSHEETPAGEW *)lp;
6188
6189         data = (struct ExportWizData *)page->lParam;
6190         SetWindowLongPtrW(hwnd, DWLP_USER, (LPARAM)data);
6191         if (data->exportInfo.pwszExportFileName)
6192             SendMessageW(GetDlgItem(hwnd, IDC_EXPORT_FILENAME), WM_SETTEXT, 0,
6193              (LPARAM)data->exportInfo.pwszExportFileName);
6194         break;
6195     }
6196     case WM_NOTIFY:
6197     {
6198         NMHDR *hdr = (NMHDR *)lp;
6199
6200         switch (hdr->code)
6201         {
6202         case PSN_WIZBACK:
6203             data = (struct ExportWizData *)GetWindowLongPtrW(hwnd, DWLP_USER);
6204             if (data->contextInfo.dwExportFormat !=
6205              CRYPTUI_WIZ_EXPORT_FORMAT_PFX)
6206             {
6207                 SetWindowLongPtrW(hwnd, DWLP_MSGRESULT, IDD_EXPORT_FORMAT);
6208                 ret = 1;
6209             }
6210             break;
6211         case PSN_WIZNEXT:
6212         {
6213             HWND fileNameEdit = GetDlgItem(hwnd, IDC_EXPORT_FILENAME);
6214             DWORD len = SendMessageW(fileNameEdit, WM_GETTEXTLENGTH, 0, 0);
6215
6216             data = (struct ExportWizData *)GetWindowLongPtrW(hwnd, DWLP_USER);
6217             if (!len)
6218             {
6219                 WCHAR title[MAX_STRING_LEN], error[MAX_STRING_LEN];
6220                 LPCWSTR pTitle;
6221
6222                 if (data->pwszWizardTitle)
6223                     pTitle = data->pwszWizardTitle;
6224                 else
6225                 {
6226                     LoadStringW(hInstance, IDS_EXPORT_WIZARD, title,
6227                      sizeof(title) / sizeof(title[0]));
6228                     pTitle = title;
6229                 }
6230                 LoadStringW(hInstance, IDS_IMPORT_EMPTY_FILE, error,
6231                  sizeof(error) / sizeof(error[0]));
6232                 MessageBoxW(hwnd, error, pTitle, MB_ICONERROR | MB_OK);
6233                 SetWindowLongPtrW(hwnd, DWLP_MSGRESULT, 1);
6234                 ret = 1;
6235             }
6236             else
6237             {
6238                 LPWSTR fileName = HeapAlloc(GetProcessHeap(), 0,
6239                  (len + 1) * sizeof(WCHAR));
6240
6241                 if (fileName)
6242                 {
6243                     SendMessageW(fileNameEdit, WM_GETTEXT, len + 1,
6244                      (LPARAM)fileName);
6245                     fileName = export_append_extension(data, fileName);
6246                     if (!export_validate_filename(hwnd, data, fileName))
6247                     {
6248                         HeapFree(GetProcessHeap(), 0, fileName);
6249                         SetWindowLongPtrW(hwnd, DWLP_MSGRESULT, 1);
6250                         ret = 1;
6251                     }
6252                     else
6253                         data->fileName = fileName;
6254                 }
6255             }
6256             break;
6257         }
6258         case PSN_SETACTIVE:
6259             PostMessageW(GetParent(hwnd), PSM_SETWIZBUTTONS, 0,
6260              PSWIZB_BACK | PSWIZB_NEXT);
6261             ret = TRUE;
6262             break;
6263         }
6264         break;
6265     }
6266     case WM_COMMAND:
6267         switch (wp)
6268         {
6269         case IDC_EXPORT_BROWSE_FILE:
6270         {
6271             OPENFILENAMEW ofn;
6272             WCHAR fileBuf[MAX_PATH];
6273
6274             data = (struct ExportWizData *)GetWindowLongPtrW(hwnd, DWLP_USER);
6275             memset(&ofn, 0, sizeof(ofn));
6276             ofn.lStructSize = sizeof(ofn);
6277             ofn.hwndOwner = hwnd;
6278             ofn.lpstrFilter = make_export_file_filter(
6279              data->contextInfo.dwExportFormat,
6280              data->exportInfo.dwSubjectChoice);
6281             ofn.lpstrFile = fileBuf;
6282             ofn.nMaxFile = sizeof(fileBuf) / sizeof(fileBuf[0]);
6283             fileBuf[0] = 0;
6284             if (GetSaveFileNameW(&ofn))
6285                 SendMessageW(GetDlgItem(hwnd, IDC_EXPORT_FILENAME), WM_SETTEXT,
6286                  0, (LPARAM)ofn.lpstrFile);
6287             HeapFree(GetProcessHeap(), 0, (LPWSTR)ofn.lpstrFilter);
6288             break;
6289         }
6290         }
6291         break;
6292     }
6293     return ret;
6294 }
6295
6296 static void show_export_details(HWND lv, struct ExportWizData *data)
6297 {
6298     WCHAR text[MAX_STRING_LEN];
6299     LVITEMW item;
6300     int contentID;
6301
6302     item.mask = LVIF_TEXT;
6303     if (data->fileName)
6304     {
6305         item.iItem = SendMessageW(lv, LVM_GETITEMCOUNT, 0, 0);
6306         item.iSubItem = 0;
6307         LoadStringW(hInstance, IDS_IMPORT_FILE, text,
6308          sizeof(text)/ sizeof(text[0]));
6309         item.pszText = text;
6310         SendMessageW(lv, LVM_INSERTITEMW, 0, (LPARAM)&item);
6311         item.iSubItem = 1;
6312         item.pszText = data->fileName;
6313         SendMessageW(lv, LVM_SETITEMTEXTW, item.iItem, (LPARAM)&item);
6314     }
6315
6316     item.pszText = text;
6317     switch (data->exportInfo.dwSubjectChoice)
6318     {
6319     case CRYPTUI_WIZ_EXPORT_CRL_CONTEXT:
6320     case CRYPTUI_WIZ_EXPORT_CTL_CONTEXT:
6321     case CRYPTUI_WIZ_EXPORT_CERT_STORE:
6322     case CRYPTUI_WIZ_EXPORT_CERT_STORE_CERTIFICATES_ONLY:
6323         /* do nothing */
6324         break;
6325     default:
6326     {
6327         item.iItem = SendMessageW(lv, LVM_GETITEMCOUNT, 0, 0);
6328         item.iSubItem = 0;
6329         LoadStringW(hInstance, IDS_EXPORT_INCLUDE_CHAIN, text,
6330          sizeof(text) / sizeof(text[0]));
6331         SendMessageW(lv, LVM_INSERTITEMW, item.iItem, (LPARAM)&item);
6332         item.iSubItem = 1;
6333         LoadStringW(hInstance,
6334          data->contextInfo.fExportChain ? IDS_YES : IDS_NO, text,
6335          sizeof(text) / sizeof(text[0]));
6336         SendMessageW(lv, LVM_SETITEMTEXTW, item.iItem, (LPARAM)&item);
6337
6338         item.iItem = SendMessageW(lv, LVM_GETITEMCOUNT, 0, 0);
6339         item.iSubItem = 0;
6340         LoadStringW(hInstance, IDS_EXPORT_KEYS, text,
6341          sizeof(text) / sizeof(text[0]));
6342         SendMessageW(lv, LVM_INSERTITEMW, item.iItem, (LPARAM)&item);
6343         item.iSubItem = 1;
6344         LoadStringW(hInstance,
6345          data->contextInfo.fExportPrivateKeys ? IDS_YES : IDS_NO, text,
6346          sizeof(text) / sizeof(text[0]));
6347         SendMessageW(lv, LVM_SETITEMTEXTW, item.iItem, (LPARAM)&item);
6348     }
6349     }
6350
6351     item.iItem = SendMessageW(lv, LVM_GETITEMCOUNT, 0, 0);
6352     item.iSubItem = 0;
6353     LoadStringW(hInstance, IDS_EXPORT_FORMAT, text,
6354      sizeof(text)/ sizeof(text[0]));
6355     SendMessageW(lv, LVM_INSERTITEMW, 0, (LPARAM)&item);
6356
6357     item.iSubItem = 1;
6358     switch (data->exportInfo.dwSubjectChoice)
6359     {
6360     case CRYPTUI_WIZ_EXPORT_CRL_CONTEXT:
6361         contentID = IDS_EXPORT_FILTER_CRL;
6362         break;
6363     case CRYPTUI_WIZ_EXPORT_CTL_CONTEXT:
6364         contentID = IDS_EXPORT_FILTER_CTL;
6365         break;
6366     case CRYPTUI_WIZ_EXPORT_CERT_STORE:
6367         contentID = IDS_EXPORT_FILTER_SERIALIZED_CERT_STORE;
6368         break;
6369     default:
6370         switch (data->contextInfo.dwExportFormat)
6371         {
6372         case CRYPTUI_WIZ_EXPORT_FORMAT_BASE64:
6373             contentID = IDS_EXPORT_FILTER_BASE64_CERT;
6374             break;
6375         case CRYPTUI_WIZ_EXPORT_FORMAT_PKCS7:
6376             contentID = IDS_EXPORT_FILTER_CMS;
6377             break;
6378         case CRYPTUI_WIZ_EXPORT_FORMAT_PFX:
6379             contentID = IDS_EXPORT_FILTER_PFX;
6380             break;
6381         default:
6382             contentID = IDS_EXPORT_FILTER_CERT;
6383         }
6384     }
6385     LoadStringW(hInstance, contentID, text, sizeof(text) / sizeof(text[0]));
6386     SendMessageW(lv, LVM_SETITEMTEXTW, item.iItem, (LPARAM)&item);
6387 }
6388
6389 static inline BOOL save_der(HANDLE file, const BYTE *pb, DWORD cb)
6390 {
6391     DWORD bytesWritten;
6392
6393     return WriteFile(file, pb, cb, &bytesWritten, NULL);
6394 }
6395
6396 static BOOL save_base64(HANDLE file, const BYTE *pb, DWORD cb)
6397 {
6398     BOOL ret;
6399     DWORD size = 0;
6400
6401     if ((ret = CryptBinaryToStringA(pb, cb, CRYPT_STRING_BASE64, NULL, &size)))
6402     {
6403         LPSTR buf = HeapAlloc(GetProcessHeap(), 0, size);
6404
6405         if (buf)
6406         {
6407             if ((ret = CryptBinaryToStringA(pb, cb, CRYPT_STRING_BASE64, buf,
6408              &size)))
6409                 ret = WriteFile(file, buf, size, &size, NULL);
6410             HeapFree(GetProcessHeap(), 0, buf);
6411         }
6412         else
6413         {
6414             SetLastError(ERROR_OUTOFMEMORY);
6415             ret = FALSE;
6416         }
6417     }
6418     return ret;
6419 }
6420
6421 static inline BOOL save_store_as_cms(HANDLE file, HCERTSTORE store)
6422 {
6423     return CertSaveStore(store, PKCS_7_ASN_ENCODING | X509_ASN_ENCODING,
6424      CERT_STORE_SAVE_AS_PKCS7, CERT_STORE_SAVE_TO_FILE, file, 0);
6425 }
6426
6427 static BOOL save_cert_as_cms(HANDLE file, PCCRYPTUI_WIZ_EXPORT_INFO pExportInfo,
6428  BOOL includeChain)
6429 {
6430     BOOL ret;
6431     HCERTSTORE store = CertOpenStore(CERT_STORE_PROV_MEMORY, 0, 0,
6432      CERT_STORE_CREATE_NEW_FLAG, NULL);
6433
6434     if (store)
6435     {
6436         if (includeChain)
6437         {
6438             HCERTSTORE addlStore = CertOpenStore(CERT_STORE_PROV_COLLECTION,
6439              0, 0, CERT_STORE_CREATE_NEW_FLAG, NULL);
6440
6441             if (addlStore)
6442             {
6443                 DWORD i;
6444
6445                 ret = TRUE;
6446                 for (i = 0; ret && i < pExportInfo->cStores; i++)
6447                     ret = CertAddStoreToCollection(addlStore,
6448                      pExportInfo->rghStores, 0, 0);
6449                 if (ret)
6450                 {
6451                     PCCERT_CHAIN_CONTEXT chain;
6452
6453                     ret = CertGetCertificateChain(NULL,
6454                      pExportInfo->u.pCertContext, NULL, addlStore, NULL, 0,
6455                      NULL, &chain);
6456                     if (ret)
6457                     {
6458                         DWORD j;
6459
6460                         for (i = 0; ret && i < chain->cChain; i++)
6461                             for (j = 0; ret && j < chain->rgpChain[i]->cElement;
6462                              j++)
6463                                 ret = CertAddCertificateContextToStore(store,
6464                                  chain->rgpChain[i]->rgpElement[j]->pCertContext,
6465                                  CERT_STORE_ADD_ALWAYS, NULL);
6466                         CertFreeCertificateChain(chain);
6467                     }
6468                     else
6469                     {
6470                         /* No chain could be created, just add the individual
6471                          * cert to the message.
6472                          */
6473                         ret = CertAddCertificateContextToStore(store,
6474                          pExportInfo->u.pCertContext, CERT_STORE_ADD_ALWAYS,
6475                          NULL);
6476                     }
6477                 }
6478                 CertCloseStore(addlStore, 0);
6479             }
6480             else
6481                 ret = FALSE;
6482         }
6483         else
6484             ret = CertAddCertificateContextToStore(store,
6485              pExportInfo->u.pCertContext, CERT_STORE_ADD_ALWAYS, NULL);
6486         if (ret)
6487             ret = save_store_as_cms(file, store);
6488         CertCloseStore(store, 0);
6489     }
6490     else
6491         ret = FALSE;
6492     return ret;
6493 }
6494
6495 static BOOL save_serialized_store(HANDLE file, HCERTSTORE store)
6496 {
6497     return CertSaveStore(store, PKCS_7_ASN_ENCODING | X509_ASN_ENCODING,
6498      CERT_STORE_SAVE_AS_STORE, CERT_STORE_SAVE_TO_FILE, file, 0);
6499 }
6500
6501 static BOOL save_pfx(HANDLE file, PCCRYPTUI_WIZ_EXPORT_INFO pExportInfo,
6502  PCCRYPTUI_WIZ_EXPORT_CERTCONTEXT_INFO pContextInfo)
6503 {
6504     HCERTSTORE store = CertOpenStore(CERT_STORE_PROV_MEMORY, X509_ASN_ENCODING,
6505      0, CERT_STORE_CREATE_NEW_FLAG, NULL);
6506     BOOL ret = FALSE;
6507
6508     if (store)
6509     {
6510         CRYPT_DATA_BLOB pfxBlob = { 0, NULL };
6511
6512         if (pContextInfo->fExportChain)
6513         {
6514             HCERTCHAINENGINE engine = NULL;
6515
6516             if (pExportInfo->cStores)
6517             {
6518                 CERT_CHAIN_ENGINE_CONFIG config;
6519
6520                 memset(&config, 0, sizeof(config));
6521                 config.cbSize = sizeof(config);
6522                 config.cAdditionalStore = pExportInfo->cStores;
6523                 config.rghAdditionalStore = pExportInfo->rghStores;
6524                 ret = CertCreateCertificateChainEngine(&config, &engine);
6525             }
6526             else
6527                 ret = TRUE;
6528             if (ret)
6529             {
6530                 CERT_CHAIN_PARA chainPara;
6531                 PCCERT_CHAIN_CONTEXT chain;
6532
6533                 memset(&chainPara, 0, sizeof(chainPara));
6534                 chainPara.cbSize = sizeof(chainPara);
6535                 ret = CertGetCertificateChain(engine,
6536                  pExportInfo->u.pCertContext, NULL, NULL, &chainPara, 0, NULL,
6537                  &chain);
6538                 if (ret)
6539                 {
6540                     DWORD i, j;
6541
6542                     for (i = 0; ret && i < chain->cChain; i++)
6543                         for (j = 0; ret && j < chain->rgpChain[i]->cElement;
6544                          j++)
6545                             ret = CertAddCertificateContextToStore(store,
6546                              chain->rgpChain[i]->rgpElement[j]->pCertContext,
6547                              CERT_STORE_ADD_ALWAYS, NULL);
6548                     CertFreeCertificateChain(chain);
6549                 }
6550             }
6551             if (engine)
6552                 CertFreeCertificateChainEngine(engine);
6553         }
6554         else
6555             ret = CertAddCertificateContextToStore(store,
6556              pExportInfo->u.pCertContext, CERT_STORE_ADD_ALWAYS, NULL);
6557         if (ret)
6558         {
6559             DWORD exportFlags =
6560              REPORT_NOT_ABLE_TO_EXPORT_PRIVATE_KEY | EXPORT_PRIVATE_KEYS;
6561
6562             ret = PFXExportCertStore(store, &pfxBlob,
6563              pContextInfo->pwszPassword, exportFlags);
6564             if (ret)
6565             {
6566                 pfxBlob.pbData = HeapAlloc(GetProcessHeap(), 0, pfxBlob.cbData);
6567                 if (pfxBlob.pbData)
6568                 {
6569                     ret = PFXExportCertStore(store, &pfxBlob,
6570                      pContextInfo->pwszPassword, exportFlags);
6571                     if (ret)
6572                     {
6573                         DWORD bytesWritten;
6574
6575                         ret = WriteFile(file, pfxBlob.pbData, pfxBlob.cbData,
6576                          &bytesWritten, NULL);
6577                     }
6578                 }
6579                 else
6580                 {
6581                     SetLastError(ERROR_OUTOFMEMORY);
6582                     ret = FALSE;
6583                 }
6584             }
6585         }
6586         CertCloseStore(store, 0);
6587     }
6588     return ret;
6589 }
6590
6591 static BOOL do_export(HANDLE file, PCCRYPTUI_WIZ_EXPORT_INFO pExportInfo,
6592  PCCRYPTUI_WIZ_EXPORT_CERTCONTEXT_INFO pContextInfo)
6593 {
6594     BOOL ret;
6595
6596     if (pContextInfo->dwSize != sizeof(CRYPTUI_WIZ_EXPORT_CERTCONTEXT_INFO))
6597     {
6598         SetLastError(E_INVALIDARG);
6599         return FALSE;
6600     }
6601     switch (pExportInfo->dwSubjectChoice)
6602     {
6603     case CRYPTUI_WIZ_EXPORT_CRL_CONTEXT:
6604         ret = save_der(file,
6605          pExportInfo->u.pCRLContext->pbCrlEncoded,
6606          pExportInfo->u.pCRLContext->cbCrlEncoded);
6607         break;
6608     case CRYPTUI_WIZ_EXPORT_CTL_CONTEXT:
6609         ret = save_der(file,
6610          pExportInfo->u.pCTLContext->pbCtlEncoded,
6611          pExportInfo->u.pCTLContext->cbCtlEncoded);
6612         break;
6613     case CRYPTUI_WIZ_EXPORT_CERT_STORE:
6614         ret = save_serialized_store(file, pExportInfo->u.hCertStore);
6615         break;
6616     case CRYPTUI_WIZ_EXPORT_CERT_STORE_CERTIFICATES_ONLY:
6617         ret = save_store_as_cms(file, pExportInfo->u.hCertStore);
6618         break;
6619     default:
6620         switch (pContextInfo->dwExportFormat)
6621         {
6622         case CRYPTUI_WIZ_EXPORT_FORMAT_DER:
6623             ret = save_der(file, pExportInfo->u.pCertContext->pbCertEncoded,
6624              pExportInfo->u.pCertContext->cbCertEncoded);
6625             break;
6626         case CRYPTUI_WIZ_EXPORT_FORMAT_BASE64:
6627             ret = save_base64(file,
6628              pExportInfo->u.pCertContext->pbCertEncoded,
6629              pExportInfo->u.pCertContext->cbCertEncoded);
6630             break;
6631         case CRYPTUI_WIZ_EXPORT_FORMAT_PKCS7:
6632             ret = save_cert_as_cms(file, pExportInfo,
6633              pContextInfo->fExportChain);
6634             break;
6635         case CRYPTUI_WIZ_EXPORT_FORMAT_PFX:
6636             ret = save_pfx(file, pExportInfo, pContextInfo);
6637             break;
6638         default:
6639             SetLastError(E_FAIL);
6640             ret = FALSE;
6641         }
6642     }
6643     return ret;
6644 }
6645
6646 static LRESULT CALLBACK export_finish_dlg_proc(HWND hwnd, UINT msg, WPARAM wp,
6647  LPARAM lp)
6648 {
6649     LRESULT ret = 0;
6650     struct ExportWizData *data;
6651
6652     switch (msg)
6653     {
6654     case WM_INITDIALOG:
6655     {
6656         PROPSHEETPAGEW *page = (PROPSHEETPAGEW *)lp;
6657         HWND lv = GetDlgItem(hwnd, IDC_EXPORT_SETTINGS);
6658         RECT rc;
6659         LVCOLUMNW column;
6660
6661         data = (struct ExportWizData *)page->lParam;
6662         SetWindowLongPtrW(hwnd, DWLP_USER, (LPARAM)data);
6663         SendMessageW(GetDlgItem(hwnd, IDC_EXPORT_TITLE), WM_SETFONT,
6664          (WPARAM)data->titleFont, TRUE);
6665         GetWindowRect(lv, &rc);
6666         column.mask = LVCF_WIDTH;
6667         column.cx = (rc.right - rc.left) / 2 - 2;
6668         SendMessageW(lv, LVM_INSERTCOLUMNW, 0, (LPARAM)&column);
6669         SendMessageW(lv, LVM_INSERTCOLUMNW, 1, (LPARAM)&column);
6670         show_export_details(lv, data);
6671         break;
6672     }
6673     case WM_NOTIFY:
6674     {
6675         NMHDR *hdr = (NMHDR *)lp;
6676
6677         switch (hdr->code)
6678         {
6679         case PSN_SETACTIVE:
6680         {
6681             HWND lv = GetDlgItem(hwnd, IDC_EXPORT_SETTINGS);
6682
6683             data = (struct ExportWizData *)GetWindowLongPtrW(hwnd, DWLP_USER);
6684             SendMessageW(lv, LVM_DELETEALLITEMS, 0, 0);
6685             show_export_details(lv, data);
6686             PostMessageW(GetParent(hwnd), PSM_SETWIZBUTTONS, 0,
6687              PSWIZB_BACK | PSWIZB_FINISH);
6688             ret = TRUE;
6689             break;
6690         }
6691         case PSN_WIZFINISH:
6692         {
6693             int messageID;
6694             WCHAR title[MAX_STRING_LEN], message[MAX_STRING_LEN];
6695             LPCWSTR pTitle;
6696             DWORD mbFlags;
6697
6698             data = (struct ExportWizData *)GetWindowLongPtrW(hwnd, DWLP_USER);
6699             if ((data->success = do_export(data->file, &data->exportInfo,
6700              &data->contextInfo)))
6701             {
6702                 messageID = IDS_EXPORT_SUCCEEDED;
6703                 mbFlags = MB_OK;
6704             }
6705             else
6706             {
6707                 messageID = IDS_EXPORT_FAILED;
6708                 mbFlags = MB_OK | MB_ICONERROR;
6709             }
6710             if (data->pwszWizardTitle)
6711                 pTitle = data->pwszWizardTitle;
6712             else
6713             {
6714                 LoadStringW(hInstance, IDS_EXPORT_WIZARD, title,
6715                  sizeof(title) / sizeof(title[0]));
6716                 pTitle = title;
6717             }
6718             LoadStringW(hInstance, messageID, message,
6719              sizeof(message) / sizeof(message[0]));
6720             MessageBoxW(hwnd, message, pTitle, mbFlags);
6721             break;
6722         }
6723         }
6724         break;
6725     }
6726     }
6727     return ret;
6728 }
6729
6730 static BOOL show_export_ui(DWORD dwFlags, HWND hwndParent,
6731  LPCWSTR pwszWizardTitle, PCCRYPTUI_WIZ_EXPORT_INFO pExportInfo, void *pvoid)
6732 {
6733     PROPSHEETHEADERW hdr;
6734     PROPSHEETPAGEW pages[6];
6735     struct ExportWizData data;
6736     int nPages = 0;
6737     BOOL hasPrivateKey, showFormatPage = TRUE;
6738     INT_PTR l;
6739
6740     data.dwFlags = dwFlags;
6741     data.pwszWizardTitle = pwszWizardTitle;
6742     memset(&data.exportInfo, 0, sizeof(data.exportInfo));
6743     memcpy(&data.exportInfo, pExportInfo,
6744      min(sizeof(data.exportInfo), pExportInfo->dwSize));
6745     if (pExportInfo->dwSize > sizeof(data.exportInfo))
6746         data.exportInfo.dwSize = sizeof(data.exportInfo);
6747     data.contextInfo.dwSize = sizeof(data.contextInfo);
6748     data.contextInfo.dwExportFormat = CRYPTUI_WIZ_EXPORT_FORMAT_DER;
6749     data.contextInfo.fExportChain = FALSE;
6750     data.contextInfo.fStrongEncryption = FALSE;
6751     data.contextInfo.fExportPrivateKeys = FALSE;
6752     data.contextInfo.pwszPassword = NULL;
6753     data.freePassword = FALSE;
6754     if (pExportInfo->dwSubjectChoice == CRYPTUI_WIZ_EXPORT_CERT_CONTEXT &&
6755      pvoid)
6756         memcpy(&data.contextInfo, pvoid,
6757          min(((PCCRYPTUI_WIZ_EXPORT_CERTCONTEXT_INFO)pvoid)->dwSize,
6758          sizeof(data.contextInfo)));
6759     data.keyProvInfo = NULL;
6760     data.fileName = NULL;
6761     data.file = INVALID_HANDLE_VALUE;
6762     data.success = FALSE;
6763
6764     memset(&pages, 0, sizeof(pages));
6765
6766     pages[nPages].dwSize = sizeof(pages[0]);
6767     pages[nPages].hInstance = hInstance;
6768     pages[nPages].u.pszTemplate = MAKEINTRESOURCEW(IDD_EXPORT_WELCOME);
6769     pages[nPages].pfnDlgProc = export_welcome_dlg_proc;
6770     pages[nPages].dwFlags = PSP_HIDEHEADER;
6771     pages[nPages].lParam = (LPARAM)&data;
6772     nPages++;
6773
6774     hasPrivateKey = export_info_has_private_key(pExportInfo);
6775     switch (pExportInfo->dwSubjectChoice)
6776     {
6777     case CRYPTUI_WIZ_EXPORT_CRL_CONTEXT:
6778     case CRYPTUI_WIZ_EXPORT_CTL_CONTEXT:
6779         showFormatPage = FALSE;
6780         data.contextInfo.dwExportFormat = CRYPTUI_WIZ_EXPORT_FORMAT_DER;
6781         break;
6782     case CRYPTUI_WIZ_EXPORT_CERT_STORE:
6783         showFormatPage = FALSE;
6784         data.contextInfo.dwExportFormat =
6785          CRYPTUI_WIZ_EXPORT_FORMAT_SERIALIZED_CERT_STORE;
6786         break;
6787     case CRYPTUI_WIZ_EXPORT_CERT_STORE_CERTIFICATES_ONLY:
6788         showFormatPage = FALSE;
6789         data.contextInfo.dwExportFormat = CRYPTUI_WIZ_EXPORT_FORMAT_PKCS7;
6790         break;
6791     }
6792
6793     if (hasPrivateKey && showFormatPage)
6794     {
6795         pages[nPages].dwSize = sizeof(pages[0]);
6796         pages[nPages].hInstance = hInstance;
6797         pages[nPages].u.pszTemplate = MAKEINTRESOURCEW(IDD_EXPORT_PRIVATE_KEY);
6798         pages[nPages].pfnDlgProc = export_private_key_dlg_proc;
6799         pages[nPages].dwFlags = PSP_USEHEADERTITLE | PSP_USEHEADERSUBTITLE;
6800         pages[nPages].pszHeaderTitle =
6801          MAKEINTRESOURCEW(IDS_EXPORT_PRIVATE_KEY_TITLE);
6802         pages[nPages].pszHeaderSubTitle =
6803          MAKEINTRESOURCEW(IDS_EXPORT_PRIVATE_KEY_SUBTITLE);
6804         pages[nPages].lParam = (LPARAM)&data;
6805         nPages++;
6806     }
6807     if (showFormatPage)
6808     {
6809         pages[nPages].dwSize = sizeof(pages[0]);
6810         pages[nPages].hInstance = hInstance;
6811         pages[nPages].u.pszTemplate = MAKEINTRESOURCEW(IDD_EXPORT_FORMAT);
6812         pages[nPages].pfnDlgProc = export_format_dlg_proc;
6813         pages[nPages].dwFlags = PSP_USEHEADERTITLE | PSP_USEHEADERSUBTITLE;
6814         pages[nPages].pszHeaderTitle =
6815          MAKEINTRESOURCEW(IDS_EXPORT_FORMAT_TITLE);
6816         pages[nPages].pszHeaderSubTitle =
6817          MAKEINTRESOURCEW(IDS_EXPORT_FORMAT_SUBTITLE);
6818         pages[nPages].lParam = (LPARAM)&data;
6819         nPages++;
6820     }
6821     if (hasPrivateKey && showFormatPage)
6822     {
6823         pages[nPages].dwSize = sizeof(pages[0]);
6824         pages[nPages].hInstance = hInstance;
6825         pages[nPages].u.pszTemplate = MAKEINTRESOURCEW(IDD_EXPORT_PASSWORD);
6826         pages[nPages].pfnDlgProc = export_password_dlg_proc;
6827         pages[nPages].dwFlags = PSP_USEHEADERTITLE | PSP_USEHEADERSUBTITLE;
6828         pages[nPages].pszHeaderTitle =
6829          MAKEINTRESOURCEW(IDS_EXPORT_PASSWORD_TITLE);
6830         pages[nPages].pszHeaderSubTitle =
6831          MAKEINTRESOURCEW(IDS_EXPORT_PASSWORD_SUBTITLE);
6832         pages[nPages].lParam = (LPARAM)&data;
6833         nPages++;
6834     }
6835
6836     pages[nPages].dwSize = sizeof(pages[0]);
6837     pages[nPages].hInstance = hInstance;
6838     pages[nPages].u.pszTemplate = MAKEINTRESOURCEW(IDD_EXPORT_FILE);
6839     pages[nPages].pfnDlgProc = export_file_dlg_proc;
6840     pages[nPages].dwFlags = PSP_USEHEADERTITLE | PSP_USEHEADERSUBTITLE;
6841     pages[nPages].pszHeaderTitle = MAKEINTRESOURCEW(IDS_EXPORT_FILE_TITLE);
6842     pages[nPages].pszHeaderSubTitle =
6843      MAKEINTRESOURCEW(IDS_EXPORT_FILE_SUBTITLE);
6844     pages[nPages].lParam = (LPARAM)&data;
6845     nPages++;
6846
6847     pages[nPages].dwSize = sizeof(pages[0]);
6848     pages[nPages].hInstance = hInstance;
6849     pages[nPages].u.pszTemplate = MAKEINTRESOURCEW(IDD_EXPORT_FINISH);
6850     pages[nPages].pfnDlgProc = export_finish_dlg_proc;
6851     pages[nPages].dwFlags = PSP_HIDEHEADER;
6852     pages[nPages].lParam = (LPARAM)&data;
6853     nPages++;
6854
6855     memset(&hdr, 0, sizeof(hdr));
6856     hdr.dwSize = sizeof(hdr);
6857     hdr.hwndParent = hwndParent;
6858     hdr.dwFlags = PSH_PROPSHEETPAGE | PSH_WIZARD97_NEW | PSH_HEADER |
6859      PSH_WATERMARK;
6860     hdr.hInstance = hInstance;
6861     if (pwszWizardTitle)
6862         hdr.pszCaption = pwszWizardTitle;
6863     else
6864         hdr.pszCaption = MAKEINTRESOURCEW(IDS_EXPORT_WIZARD);
6865     hdr.u3.ppsp = pages;
6866     hdr.nPages = nPages;
6867     hdr.u4.pszbmWatermark = MAKEINTRESOURCEW(IDB_CERT_WATERMARK);
6868     hdr.u5.pszbmHeader = MAKEINTRESOURCEW(IDB_CERT_HEADER);
6869     l = PropertySheetW(&hdr);
6870     DeleteObject(data.titleFont);
6871     if (data.freePassword)
6872         HeapFree(GetProcessHeap(), 0,
6873          (LPWSTR)data.contextInfo.pwszPassword);
6874     HeapFree(GetProcessHeap(), 0, data.keyProvInfo);
6875     CloseHandle(data.file);
6876     HeapFree(GetProcessHeap(), 0, data.fileName);
6877     if (l == 0)
6878     {
6879         SetLastError(ERROR_CANCELLED);
6880         return FALSE;
6881     }
6882     else
6883         return data.success;
6884 }
6885
6886 BOOL WINAPI CryptUIWizExport(DWORD dwFlags, HWND hwndParent,
6887  LPCWSTR pwszWizardTitle, PCCRYPTUI_WIZ_EXPORT_INFO pExportInfo, void *pvoid)
6888 {
6889     BOOL ret;
6890
6891     TRACE("(%08x, %p, %s, %p, %p)\n", dwFlags, hwndParent,
6892      debugstr_w(pwszWizardTitle), pExportInfo, pvoid);
6893
6894     if (!(dwFlags & CRYPTUI_WIZ_NO_UI))
6895         ret = show_export_ui(dwFlags, hwndParent, pwszWizardTitle, pExportInfo,
6896          pvoid);
6897     else
6898     {
6899         HANDLE file = CreateFileW(pExportInfo->pwszExportFileName,
6900          GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
6901          CREATE_ALWAYS, 0, NULL);
6902
6903         if (file != INVALID_HANDLE_VALUE)
6904         {
6905             ret = do_export(file, pExportInfo, pvoid);
6906             CloseHandle(file);
6907         }
6908         else
6909             ret = FALSE;
6910     }
6911     return ret;
6912 }