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