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