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