cryptui: Disable the PFX export format in the export wizard unless the source has...
[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 LRESULT CALLBACK cert_mgr_dlg_proc(HWND hwnd, UINT msg, WPARAM wp,
1005  LPARAM lp)
1006 {
1007     struct CertMgrData *data;
1008
1009     switch (msg)
1010     {
1011     case WM_INITDIALOG:
1012     {
1013         PCCRYPTUI_CERT_MGR_STRUCT pCryptUICertMgr =
1014          (PCCRYPTUI_CERT_MGR_STRUCT)lp;
1015         HWND tab = GetDlgItem(hwnd, IDC_MGR_STORES);
1016
1017         data = HeapAlloc(GetProcessHeap(), 0, sizeof(struct CertMgrData));
1018         if (data)
1019         {
1020             data->imageList = ImageList_Create(16, 16, ILC_COLOR4 | ILC_MASK,
1021              2, 0);
1022             if (data->imageList)
1023             {
1024                 HBITMAP bmp;
1025                 COLORREF backColor = RGB(255, 0, 255);
1026
1027                 bmp = LoadBitmapW(hInstance, MAKEINTRESOURCEW(IDB_SMALL_ICONS));
1028                 ImageList_AddMasked(data->imageList, bmp, backColor);
1029                 DeleteObject(bmp);
1030                 ImageList_SetBkColor(data->imageList, CLR_NONE);
1031                 SendMessageW(GetDlgItem(hwnd, IDC_MGR_CERTS), LVM_SETIMAGELIST,
1032                  LVSIL_SMALL, (LPARAM)data->imageList);
1033             }
1034             SetWindowLongPtrW(hwnd, DWLP_USER, (LPARAM)data);
1035             data->title = pCryptUICertMgr->pwszTitle;
1036         }
1037         initialize_purpose_selection(hwnd);
1038         add_cert_columns(hwnd);
1039         if (pCryptUICertMgr->pwszTitle)
1040             SendMessageW(hwnd, WM_SETTEXT, 0,
1041              (LPARAM)pCryptUICertMgr->pwszTitle);
1042         show_cert_stores(hwnd, pCryptUICertMgr->dwFlags, data);
1043         show_store_certs(hwnd, cert_mgr_index_to_store(tab, 0));
1044         break;
1045     }
1046     case WM_NOTIFY:
1047     {
1048         NMHDR *hdr = (NMHDR *)lp;
1049
1050         switch (hdr->code)
1051         {
1052         case TCN_SELCHANGE:
1053             cert_mgr_clear_cert_selection(hwnd);
1054             break;
1055         case LVN_ITEMCHANGED:
1056         {
1057             NMITEMACTIVATE *nm;
1058             HWND lv = GetDlgItem(hwnd, IDC_MGR_CERTS);
1059
1060             nm = (NMITEMACTIVATE*)lp;
1061             if (nm->uNewState & LVN_ITEMACTIVATE)
1062             {
1063                 int numSelected = SendMessageW(lv, LVM_GETSELECTEDCOUNT, 0, 0);
1064
1065                 EnableWindow(GetDlgItem(hwnd, IDC_MGR_EXPORT), numSelected > 0);
1066                 EnableWindow(GetDlgItem(hwnd, IDC_MGR_REMOVE), numSelected > 0);
1067                 EnableWindow(GetDlgItem(hwnd, IDC_MGR_VIEW), numSelected == 1);
1068                 if (numSelected == 1)
1069                     cert_mgr_show_cert_usages(hwnd, nm->iItem);
1070             }
1071             break;
1072         }
1073         case NM_DBLCLK:
1074             show_selected_cert(hwnd, ((NMITEMACTIVATE *)lp)->iItem);
1075             break;
1076         case LVN_KEYDOWN:
1077         {
1078             NMLVKEYDOWN *lvk = (NMLVKEYDOWN *)lp;
1079
1080             if (lvk->wVKey == VK_DELETE)
1081                 cert_mgr_do_remove(hwnd);
1082             break;
1083         }
1084         }
1085         break;
1086     }
1087     case WM_COMMAND:
1088         switch (wp)
1089         {
1090         case ((CBN_SELCHANGE << 16) | IDC_MGR_PURPOSE_SELECTION):
1091             cert_mgr_clear_cert_selection(hwnd);
1092             break;
1093         case IDC_MGR_IMPORT:
1094             if (CryptUIWizImport(0, hwnd, NULL, NULL,
1095              cert_mgr_current_store(hwnd)))
1096                 refresh_store_certs(hwnd);
1097             break;
1098         case IDC_MGR_ADVANCED:
1099             if (DialogBoxW(hInstance, MAKEINTRESOURCEW(IDD_CERT_MGR_ADVANCED),
1100              hwnd, cert_mgr_advanced_dlg_proc) == IDOK)
1101             {
1102                 HWND cb = GetDlgItem(hwnd, IDC_MGR_PURPOSE_SELECTION);
1103                 int index, len;
1104                 LPWSTR curString = NULL;
1105
1106                 index = SendMessageW(cb, CB_GETCURSEL, 0, 0);
1107                 if (index >= 0)
1108                 {
1109                     len = SendMessageW(cb, CB_GETLBTEXTLEN, index, 0);
1110                     curString = HeapAlloc(GetProcessHeap(), 0,
1111                      (len + 1) * sizeof(WCHAR));
1112                     SendMessageW(cb, CB_GETLBTEXT, index, (LPARAM)curString);
1113                 }
1114                 SendMessageW(cb, CB_RESETCONTENT, 0, 0);
1115                 initialize_purpose_selection(hwnd);
1116                 if (curString)
1117                 {
1118                     index = SendMessageW(cb, CB_FINDSTRINGEXACT, -1,
1119                      (LPARAM)curString);
1120                     if (index >= 0)
1121                         SendMessageW(cb, CB_SETCURSEL, index, 0);
1122                     HeapFree(GetProcessHeap(), 0, curString);
1123                 }
1124                 refresh_store_certs(hwnd);
1125             }
1126             break;
1127         case IDC_MGR_VIEW:
1128         {
1129             HWND lv = GetDlgItem(hwnd, IDC_MGR_CERTS);
1130             int selection = SendMessageW(lv, LVM_GETNEXTITEM, -1,
1131              LVNI_SELECTED);
1132
1133             if (selection >= 0)
1134                 show_selected_cert(hwnd, selection);
1135             break;
1136         }
1137         case IDC_MGR_REMOVE:
1138             cert_mgr_do_remove(hwnd);
1139             break;
1140         case IDCANCEL:
1141             free_certs(GetDlgItem(hwnd, IDC_MGR_CERTS));
1142             close_stores(GetDlgItem(hwnd, IDC_MGR_STORES));
1143             close_stores(GetDlgItem(hwnd, IDC_MGR_STORES));
1144             data = (struct CertMgrData *)GetWindowLongPtrW(hwnd, DWLP_USER);
1145             ImageList_Destroy(data->imageList);
1146             HeapFree(GetProcessHeap(), 0, data);
1147             EndDialog(hwnd, IDCANCEL);
1148             break;
1149         }
1150         break;
1151     }
1152     return 0;
1153 }
1154
1155 /***********************************************************************
1156  *              CryptUIDlgCertMgr (CRYPTUI.@)
1157  */
1158 BOOL WINAPI CryptUIDlgCertMgr(PCCRYPTUI_CERT_MGR_STRUCT pCryptUICertMgr)
1159 {
1160     TRACE("(%p)\n", pCryptUICertMgr);
1161
1162     if (pCryptUICertMgr->dwSize != sizeof(CRYPTUI_CERT_MGR_STRUCT))
1163     {
1164         WARN("unexpected size %d\n", pCryptUICertMgr->dwSize);
1165         SetLastError(E_INVALIDARG);
1166         return FALSE;
1167     }
1168     DialogBoxParamW(hInstance, MAKEINTRESOURCEW(IDD_CERT_MGR),
1169      pCryptUICertMgr->hwndParent, cert_mgr_dlg_proc, (LPARAM)pCryptUICertMgr);
1170     return TRUE;
1171 }
1172
1173 /* FIXME: real names are unknown, functions are undocumented */
1174 typedef struct _CRYPTUI_ENUM_SYSTEM_STORE_ARGS
1175 {
1176     DWORD dwFlags;
1177     void *pvSystemStoreLocationPara;
1178 } CRYPTUI_ENUM_SYSTEM_STORE_ARGS, *PCRYPTUI_ENUM_SYSTEM_STORE_ARGS;
1179
1180 typedef struct _CRYPTUI_ENUM_DATA
1181 {
1182     DWORD                           cStores;
1183     HCERTSTORE                     *rghStore;
1184     DWORD                           cEnumArgs;
1185     PCRYPTUI_ENUM_SYSTEM_STORE_ARGS rgEnumArgs;
1186 } CRYPTUI_ENUM_DATA, *PCRYPTUI_ENUM_DATA;
1187
1188 typedef BOOL (WINAPI *PFN_SELECTED_STORE_CB)(HCERTSTORE store, HWND hwnd,
1189  void *pvArg);
1190
1191 /* Values for dwFlags */
1192 #define CRYPTUI_ENABLE_SHOW_PHYSICAL_STORE 0x00000001
1193
1194 typedef struct _CRYPTUI_SELECTSTORE_INFO_A
1195 {
1196     DWORD                 dwSize;
1197     HWND                  parent;
1198     DWORD                 dwFlags;
1199     LPSTR                 pszTitle;
1200     LPSTR                 pszText;
1201     CRYPTUI_ENUM_DATA    *pEnumData;
1202     PFN_SELECTED_STORE_CB pfnSelectedStoreCallback;
1203     void                 *pvArg;
1204 } CRYPTUI_SELECTSTORE_INFO_A, *PCRYPTUI_SELECTSTORE_INFO_A;
1205
1206 typedef struct _CRYPTUI_SELECTSTORE_INFO_W
1207 {
1208     DWORD                 dwSize;
1209     HWND                  parent;
1210     DWORD                 dwFlags;
1211     LPWSTR                pwszTitle;
1212     LPWSTR                pwszText;
1213     CRYPTUI_ENUM_DATA    *pEnumData;
1214     PFN_SELECTED_STORE_CB pfnSelectedStoreCallback;
1215     void                 *pvArg;
1216 } CRYPTUI_SELECTSTORE_INFO_W, *PCRYPTUI_SELECTSTORE_INFO_W;
1217
1218 struct StoreInfo
1219 {
1220     enum {
1221         StoreHandle,
1222         SystemStore
1223     } type;
1224     union {
1225         HCERTSTORE store;
1226         LPWSTR name;
1227     } DUMMYUNIONNAME;
1228 };
1229
1230 static BOOL WINAPI enum_store_callback(const void *pvSystemStore,
1231  DWORD dwFlags, PCERT_SYSTEM_STORE_INFO pStoreInfo, void *pvReserved,
1232  void *pvArg)
1233 {
1234     HWND tree = GetDlgItem(pvArg, IDC_STORE_LIST);
1235     TVINSERTSTRUCTW tvis;
1236     LPCWSTR localizedName;
1237     BOOL ret = TRUE;
1238
1239     tvis.hParent = NULL;
1240     tvis.hInsertAfter = TVI_LAST;
1241     tvis.u.item.mask = TVIF_TEXT;
1242     if ((localizedName = CryptFindLocalizedName(pvSystemStore)))
1243     {
1244         struct StoreInfo *storeInfo = HeapAlloc(GetProcessHeap(), 0,
1245          sizeof(struct StoreInfo));
1246
1247         if (storeInfo)
1248         {
1249             storeInfo->type = SystemStore;
1250             storeInfo->u.name = HeapAlloc(GetProcessHeap(), 0,
1251              (strlenW(pvSystemStore) + 1) * sizeof(WCHAR));
1252             if (storeInfo->u.name)
1253             {
1254                 tvis.u.item.mask |= TVIF_PARAM;
1255                 tvis.u.item.lParam = (LPARAM)storeInfo;
1256                 strcpyW(storeInfo->u.name, pvSystemStore);
1257             }
1258             else
1259             {
1260                 HeapFree(GetProcessHeap(), 0, storeInfo);
1261                 ret = FALSE;
1262             }
1263         }
1264         else
1265             ret = FALSE;
1266         tvis.u.item.pszText = (LPWSTR)localizedName;
1267     }
1268     else
1269         tvis.u.item.pszText = (LPWSTR)pvSystemStore;
1270     /* FIXME: need a folder icon for the store too */
1271     if (ret)
1272         SendMessageW(tree, TVM_INSERTITEMW, 0, (LPARAM)&tvis);
1273     return ret;
1274 }
1275
1276 static void enumerate_stores(HWND hwnd, CRYPTUI_ENUM_DATA *pEnumData)
1277 {
1278     DWORD i;
1279     HWND tree = GetDlgItem(hwnd, IDC_STORE_LIST);
1280
1281     for (i = 0; i < pEnumData->cEnumArgs; i++)
1282         CertEnumSystemStore(pEnumData->rgEnumArgs[i].dwFlags,
1283          pEnumData->rgEnumArgs[i].pvSystemStoreLocationPara,
1284          hwnd, enum_store_callback);
1285     for (i = 0; i < pEnumData->cStores; i++)
1286     {
1287         DWORD size;
1288
1289         if (CertGetStoreProperty(pEnumData->rghStore[i],
1290          CERT_STORE_LOCALIZED_NAME_PROP_ID, NULL, &size))
1291         {
1292             LPWSTR name = HeapAlloc(GetProcessHeap(), 0, size);
1293
1294             if (name)
1295             {
1296                 if (CertGetStoreProperty(pEnumData->rghStore[i],
1297                  CERT_STORE_LOCALIZED_NAME_PROP_ID, name, &size))
1298                 {
1299                     struct StoreInfo *storeInfo = HeapAlloc(GetProcessHeap(),
1300                      0, sizeof(struct StoreInfo));
1301
1302                     if (storeInfo)
1303                     {
1304                         TVINSERTSTRUCTW tvis;
1305
1306                         storeInfo->type = StoreHandle;
1307                         storeInfo->u.store = pEnumData->rghStore[i];
1308                         tvis.hParent = NULL;
1309                         tvis.hInsertAfter = TVI_LAST;
1310                         tvis.u.item.mask = TVIF_TEXT | TVIF_PARAM;
1311                         tvis.u.item.pszText = name;
1312                         tvis.u.item.lParam = (LPARAM)storeInfo;
1313                         SendMessageW(tree, TVM_INSERTITEMW, 0, (LPARAM)&tvis);
1314                     }
1315                 }
1316                 HeapFree(GetProcessHeap(), 0, name);
1317             }
1318         }
1319     }
1320 }
1321
1322 static void free_store_info(HWND tree)
1323 {
1324     HTREEITEM next = (HTREEITEM)SendMessageW(tree, TVM_GETNEXTITEM, TVGN_CHILD,
1325      (LPARAM)NULL);
1326
1327     while (next)
1328     {
1329         TVITEMW item;
1330
1331         memset(&item, 0, sizeof(item));
1332         item.mask = TVIF_HANDLE | TVIF_PARAM;
1333         item.hItem = next;
1334         SendMessageW(tree, TVM_GETITEMW, 0, (LPARAM)&item);
1335         if (item.lParam)
1336         {
1337             struct StoreInfo *storeInfo = (struct StoreInfo *)item.lParam;
1338
1339             if (storeInfo->type == SystemStore)
1340                 HeapFree(GetProcessHeap(), 0, storeInfo->u.name);
1341             HeapFree(GetProcessHeap(), 0, storeInfo);
1342         }
1343         next = (HTREEITEM)SendMessageW(tree, TVM_GETNEXTITEM, TVGN_NEXT,
1344          (LPARAM)next);
1345     }
1346 }
1347
1348 static HCERTSTORE selected_item_to_store(HWND tree, HTREEITEM hItem)
1349 {
1350     WCHAR buf[MAX_STRING_LEN];
1351     TVITEMW item;
1352     HCERTSTORE store;
1353
1354     memset(&item, 0, sizeof(item));
1355     item.mask = TVIF_HANDLE | TVIF_PARAM | TVIF_TEXT;
1356     item.hItem = hItem;
1357     item.cchTextMax = sizeof(buf) / sizeof(buf[0]);
1358     item.pszText = buf;
1359     SendMessageW(tree, TVM_GETITEMW, 0, (LPARAM)&item);
1360     if (item.lParam)
1361     {
1362         struct StoreInfo *storeInfo = (struct StoreInfo *)item.lParam;
1363
1364         if (storeInfo->type == StoreHandle)
1365             store = storeInfo->u.store;
1366         else
1367             store = CertOpenSystemStoreW(0, storeInfo->u.name);
1368     }
1369     else
1370     {
1371         /* It's implicitly a system store */
1372         store = CertOpenSystemStoreW(0, buf);
1373     }
1374     return store;
1375 }
1376
1377 struct SelectStoreInfo
1378 {
1379     PCRYPTUI_SELECTSTORE_INFO_W info;
1380     HCERTSTORE                  store;
1381 };
1382
1383 static LRESULT CALLBACK select_store_dlg_proc(HWND hwnd, UINT msg, WPARAM wp,
1384  LPARAM lp)
1385 {
1386     struct SelectStoreInfo *selectInfo;
1387     LRESULT ret = 0;
1388
1389     switch (msg)
1390     {
1391     case WM_INITDIALOG:
1392     {
1393         selectInfo = (struct SelectStoreInfo *)lp;
1394         SetWindowLongPtrW(hwnd, DWLP_USER, lp);
1395         if (selectInfo->info->pwszTitle)
1396             SendMessageW(hwnd, WM_SETTEXT, 0,
1397              (LPARAM)selectInfo->info->pwszTitle);
1398         if (selectInfo->info->pwszText)
1399             SendMessageW(GetDlgItem(hwnd, IDC_STORE_TEXT), WM_SETTEXT, 0,
1400              (LPARAM)selectInfo->info->pwszText);
1401         if (!(selectInfo->info->dwFlags & CRYPTUI_ENABLE_SHOW_PHYSICAL_STORE))
1402             ShowWindow(GetDlgItem(hwnd, IDC_SHOW_PHYSICAL_STORES), FALSE);
1403         enumerate_stores(hwnd, selectInfo->info->pEnumData);
1404         break;
1405     }
1406     case WM_COMMAND:
1407         switch (wp)
1408         {
1409         case IDOK:
1410         {
1411             HWND tree = GetDlgItem(hwnd, IDC_STORE_LIST);
1412             HTREEITEM selection = (HTREEITEM)SendMessageW(tree,
1413              TVM_GETNEXTITEM, TVGN_CARET, (LPARAM)NULL);
1414
1415             selectInfo = (struct SelectStoreInfo *)GetWindowLongPtrW(hwnd,
1416              DWLP_USER);
1417             if (!selection)
1418             {
1419                 WCHAR title[MAX_STRING_LEN], error[MAX_STRING_LEN], *pTitle;
1420
1421                 if (selectInfo->info->pwszTitle)
1422                     pTitle = selectInfo->info->pwszTitle;
1423                 else
1424                 {
1425                     LoadStringW(hInstance, IDS_SELECT_STORE_TITLE, title,
1426                      sizeof(title) / sizeof(title[0]));
1427                     pTitle = title;
1428                 }
1429                 LoadStringW(hInstance, IDS_SELECT_STORE, error,
1430                  sizeof(error) / sizeof(error[0]));
1431                 MessageBoxW(hwnd, error, pTitle, MB_ICONEXCLAMATION | MB_OK);
1432             }
1433             else
1434             {
1435                 HCERTSTORE store = selected_item_to_store(tree, selection);
1436
1437                 if (!selectInfo->info->pfnSelectedStoreCallback ||
1438                  selectInfo->info->pfnSelectedStoreCallback(store, hwnd,
1439                  selectInfo->info->pvArg))
1440                 {
1441                     selectInfo->store = store;
1442                     free_store_info(tree);
1443                     EndDialog(hwnd, IDOK);
1444                 }
1445                 else
1446                     CertCloseStore(store, 0);
1447             }
1448             ret = TRUE;
1449             break;
1450         }
1451         case IDCANCEL:
1452             free_store_info(GetDlgItem(hwnd, IDC_STORE_LIST));
1453             EndDialog(hwnd, IDCANCEL);
1454             ret = TRUE;
1455             break;
1456         }
1457         break;
1458     }
1459     return ret;
1460 }
1461
1462 /***********************************************************************
1463  *              CryptUIDlgSelectStoreW (CRYPTUI.@)
1464  */
1465 HCERTSTORE WINAPI CryptUIDlgSelectStoreW(PCRYPTUI_SELECTSTORE_INFO_W info)
1466 {
1467     struct SelectStoreInfo selectInfo = { info, NULL };
1468
1469     TRACE("(%p)\n", info);
1470
1471     if (info->dwSize != sizeof(CRYPTUI_SELECTSTORE_INFO_W))
1472     {
1473         WARN("unexpected size %d\n", info->dwSize);
1474         SetLastError(E_INVALIDARG);
1475         return NULL;
1476     }
1477     DialogBoxParamW(hInstance, MAKEINTRESOURCEW(IDD_SELECT_STORE), info->parent,
1478      select_store_dlg_proc, (LPARAM)&selectInfo);
1479     return selectInfo.store;
1480 }
1481
1482 /***********************************************************************
1483  *              CryptUIDlgSelectStoreA (CRYPTUI.@)
1484  */
1485 HCERTSTORE WINAPI CryptUIDlgSelectStoreA(PCRYPTUI_SELECTSTORE_INFO_A info)
1486 {
1487     CRYPTUI_SELECTSTORE_INFO_W infoW;
1488     HCERTSTORE ret;
1489     int len;
1490
1491     TRACE("(%p)\n", info);
1492
1493     if (info->dwSize != sizeof(CRYPTUI_SELECTSTORE_INFO_A))
1494     {
1495         WARN("unexpected size %d\n", info->dwSize);
1496         SetLastError(E_INVALIDARG);
1497         return NULL;
1498     }
1499     memcpy(&infoW, &info, sizeof(info));
1500     if (info->pszTitle)
1501     {
1502         len = MultiByteToWideChar(CP_ACP, 0, info->pszTitle, -1, NULL, 0);
1503         infoW.pwszTitle = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
1504         MultiByteToWideChar(CP_ACP, 0, info->pszTitle, -1, infoW.pwszTitle,
1505          len);
1506     }
1507     if (info->pszText)
1508     {
1509         len = MultiByteToWideChar(CP_ACP, 0, info->pszText, -1, NULL, 0);
1510         infoW.pwszText = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
1511         MultiByteToWideChar(CP_ACP, 0, info->pszText, -1, infoW.pwszText, len);
1512     }
1513     ret = CryptUIDlgSelectStoreW(&infoW);
1514     HeapFree(GetProcessHeap(), 0, infoW.pwszText);
1515     HeapFree(GetProcessHeap(), 0, infoW.pwszTitle);
1516     return ret;
1517 }
1518
1519 /***********************************************************************
1520  *              CryptUIDlgViewCertificateA (CRYPTUI.@)
1521  */
1522 BOOL WINAPI CryptUIDlgViewCertificateA(
1523  PCCRYPTUI_VIEWCERTIFICATE_STRUCTA pCertViewInfo, BOOL *pfPropertiesChanged)
1524 {
1525     CRYPTUI_VIEWCERTIFICATE_STRUCTW viewInfo;
1526     LPWSTR title = NULL;
1527     BOOL ret;
1528
1529     TRACE("(%p, %p)\n", pCertViewInfo, pfPropertiesChanged);
1530
1531     memcpy(&viewInfo, pCertViewInfo, sizeof(viewInfo));
1532     if (pCertViewInfo->szTitle)
1533     {
1534         int len = MultiByteToWideChar(CP_ACP, 0, pCertViewInfo->szTitle, -1,
1535          NULL, 0);
1536
1537         title = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
1538         if (title)
1539         {
1540             MultiByteToWideChar(CP_ACP, 0, pCertViewInfo->szTitle, -1, title,
1541              len);
1542             viewInfo.szTitle = title;
1543         }
1544         else
1545         {
1546             ret = FALSE;
1547             goto error;
1548         }
1549     }
1550     if (pCertViewInfo->cPropSheetPages)
1551     {
1552         FIXME("ignoring additional prop sheet pages\n");
1553         viewInfo.cPropSheetPages = 0;
1554     }
1555     ret = CryptUIDlgViewCertificateW(&viewInfo, pfPropertiesChanged);
1556     HeapFree(GetProcessHeap(), 0, title);
1557 error:
1558     return ret;
1559 }
1560
1561 struct ReadStringStruct
1562 {
1563     LPCWSTR buf;
1564     LONG pos;
1565     LONG len;
1566 };
1567
1568 static DWORD CALLBACK read_text_callback(DWORD_PTR dwCookie, LPBYTE buf,
1569  LONG cb, LONG *pcb)
1570 {
1571     struct ReadStringStruct *string = (struct ReadStringStruct *)dwCookie;
1572     LONG cch = min(cb / sizeof(WCHAR), string->len - string->pos);
1573
1574     TRACE("(%p, %p, %d, %p)\n", string, buf, cb, pcb);
1575
1576     memmove(buf, string->buf + string->pos, cch * sizeof(WCHAR));
1577     string->pos += cch;
1578     *pcb = cch * sizeof(WCHAR);
1579     return 0;
1580 }
1581
1582 static void add_unformatted_text_to_control(HWND hwnd, LPCWSTR text, LONG len)
1583 {
1584     struct ReadStringStruct string;
1585     EDITSTREAM editstream;
1586
1587     TRACE("(%p, %s)\n", hwnd, debugstr_wn(text, len));
1588
1589     string.buf = text;
1590     string.pos = 0;
1591     string.len = len;
1592     editstream.dwCookie = (DWORD_PTR)&string;
1593     editstream.dwError = 0;
1594     editstream.pfnCallback = read_text_callback;
1595     SendMessageW(hwnd, EM_STREAMIN, SF_TEXT | SFF_SELECTION | SF_UNICODE,
1596      (LPARAM)&editstream);
1597 }
1598
1599 static void add_string_resource_to_control(HWND hwnd, int id)
1600 {
1601     LPWSTR str;
1602     LONG len;
1603
1604     len = LoadStringW(hInstance, id, (LPWSTR)&str, 0);
1605     add_unformatted_text_to_control(hwnd, str, len);
1606 }
1607
1608 static void add_text_with_paraformat_to_control(HWND hwnd, LPCWSTR text,
1609  LONG len, const PARAFORMAT2 *fmt)
1610 {
1611     add_unformatted_text_to_control(hwnd, text, len);
1612     SendMessageW(hwnd, EM_SETPARAFORMAT, 0, (LPARAM)fmt);
1613 }
1614
1615 static void add_string_resource_with_paraformat_to_control(HWND hwnd, int id,
1616  const PARAFORMAT2 *fmt)
1617 {
1618     LPWSTR str;
1619     LONG len;
1620
1621     len = LoadStringW(hInstance, id, (LPWSTR)&str, 0);
1622     add_text_with_paraformat_to_control(hwnd, str, len, fmt);
1623 }
1624
1625 static LPWSTR get_cert_name_string(PCCERT_CONTEXT pCertContext, DWORD dwType,
1626  DWORD dwFlags)
1627 {
1628     LPWSTR buf = NULL;
1629     DWORD len;
1630
1631     len = CertGetNameStringW(pCertContext, dwType, dwFlags, NULL, NULL, 0);
1632     if (len)
1633     {
1634         buf = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
1635         if (buf)
1636             CertGetNameStringW(pCertContext, dwType, dwFlags, NULL, buf, len);
1637     }
1638     return buf;
1639 }
1640
1641 static void add_cert_string_to_control(HWND hwnd, PCCERT_CONTEXT pCertContext,
1642  DWORD dwType, DWORD dwFlags)
1643 {
1644     LPWSTR name = get_cert_name_string(pCertContext, dwType, dwFlags);
1645
1646     if (name)
1647     {
1648         /* Don't include NULL-terminator in output */
1649         DWORD len = lstrlenW(name);
1650
1651         add_unformatted_text_to_control(hwnd, name, len);
1652         HeapFree(GetProcessHeap(), 0, name);
1653     }
1654 }
1655
1656 static void add_icon_to_control(HWND hwnd, int id)
1657 {
1658     HRESULT hr;
1659     LPRICHEDITOLE richEditOle = NULL;
1660     LPOLEOBJECT object = NULL;
1661     CLSID clsid;
1662     LPOLECACHE oleCache = NULL;
1663     FORMATETC formatEtc;
1664     DWORD conn;
1665     LPDATAOBJECT dataObject = NULL;
1666     HBITMAP bitmap = NULL;
1667     RECT rect;
1668     STGMEDIUM stgm;
1669     LPOLECLIENTSITE clientSite = NULL;
1670     REOBJECT reObject;
1671
1672     TRACE("(%p, %d)\n", hwnd, id);
1673
1674     SendMessageW(hwnd, EM_GETOLEINTERFACE, 0, (LPARAM)&richEditOle);
1675     if (!richEditOle)
1676         goto end;
1677     hr = OleCreateDefaultHandler(&CLSID_NULL, NULL, &IID_IOleObject,
1678      (void**)&object);
1679     if (FAILED(hr))
1680         goto end;
1681     hr = IOleObject_GetUserClassID(object, &clsid);
1682     if (FAILED(hr))
1683         goto end;
1684     hr = IOleObject_QueryInterface(object, &IID_IOleCache, (void**)&oleCache);
1685     if (FAILED(hr))
1686         goto end;
1687     formatEtc.cfFormat = CF_BITMAP;
1688     formatEtc.ptd = NULL;
1689     formatEtc.dwAspect = DVASPECT_CONTENT;
1690     formatEtc.lindex = -1;
1691     formatEtc.tymed = TYMED_GDI;
1692     hr = IOleCache_Cache(oleCache, &formatEtc, 0, &conn);
1693     if (FAILED(hr))
1694         goto end;
1695     hr = IOleObject_QueryInterface(object, &IID_IDataObject,
1696      (void**)&dataObject);
1697     if (FAILED(hr))
1698         goto end;
1699     hr = IRichEditOle_GetClientSite(richEditOle, &clientSite);
1700     if (FAILED(hr))
1701         goto end;
1702     bitmap = LoadImageW(hInstance, MAKEINTRESOURCEW(id), IMAGE_BITMAP, 0, 0,
1703      LR_DEFAULTSIZE | LR_LOADTRANSPARENT);
1704     if (!bitmap)
1705         goto end;
1706     rect.left = rect.top = 0;
1707     rect.right = GetSystemMetrics(SM_CXICON);
1708     rect.bottom = GetSystemMetrics(SM_CYICON);
1709     stgm.tymed = TYMED_GDI;
1710     stgm.u.hBitmap = bitmap;
1711     stgm.pUnkForRelease = NULL;
1712     hr = IDataObject_SetData(dataObject, &formatEtc, &stgm, TRUE);
1713     if (FAILED(hr))
1714         goto end;
1715
1716     reObject.cbStruct = sizeof(reObject);
1717     reObject.cp = REO_CP_SELECTION;
1718     reObject.clsid = clsid;
1719     reObject.poleobj = object;
1720     reObject.pstg = NULL;
1721     reObject.polesite = clientSite;
1722     reObject.sizel.cx = reObject.sizel.cy = 0;
1723     reObject.dvaspect = DVASPECT_CONTENT;
1724     reObject.dwFlags = 0;
1725     reObject.dwUser = 0;
1726
1727     IRichEditOle_InsertObject(richEditOle, &reObject);
1728
1729 end:
1730     if (clientSite)
1731         IOleClientSite_Release(clientSite);
1732     if (dataObject)
1733         IDataObject_Release(dataObject);
1734     if (oleCache)
1735         IOleCache_Release(oleCache);
1736     if (object)
1737         IOleObject_Release(object);
1738     if (richEditOle)
1739         IRichEditOle_Release(richEditOle);
1740 }
1741
1742 #define MY_INDENT 200
1743
1744 static void add_oid_text_to_control(HWND hwnd, char *oid)
1745 {
1746     WCHAR nl = '\n';
1747     PCCRYPT_OID_INFO oidInfo = CryptFindOIDInfo(CRYPT_OID_INFO_OID_KEY, oid, 0);
1748     PARAFORMAT2 parFmt;
1749
1750     parFmt.cbSize = sizeof(parFmt);
1751     parFmt.dwMask = PFM_STARTINDENT;
1752     parFmt.dxStartIndent = MY_INDENT * 3;
1753     if (oidInfo)
1754     {
1755         add_text_with_paraformat_to_control(hwnd, oidInfo->pwszName,
1756          lstrlenW(oidInfo->pwszName), &parFmt);
1757         add_unformatted_text_to_control(hwnd, &nl, 1);
1758     }
1759 }
1760
1761 struct OIDToString
1762 {
1763     LPCSTR oid;
1764     int    id;
1765 };
1766
1767 /* The following list MUST be lexicographically sorted by OID */
1768 static struct OIDToString oidMap[] = {
1769  /* 1.3.6.1.4.1.311.10.3.1 */
1770  { szOID_KP_CTL_USAGE_SIGNING, IDS_PURPOSE_CTL_USAGE_SIGNING },
1771  /* 1.3.6.1.4.1.311.10.3.4 */
1772  { szOID_KP_EFS, IDS_PURPOSE_EFS },
1773  /* 1.3.6.1.4.1.311.10.3.4.1 */
1774  { szOID_EFS_RECOVERY, IDS_PURPOSE_EFS_RECOVERY },
1775  /* 1.3.6.1.4.1.311.10.3.5 */
1776  { szOID_WHQL_CRYPTO, IDS_PURPOSE_WHQL },
1777  /* 1.3.6.1.4.1.311.10.3.6 */
1778  { szOID_NT5_CRYPTO, IDS_PURPOSE_NT5 },
1779  /* 1.3.6.1.4.1.311.10.3.7 */
1780  { szOID_OEM_WHQL_CRYPTO, IDS_PURPOSE_OEM_WHQL },
1781  /* 1.3.6.1.4.1.311.10.3.8 */
1782  { szOID_EMBEDDED_NT_CRYPTO, IDS_PURPOSE_EMBEDDED_NT },
1783  /* 1.3.6.1.4.1.311.10.3.9 */
1784  { szOID_ROOT_LIST_SIGNER, IDS_PURPOSE_ROOT_LIST_SIGNER },
1785  /* 1.3.6.1.4.1.311.10.3.10 */
1786  { szOID_KP_QUALIFIED_SUBORDINATION, IDS_PURPOSE_QUALIFIED_SUBORDINATION },
1787  /* 1.3.6.1.4.1.311.10.3.11 */
1788  { szOID_KP_KEY_RECOVERY, IDS_PURPOSE_KEY_RECOVERY },
1789  /* 1.3.6.1.4.1.311.10.3.12 */
1790  { szOID_KP_DOCUMENT_SIGNING, IDS_PURPOSE_DOCUMENT_SIGNING },
1791  /* 1.3.6.1.4.1.311.10.3.13 */
1792  { szOID_KP_LIFETIME_SIGNING, IDS_PURPOSE_LIFETIME_SIGNING },
1793  /* 1.3.6.1.4.1.311.10.5.1 */
1794  { szOID_DRM, IDS_PURPOSE_DRM },
1795  /* 1.3.6.1.4.1.311.10.6.1 */
1796  { szOID_LICENSES, IDS_PURPOSE_LICENSES },
1797  /* 1.3.6.1.4.1.311.10.6.2 */
1798  { szOID_LICENSE_SERVER, IDS_PURPOSE_LICENSE_SERVER },
1799  /* 1.3.6.1.4.1.311.20.2.1 */
1800  { szOID_ENROLLMENT_AGENT, IDS_PURPOSE_ENROLLMENT_AGENT },
1801  /* 1.3.6.1.4.1.311.20.2.2 */
1802  { szOID_KP_SMARTCARD_LOGON, IDS_PURPOSE_SMARTCARD_LOGON },
1803  /* 1.3.6.1.4.1.311.21.5 */
1804  { szOID_KP_CA_EXCHANGE, IDS_PURPOSE_CA_EXCHANGE },
1805  /* 1.3.6.1.4.1.311.21.6 */
1806  { szOID_KP_KEY_RECOVERY_AGENT, IDS_PURPOSE_KEY_RECOVERY_AGENT },
1807  /* 1.3.6.1.4.1.311.21.19 */
1808  { szOID_DS_EMAIL_REPLICATION, IDS_PURPOSE_DS_EMAIL_REPLICATION },
1809  /* 1.3.6.1.5.5.7.3.1 */
1810  { szOID_PKIX_KP_SERVER_AUTH, IDS_PURPOSE_SERVER_AUTH },
1811  /* 1.3.6.1.5.5.7.3.2 */
1812  { szOID_PKIX_KP_CLIENT_AUTH, IDS_PURPOSE_CLIENT_AUTH },
1813  /* 1.3.6.1.5.5.7.3.3 */
1814  { szOID_PKIX_KP_CODE_SIGNING, IDS_PURPOSE_CODE_SIGNING },
1815  /* 1.3.6.1.5.5.7.3.4 */
1816  { szOID_PKIX_KP_EMAIL_PROTECTION, IDS_PURPOSE_EMAIL_PROTECTION },
1817  /* 1.3.6.1.5.5.7.3.5 */
1818  { szOID_PKIX_KP_IPSEC_END_SYSTEM, IDS_PURPOSE_IPSEC },
1819  /* 1.3.6.1.5.5.7.3.6 */
1820  { szOID_PKIX_KP_IPSEC_TUNNEL, IDS_PURPOSE_IPSEC },
1821  /* 1.3.6.1.5.5.7.3.7 */
1822  { szOID_PKIX_KP_IPSEC_USER, IDS_PURPOSE_IPSEC },
1823  /* 1.3.6.1.5.5.7.3.8 */
1824  { szOID_PKIX_KP_TIMESTAMP_SIGNING, IDS_PURPOSE_TIMESTAMP_SIGNING },
1825 };
1826
1827 static struct OIDToString *findSupportedOID(LPCSTR oid)
1828 {
1829     int indexHigh = sizeof(oidMap) / sizeof(oidMap[0]) - 1, indexLow = 0, i;
1830     struct OIDToString *ret = NULL;
1831
1832     for (i = (indexLow + indexHigh) / 2; !ret && indexLow <= indexHigh;
1833      i = (indexLow + indexHigh) / 2)
1834     {
1835         int cmp;
1836
1837         cmp = strcmp(oid, oidMap[i].oid);
1838         if (!cmp)
1839             ret = &oidMap[i];
1840         else if (cmp > 0)
1841             indexLow = i + 1;
1842         else
1843             indexHigh = i - 1;
1844     }
1845     return ret;
1846 }
1847
1848 static void add_local_oid_text_to_control(HWND text, LPCSTR oid)
1849 {
1850     struct OIDToString *entry;
1851     WCHAR nl = '\n';
1852     PARAFORMAT2 parFmt;
1853
1854     parFmt.cbSize = sizeof(parFmt);
1855     parFmt.dwMask = PFM_STARTINDENT;
1856     parFmt.dxStartIndent = MY_INDENT * 3;
1857     if ((entry = findSupportedOID(oid)))
1858     {
1859         WCHAR *str, *linebreak, *ptr;
1860         BOOL multiline = FALSE;
1861         int len;
1862
1863         len = LoadStringW(hInstance, entry->id, (LPWSTR)&str, 0);
1864         ptr = str;
1865         do {
1866             if ((linebreak = memchrW(ptr, '\n', len)))
1867             {
1868                 WCHAR copy[MAX_STRING_LEN];
1869
1870                 multiline = TRUE;
1871                 /* The source string contains a newline, which the richedit
1872                  * control won't find since it's interpreted as a paragraph
1873                  * break.  Therefore copy up to the newline.  lstrcpynW always
1874                  * NULL-terminates, so pass one more than the length of the
1875                  * source line so the copy includes the entire line and the
1876                  * NULL-terminator.
1877                  */
1878                 lstrcpynW(copy, ptr, linebreak - ptr + 1);
1879                 add_text_with_paraformat_to_control(text, copy,
1880                  linebreak - ptr, &parFmt);
1881                 ptr = linebreak + 1;
1882                 add_unformatted_text_to_control(text, &nl, 1);
1883             }
1884             else if (multiline && *ptr)
1885             {
1886                 /* Add the last line */
1887                 add_text_with_paraformat_to_control(text, ptr,
1888                  len - (ptr - str), &parFmt);
1889                 add_unformatted_text_to_control(text, &nl, 1);
1890             }
1891         } while (linebreak);
1892         if (!multiline)
1893         {
1894             add_text_with_paraformat_to_control(text, str, len, &parFmt);
1895             add_unformatted_text_to_control(text, &nl, 1);
1896         }
1897     }
1898     else
1899     {
1900         WCHAR *oidW = HeapAlloc(GetProcessHeap(), 0,
1901          (strlen(oid) + 1) * sizeof(WCHAR));
1902
1903         if (oidW)
1904         {
1905             LPCSTR src;
1906             WCHAR *dst;
1907
1908             for (src = oid, dst = oidW; *src; src++, dst++)
1909                 *dst = *src;
1910             *dst = 0;
1911             add_text_with_paraformat_to_control(text, oidW, lstrlenW(oidW),
1912              &parFmt);
1913             add_unformatted_text_to_control(text, &nl, 1);
1914             HeapFree(GetProcessHeap(), 0, oidW);
1915         }
1916     }
1917 }
1918
1919 static void display_app_usages(HWND text, PCCERT_CONTEXT cert,
1920  BOOL *anyUsageAdded)
1921 {
1922     static char any_app_policy[] = szOID_ANY_APPLICATION_POLICY;
1923     WCHAR nl = '\n';
1924     CHARFORMATW charFmt;
1925     PCERT_EXTENSION policyExt;
1926     if (!*anyUsageAdded)
1927     {
1928         PARAFORMAT2 parFmt;
1929
1930         parFmt.cbSize = sizeof(parFmt);
1931         parFmt.dwMask = PFM_STARTINDENT;
1932         parFmt.dxStartIndent = MY_INDENT;
1933         add_string_resource_with_paraformat_to_control(text,
1934          IDS_CERT_INFO_PURPOSES, &parFmt);
1935         add_unformatted_text_to_control(text, &nl, 1);
1936         *anyUsageAdded = TRUE;
1937     }
1938     memset(&charFmt, 0, sizeof(charFmt));
1939     charFmt.cbSize = sizeof(charFmt);
1940     charFmt.dwMask = CFM_BOLD;
1941     charFmt.dwEffects = 0;
1942     SendMessageW(text, EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&charFmt);
1943     if ((policyExt = CertFindExtension(szOID_APPLICATION_CERT_POLICIES,
1944      cert->pCertInfo->cExtension, cert->pCertInfo->rgExtension)))
1945     {
1946         CERT_POLICIES_INFO *policies;
1947         DWORD size;
1948
1949         if (CryptDecodeObjectEx(X509_ASN_ENCODING, X509_CERT_POLICIES,
1950          policyExt->Value.pbData, policyExt->Value.cbData,
1951          CRYPT_DECODE_ALLOC_FLAG, NULL, &policies, &size))
1952         {
1953             DWORD i;
1954
1955             for (i = 0; i < policies->cPolicyInfo; i++)
1956             {
1957                 DWORD j;
1958
1959                 for (j = 0; j < policies->rgPolicyInfo[i].cPolicyQualifier; j++)
1960                     add_local_oid_text_to_control(text,
1961                      policies->rgPolicyInfo[i].rgPolicyQualifier[j].
1962                      pszPolicyQualifierId);
1963             }
1964             LocalFree(policies);
1965         }
1966     }
1967     else
1968         add_oid_text_to_control(text, any_app_policy);
1969 }
1970
1971 static BOOL display_cert_usages(HWND text, PCCERT_CONTEXT cert,
1972  BOOL *anyUsageAdded)
1973 {
1974     WCHAR nl = '\n';
1975     DWORD size;
1976     BOOL badUsages = FALSE;
1977
1978     if (CertGetEnhancedKeyUsage(cert, 0, NULL, &size))
1979     {
1980         CHARFORMATW charFmt;
1981         static char any_cert_policy[] = szOID_ANY_CERT_POLICY;
1982         PCERT_ENHKEY_USAGE usage = HeapAlloc(GetProcessHeap(), 0, size);
1983
1984         if (usage)
1985         {
1986             if (CertGetEnhancedKeyUsage(cert, 0, usage, &size))
1987             {
1988                 DWORD i;
1989
1990                 if (!*anyUsageAdded)
1991                 {
1992                     PARAFORMAT2 parFmt;
1993
1994                     parFmt.cbSize = sizeof(parFmt);
1995                     parFmt.dwMask = PFM_STARTINDENT;
1996                     parFmt.dxStartIndent = MY_INDENT;
1997                     add_string_resource_with_paraformat_to_control(text,
1998                      IDS_CERT_INFO_PURPOSES, &parFmt);
1999                     add_unformatted_text_to_control(text, &nl, 1);
2000                     *anyUsageAdded = TRUE;
2001                 }
2002                 memset(&charFmt, 0, sizeof(charFmt));
2003                 charFmt.cbSize = sizeof(charFmt);
2004                 charFmt.dwMask = CFM_BOLD;
2005                 charFmt.dwEffects = 0;
2006                 SendMessageW(text, EM_SETCHARFORMAT, SCF_SELECTION,
2007                  (LPARAM)&charFmt);
2008                 if (!usage->cUsageIdentifier)
2009                     add_oid_text_to_control(text, any_cert_policy);
2010                 else
2011                     for (i = 0; i < usage->cUsageIdentifier; i++)
2012                         add_local_oid_text_to_control(text,
2013                          usage->rgpszUsageIdentifier[i]);
2014             }
2015             else
2016                 badUsages = TRUE;
2017             HeapFree(GetProcessHeap(), 0, usage);
2018         }
2019         else
2020             badUsages = TRUE;
2021     }
2022     else
2023         badUsages = TRUE;
2024     return badUsages;
2025 }
2026
2027 static void set_policy_text(HWND text,
2028  PCCRYPTUI_VIEWCERTIFICATE_STRUCTW pCertViewInfo)
2029 {
2030     BOOL includeCertUsages = FALSE, includeAppUsages = FALSE;
2031     BOOL badUsages = FALSE, anyUsageAdded = FALSE;
2032
2033     if (pCertViewInfo->cPurposes)
2034     {
2035         DWORD i;
2036
2037         for (i = 0; i < pCertViewInfo->cPurposes; i++)
2038         {
2039             if (!strcmp(pCertViewInfo->rgszPurposes[i], szOID_ANY_CERT_POLICY))
2040                 includeCertUsages = TRUE;
2041             else if (!strcmp(pCertViewInfo->rgszPurposes[i],
2042              szOID_ANY_APPLICATION_POLICY))
2043                 includeAppUsages = TRUE;
2044             else
2045                 badUsages = TRUE;
2046         }
2047     }
2048     else
2049         includeAppUsages = includeCertUsages = TRUE;
2050     if (includeAppUsages)
2051         display_app_usages(text, pCertViewInfo->pCertContext, &anyUsageAdded);
2052     if (includeCertUsages)
2053         badUsages = display_cert_usages(text, pCertViewInfo->pCertContext,
2054          &anyUsageAdded);
2055     if (badUsages)
2056     {
2057         PARAFORMAT2 parFmt;
2058
2059         parFmt.cbSize = sizeof(parFmt);
2060         parFmt.dwMask = PFM_STARTINDENT;
2061         parFmt.dxStartIndent = MY_INDENT;
2062         add_string_resource_with_paraformat_to_control(text,
2063          IDS_CERT_INFO_BAD_PURPOSES, &parFmt);
2064     }
2065 }
2066
2067 static CRYPT_OBJID_BLOB *find_policy_qualifier(CERT_POLICIES_INFO *policies,
2068  LPCSTR policyOid)
2069 {
2070     CRYPT_OBJID_BLOB *ret = NULL;
2071     DWORD i;
2072
2073     for (i = 0; !ret && i < policies->cPolicyInfo; i++)
2074     {
2075         DWORD j;
2076
2077         for (j = 0; !ret && j < policies->rgPolicyInfo[i].cPolicyQualifier; j++)
2078             if (!strcmp(policies->rgPolicyInfo[i].rgPolicyQualifier[j].
2079              pszPolicyQualifierId, policyOid))
2080                 ret = &policies->rgPolicyInfo[i].rgPolicyQualifier[j].
2081                  Qualifier;
2082     }
2083     return ret;
2084 }
2085
2086 static WCHAR *get_cps_str_from_qualifier(CRYPT_OBJID_BLOB *qualifier)
2087 {
2088     LPWSTR qualifierStr = NULL;
2089     CERT_NAME_VALUE *qualifierValue;
2090     DWORD size;
2091
2092     if (CryptDecodeObjectEx(X509_ASN_ENCODING, X509_NAME_VALUE,
2093      qualifier->pbData, qualifier->cbData, CRYPT_DECODE_ALLOC_FLAG, NULL,
2094      &qualifierValue, &size))
2095     {
2096         size = CertRDNValueToStrW(qualifierValue->dwValueType,
2097          &qualifierValue->Value, NULL, 0);
2098         qualifierStr = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
2099         if (qualifierStr)
2100             CertRDNValueToStrW(qualifierValue->dwValueType,
2101              &qualifierValue->Value, qualifierStr, size);
2102         LocalFree(qualifierValue);
2103     }
2104     return qualifierStr;
2105 }
2106
2107 static WCHAR *get_user_notice_from_qualifier(CRYPT_OBJID_BLOB *qualifier)
2108 {
2109     LPWSTR str = NULL;
2110     CERT_POLICY_QUALIFIER_USER_NOTICE *qualifierValue;
2111     DWORD size;
2112
2113     if (CryptDecodeObjectEx(X509_ASN_ENCODING,
2114      X509_PKIX_POLICY_QUALIFIER_USERNOTICE,
2115      qualifier->pbData, qualifier->cbData, CRYPT_DECODE_ALLOC_FLAG, NULL,
2116      &qualifierValue, &size))
2117     {
2118         str = HeapAlloc(GetProcessHeap(), 0,
2119          (strlenW(qualifierValue->pszDisplayText) + 1) * sizeof(WCHAR));
2120         if (str)
2121             strcpyW(str, qualifierValue->pszDisplayText);
2122         LocalFree(qualifierValue);
2123     }
2124     return str;
2125 }
2126
2127 struct IssuerStatement
2128 {
2129     LPWSTR cps;
2130     LPWSTR userNotice;
2131 };
2132
2133 static void set_issuer_statement(HWND hwnd,
2134  PCCRYPTUI_VIEWCERTIFICATE_STRUCTW pCertViewInfo)
2135 {
2136     PCERT_EXTENSION policyExt;
2137
2138     if (!(pCertViewInfo->dwFlags & CRYPTUI_DISABLE_ISSUERSTATEMENT) &&
2139      (policyExt = CertFindExtension(szOID_CERT_POLICIES,
2140      pCertViewInfo->pCertContext->pCertInfo->cExtension,
2141      pCertViewInfo->pCertContext->pCertInfo->rgExtension)))
2142     {
2143         CERT_POLICIES_INFO *policies;
2144         DWORD size;
2145
2146         if (CryptDecodeObjectEx(X509_ASN_ENCODING, policyExt->pszObjId,
2147          policyExt->Value.pbData, policyExt->Value.cbData,
2148          CRYPT_DECODE_ALLOC_FLAG, NULL, &policies, &size))
2149         {
2150             CRYPT_OBJID_BLOB *qualifier;
2151             LPWSTR cps = NULL, userNotice = NULL;
2152
2153             if ((qualifier = find_policy_qualifier(policies,
2154              szOID_PKIX_POLICY_QUALIFIER_CPS)))
2155                 cps = get_cps_str_from_qualifier(qualifier);
2156             if ((qualifier = find_policy_qualifier(policies,
2157              szOID_PKIX_POLICY_QUALIFIER_USERNOTICE)))
2158                 userNotice = get_user_notice_from_qualifier(qualifier);
2159             if (cps || userNotice)
2160             {
2161                 struct IssuerStatement *issuerStatement =
2162                  HeapAlloc(GetProcessHeap(), 0, sizeof(struct IssuerStatement));
2163
2164                 if (issuerStatement)
2165                 {
2166                     issuerStatement->cps = cps;
2167                     issuerStatement->userNotice = userNotice;
2168                     EnableWindow(GetDlgItem(hwnd, IDC_ISSUERSTATEMENT), TRUE);
2169                     SetWindowLongPtrW(hwnd, DWLP_USER,
2170                      (ULONG_PTR)issuerStatement);
2171                 }
2172             }
2173             LocalFree(policies);
2174         }
2175     }
2176 }
2177
2178 static void set_cert_info(HWND hwnd,
2179  PCCRYPTUI_VIEWCERTIFICATE_STRUCTW pCertViewInfo)
2180 {
2181     CHARFORMATW charFmt;
2182     PARAFORMAT2 parFmt;
2183     HWND icon = GetDlgItem(hwnd, IDC_CERTIFICATE_ICON);
2184     HWND text = GetDlgItem(hwnd, IDC_CERTIFICATE_INFO);
2185     CRYPT_PROVIDER_SGNR *provSigner = WTHelperGetProvSignerFromChain(
2186      (CRYPT_PROVIDER_DATA *)pCertViewInfo->u.pCryptProviderData,
2187      pCertViewInfo->idxSigner, pCertViewInfo->fCounterSigner,
2188      pCertViewInfo->idxCounterSigner);
2189     CRYPT_PROVIDER_CERT *root =
2190      &provSigner->pasCertChain[provSigner->csCertChain - 1];
2191
2192     if (!provSigner->pChainContext ||
2193      (provSigner->pChainContext->TrustStatus.dwErrorStatus &
2194      CERT_TRUST_IS_PARTIAL_CHAIN))
2195         add_icon_to_control(icon, IDB_CERT_WARNING);
2196     else if (!root->fTrustedRoot)
2197         add_icon_to_control(icon, IDB_CERT_ERROR);
2198     else
2199         add_icon_to_control(icon, IDB_CERT);
2200
2201     memset(&charFmt, 0, sizeof(charFmt));
2202     charFmt.cbSize = sizeof(charFmt);
2203     charFmt.dwMask = CFM_BOLD;
2204     charFmt.dwEffects = CFE_BOLD;
2205     SendMessageW(text, EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&charFmt);
2206     /* FIXME: vertically center text */
2207     parFmt.cbSize = sizeof(parFmt);
2208     parFmt.dwMask = PFM_STARTINDENT;
2209     parFmt.dxStartIndent = MY_INDENT;
2210     add_string_resource_with_paraformat_to_control(text,
2211      IDS_CERTIFICATEINFORMATION, &parFmt);
2212
2213     text = GetDlgItem(hwnd, IDC_CERTIFICATE_STATUS);
2214     SendMessageW(text, EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&charFmt);
2215     if (provSigner->dwError == TRUST_E_CERT_SIGNATURE)
2216         add_string_resource_with_paraformat_to_control(text,
2217          IDS_CERT_INFO_BAD_SIG, &parFmt);
2218     else if (!provSigner->pChainContext ||
2219      (provSigner->pChainContext->TrustStatus.dwErrorStatus &
2220      CERT_TRUST_IS_PARTIAL_CHAIN))
2221         add_string_resource_with_paraformat_to_control(text,
2222          IDS_CERT_INFO_PARTIAL_CHAIN, &parFmt);
2223     else if (!root->fTrustedRoot)
2224     {
2225         if (provSigner->csCertChain == 1 && root->fSelfSigned)
2226             add_string_resource_with_paraformat_to_control(text,
2227              IDS_CERT_INFO_UNTRUSTED_CA, &parFmt);
2228         else
2229             add_string_resource_with_paraformat_to_control(text,
2230              IDS_CERT_INFO_UNTRUSTED_ROOT, &parFmt);
2231     }
2232     else
2233     {
2234         set_policy_text(text, pCertViewInfo);
2235         set_issuer_statement(hwnd, pCertViewInfo);
2236     }
2237 }
2238
2239 static void set_cert_name_string(HWND hwnd, PCCERT_CONTEXT cert,
2240  DWORD nameFlags, int heading)
2241 {
2242     WCHAR nl = '\n';
2243     HWND text = GetDlgItem(hwnd, IDC_CERTIFICATE_NAMES);
2244     CHARFORMATW charFmt;
2245     PARAFORMAT2 parFmt;
2246
2247     memset(&charFmt, 0, sizeof(charFmt));
2248     charFmt.cbSize = sizeof(charFmt);
2249     charFmt.dwMask = CFM_BOLD;
2250     charFmt.dwEffects = CFE_BOLD;
2251     SendMessageW(text, EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&charFmt);
2252     parFmt.cbSize = sizeof(parFmt);
2253     parFmt.dwMask = PFM_STARTINDENT;
2254     parFmt.dxStartIndent = MY_INDENT * 3;
2255     add_string_resource_with_paraformat_to_control(text, heading, &parFmt);
2256     charFmt.dwEffects = 0;
2257     SendMessageW(text, EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&charFmt);
2258     add_cert_string_to_control(text, cert, CERT_NAME_SIMPLE_DISPLAY_TYPE,
2259      nameFlags);
2260     add_unformatted_text_to_control(text, &nl, 1);
2261     add_unformatted_text_to_control(text, &nl, 1);
2262     add_unformatted_text_to_control(text, &nl, 1);
2263
2264 }
2265
2266 static void add_date_string_to_control(HWND hwnd, const FILETIME *fileTime)
2267 {
2268     WCHAR dateFmt[80]; /* sufficient for all versions of LOCALE_SSHORTDATE */
2269     WCHAR date[80];
2270     SYSTEMTIME sysTime;
2271
2272     GetLocaleInfoW(LOCALE_SYSTEM_DEFAULT, LOCALE_SSHORTDATE, dateFmt,
2273      sizeof(dateFmt) / sizeof(dateFmt[0]));
2274     FileTimeToSystemTime(fileTime, &sysTime);
2275     GetDateFormatW(LOCALE_SYSTEM_DEFAULT, 0, &sysTime, dateFmt, date,
2276      sizeof(date) / sizeof(date[0]));
2277     add_unformatted_text_to_control(hwnd, date, lstrlenW(date));
2278 }
2279
2280 static void set_cert_validity_period(HWND hwnd, PCCERT_CONTEXT cert)
2281 {
2282     WCHAR nl = '\n';
2283     HWND text = GetDlgItem(hwnd, IDC_CERTIFICATE_NAMES);
2284     CHARFORMATW charFmt;
2285     PARAFORMAT2 parFmt;
2286
2287     memset(&charFmt, 0, sizeof(charFmt));
2288     charFmt.cbSize = sizeof(charFmt);
2289     charFmt.dwMask = CFM_BOLD;
2290     charFmt.dwEffects = CFE_BOLD;
2291     SendMessageW(text, EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&charFmt);
2292     parFmt.cbSize = sizeof(parFmt);
2293     parFmt.dwMask = PFM_STARTINDENT;
2294     parFmt.dxStartIndent = MY_INDENT * 3;
2295     add_string_resource_with_paraformat_to_control(text, IDS_VALID_FROM,
2296      &parFmt);
2297     charFmt.dwEffects = 0;
2298     SendMessageW(text, EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&charFmt);
2299     add_date_string_to_control(text, &cert->pCertInfo->NotBefore);
2300     charFmt.dwEffects = CFE_BOLD;
2301     SendMessageW(text, EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&charFmt);
2302     add_string_resource_to_control(text, IDS_VALID_TO);
2303     charFmt.dwEffects = 0;
2304     SendMessageW(text, EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&charFmt);
2305     add_date_string_to_control(text, &cert->pCertInfo->NotAfter);
2306     add_unformatted_text_to_control(text, &nl, 1);
2307 }
2308
2309 static void set_general_info(HWND hwnd,
2310  PCCRYPTUI_VIEWCERTIFICATE_STRUCTW pCertViewInfo)
2311 {
2312     set_cert_info(hwnd, pCertViewInfo);
2313     set_cert_name_string(hwnd, pCertViewInfo->pCertContext, 0,
2314      IDS_SUBJECT_HEADING);
2315     set_cert_name_string(hwnd, pCertViewInfo->pCertContext,
2316      CERT_NAME_ISSUER_FLAG, IDS_ISSUER_HEADING);
2317     set_cert_validity_period(hwnd, pCertViewInfo->pCertContext);
2318 }
2319
2320 static LRESULT CALLBACK user_notice_dlg_proc(HWND hwnd, UINT msg, WPARAM wp,
2321  LPARAM lp)
2322 {
2323     LRESULT ret = 0;
2324     HWND text;
2325     struct IssuerStatement *issuerStatement;
2326
2327     switch (msg)
2328     {
2329     case WM_INITDIALOG:
2330         text = GetDlgItem(hwnd, IDC_USERNOTICE);
2331         issuerStatement = (struct IssuerStatement *)lp;
2332         add_unformatted_text_to_control(text, issuerStatement->userNotice,
2333          strlenW(issuerStatement->userNotice));
2334         if (issuerStatement->cps)
2335             SetWindowLongPtrW(hwnd, DWLP_USER, (LPARAM)issuerStatement->cps);
2336         else
2337             EnableWindow(GetDlgItem(hwnd, IDC_CPS), FALSE);
2338         break;
2339     case WM_COMMAND:
2340         switch (wp)
2341         {
2342         case IDOK:
2343             EndDialog(hwnd, IDOK);
2344             ret = TRUE;
2345             break;
2346         case IDC_CPS:
2347         {
2348             IBindCtx *bctx = NULL;
2349             LPWSTR cps;
2350
2351             CreateBindCtx(0, &bctx);
2352             cps = (LPWSTR)GetWindowLongPtrW(hwnd, DWLP_USER);
2353             HlinkSimpleNavigateToString(cps, NULL, NULL, NULL, bctx, NULL,
2354              HLNF_OPENINNEWWINDOW, 0);
2355             IBindCtx_Release(bctx);
2356             break;
2357         }
2358         }
2359     }
2360     return ret;
2361 }
2362
2363 static void show_user_notice(HWND hwnd, struct IssuerStatement *issuerStatement)
2364 {
2365     DialogBoxParamW(hInstance, MAKEINTRESOURCEW(IDD_USERNOTICE), hwnd,
2366      user_notice_dlg_proc, (LPARAM)issuerStatement);
2367 }
2368
2369 static LRESULT CALLBACK general_dlg_proc(HWND hwnd, UINT msg, WPARAM wp,
2370  LPARAM lp)
2371 {
2372     PROPSHEETPAGEW *page;
2373     PCCRYPTUI_VIEWCERTIFICATE_STRUCTW pCertViewInfo;
2374
2375     TRACE("(%p, %08x, %08lx, %08lx)\n", hwnd, msg, wp, lp);
2376
2377     switch (msg)
2378     {
2379     case WM_INITDIALOG:
2380         page = (PROPSHEETPAGEW *)lp;
2381         pCertViewInfo = (PCCRYPTUI_VIEWCERTIFICATE_STRUCTW)page->lParam;
2382         if (pCertViewInfo->dwFlags & CRYPTUI_DISABLE_ADDTOSTORE)
2383             ShowWindow(GetDlgItem(hwnd, IDC_ADDTOSTORE), FALSE);
2384         EnableWindow(GetDlgItem(hwnd, IDC_ISSUERSTATEMENT), FALSE);
2385         set_general_info(hwnd, pCertViewInfo);
2386         break;
2387     case WM_COMMAND:
2388         switch (wp)
2389         {
2390         case IDC_ADDTOSTORE:
2391             CryptUIWizImport(0, hwnd, NULL, NULL, NULL);
2392             break;
2393         case IDC_ISSUERSTATEMENT:
2394         {
2395             struct IssuerStatement *issuerStatement =
2396              (struct IssuerStatement *)GetWindowLongPtrW(hwnd, DWLP_USER);
2397
2398             if (issuerStatement)
2399             {
2400                 if (issuerStatement->userNotice)
2401                     show_user_notice(hwnd, issuerStatement);
2402                 else if (issuerStatement->cps)
2403                 {
2404                     IBindCtx *bctx = NULL;
2405
2406                     CreateBindCtx(0, &bctx);
2407                     HlinkSimpleNavigateToString(issuerStatement->cps, NULL,
2408                      NULL, NULL, bctx, NULL, HLNF_OPENINNEWWINDOW, 0);
2409                     IBindCtx_Release(bctx);
2410                 }
2411             }
2412             break;
2413         }
2414         }
2415         break;
2416     }
2417     return 0;
2418 }
2419
2420 static UINT CALLBACK general_callback_proc(HWND hwnd, UINT msg,
2421  PROPSHEETPAGEW *page)
2422 {
2423     struct IssuerStatement *issuerStatement;
2424
2425     switch (msg)
2426     {
2427     case PSPCB_RELEASE:
2428         issuerStatement =
2429          (struct IssuerStatement *)GetWindowLongPtrW(hwnd, DWLP_USER);
2430         if (issuerStatement)
2431         {
2432             HeapFree(GetProcessHeap(), 0, issuerStatement->cps);
2433             HeapFree(GetProcessHeap(), 0, issuerStatement->userNotice);
2434             HeapFree(GetProcessHeap(), 0, issuerStatement);
2435         }
2436         break;
2437     }
2438     return 1;
2439 }
2440
2441 static void init_general_page(PCCRYPTUI_VIEWCERTIFICATE_STRUCTW pCertViewInfo,
2442  PROPSHEETPAGEW *page)
2443 {
2444     memset(page, 0, sizeof(PROPSHEETPAGEW));
2445     page->dwSize = sizeof(PROPSHEETPAGEW);
2446     page->dwFlags = PSP_USECALLBACK;
2447     page->pfnCallback = general_callback_proc;
2448     page->hInstance = hInstance;
2449     page->u.pszTemplate = MAKEINTRESOURCEW(IDD_GENERAL);
2450     page->pfnDlgProc = general_dlg_proc;
2451     page->lParam = (LPARAM)pCertViewInfo;
2452 }
2453
2454 typedef WCHAR * (*field_format_func)(PCCERT_CONTEXT cert);
2455
2456 static WCHAR *field_format_version(PCCERT_CONTEXT cert)
2457 {
2458     static const WCHAR fmt[] = { 'V','%','d',0 };
2459     WCHAR *buf = HeapAlloc(GetProcessHeap(), 0, 12 * sizeof(WCHAR));
2460
2461     if (buf)
2462         sprintfW(buf, fmt, cert->pCertInfo->dwVersion);
2463     return buf;
2464 }
2465
2466 static WCHAR *format_hex_string(void *pb, DWORD cb)
2467 {
2468     WCHAR *buf = HeapAlloc(GetProcessHeap(), 0, (cb * 3 + 1) * sizeof(WCHAR));
2469
2470     if (buf)
2471     {
2472         static const WCHAR fmt[] = { '%','0','2','x',' ',0 };
2473         DWORD i;
2474         WCHAR *ptr;
2475
2476         for (i = 0, ptr = buf; i < cb; i++, ptr += 3)
2477             sprintfW(ptr, fmt, ((BYTE *)pb)[i]);
2478     }
2479     return buf;
2480 }
2481
2482 static WCHAR *field_format_serial_number(PCCERT_CONTEXT cert)
2483 {
2484     return format_hex_string(cert->pCertInfo->SerialNumber.pbData,
2485      cert->pCertInfo->SerialNumber.cbData);
2486 }
2487
2488 static WCHAR *field_format_issuer(PCCERT_CONTEXT cert)
2489 {
2490     return get_cert_name_string(cert, CERT_NAME_SIMPLE_DISPLAY_TYPE,
2491      CERT_NAME_ISSUER_FLAG);
2492 }
2493
2494 static WCHAR *field_format_detailed_cert_name(PCERT_NAME_BLOB name)
2495 {
2496     WCHAR *str = NULL;
2497     DWORD len = CertNameToStrW(X509_ASN_ENCODING, name,
2498      CERT_X500_NAME_STR | CERT_NAME_STR_CRLF_FLAG, NULL, 0);
2499
2500     if (len)
2501     {
2502         str = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
2503         if (str)
2504             CertNameToStrW(X509_ASN_ENCODING, name,
2505              CERT_X500_NAME_STR | CERT_NAME_STR_CRLF_FLAG, str, len);
2506     }
2507     return str;
2508 }
2509
2510 static WCHAR *field_format_detailed_issuer(PCCERT_CONTEXT cert, void *param)
2511 {
2512     return field_format_detailed_cert_name(&cert->pCertInfo->Issuer);
2513 }
2514
2515 static WCHAR *field_format_subject(PCCERT_CONTEXT cert)
2516 {
2517     return get_cert_name_string(cert, CERT_NAME_SIMPLE_DISPLAY_TYPE, 0);
2518 }
2519
2520 static WCHAR *field_format_detailed_subject(PCCERT_CONTEXT cert, void *param)
2521 {
2522     return field_format_detailed_cert_name(&cert->pCertInfo->Subject);
2523 }
2524
2525 static WCHAR *format_long_date(const FILETIME *fileTime)
2526 {
2527     WCHAR dateFmt[80]; /* long enough for LOCALE_SLONGDATE */
2528     DWORD len;
2529     WCHAR *buf = NULL;
2530     SYSTEMTIME sysTime;
2531
2532     /* FIXME: format isn't quite right, want time too */
2533     GetLocaleInfoW(LOCALE_SYSTEM_DEFAULT, LOCALE_SLONGDATE, dateFmt,
2534      sizeof(dateFmt) / sizeof(dateFmt[0]));
2535     FileTimeToSystemTime(fileTime, &sysTime);
2536     len = GetDateFormatW(LOCALE_SYSTEM_DEFAULT, 0, &sysTime, dateFmt, NULL, 0);
2537     if (len)
2538     {
2539         buf = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
2540         if (buf)
2541             GetDateFormatW(LOCALE_SYSTEM_DEFAULT, 0, &sysTime, dateFmt, buf,
2542              len);
2543     }
2544     return buf;
2545 }
2546
2547 static WCHAR *field_format_from_date(PCCERT_CONTEXT cert)
2548 {
2549     return format_long_date(&cert->pCertInfo->NotBefore);
2550 }
2551
2552 static WCHAR *field_format_to_date(PCCERT_CONTEXT cert)
2553 {
2554     return format_long_date(&cert->pCertInfo->NotAfter);
2555 }
2556
2557 static WCHAR *field_format_public_key(PCCERT_CONTEXT cert)
2558 {
2559     PCCRYPT_OID_INFO oidInfo;
2560     WCHAR *buf = NULL;
2561
2562     oidInfo = CryptFindOIDInfo(CRYPT_OID_INFO_OID_KEY,
2563      cert->pCertInfo->SubjectPublicKeyInfo.Algorithm.pszObjId, 0);
2564     if (oidInfo)
2565     {
2566         WCHAR fmt[MAX_STRING_LEN];
2567
2568         if (LoadStringW(hInstance, IDS_FIELD_PUBLIC_KEY_FORMAT, fmt,
2569          sizeof(fmt) / sizeof(fmt[0])))
2570         {
2571             /* Allocate the output buffer.  Use the number of bytes in the
2572              * public key as a conservative (high) estimate for the number of
2573              * digits in its output.
2574              * The output is of the form (in English)
2575              * "<public key algorithm> (<public key bit length> bits)".
2576              * Ordinarily having two positional parameters in a string is not a
2577              * good idea, but as this isn't a sentence fragment, it shouldn't
2578              * be word-order dependent.
2579              */
2580             buf = HeapAlloc(GetProcessHeap(), 0,
2581              (strlenW(fmt) + strlenW(oidInfo->pwszName) +
2582              cert->pCertInfo->SubjectPublicKeyInfo.PublicKey.cbData * 8)
2583              * sizeof(WCHAR));
2584             if (buf)
2585                 sprintfW(buf, fmt, oidInfo->pwszName,
2586                  CertGetPublicKeyLength(X509_ASN_ENCODING,
2587                   &cert->pCertInfo->SubjectPublicKeyInfo));
2588         }
2589     }
2590     return buf;
2591 }
2592
2593 static WCHAR *field_format_detailed_public_key(PCCERT_CONTEXT cert, void *param)
2594 {
2595     return format_hex_string(
2596      cert->pCertInfo->SubjectPublicKeyInfo.PublicKey.pbData,
2597      cert->pCertInfo->SubjectPublicKeyInfo.PublicKey.cbData);
2598 }
2599
2600 struct field_value_data;
2601 struct detail_data
2602 {
2603     PCCRYPTUI_VIEWCERTIFICATE_STRUCTW pCertViewInfo;
2604     BOOL *pfPropertiesChanged;
2605     int cFields;
2606     struct field_value_data *fields;
2607 };
2608
2609 typedef void (*add_fields_func)(HWND hwnd, struct detail_data *data);
2610
2611 typedef WCHAR *(*create_detailed_value_func)(PCCERT_CONTEXT cert, void *param);
2612
2613 struct field_value_data
2614 {
2615     create_detailed_value_func create;
2616     LPWSTR detailed_value;
2617     void *param;
2618 };
2619
2620 static void add_field_value_data(struct detail_data *data,
2621  create_detailed_value_func create, void *param)
2622 {
2623     if (data->cFields)
2624         data->fields = HeapReAlloc(GetProcessHeap(), 0, data->fields,
2625          (data->cFields + 1) * sizeof(struct field_value_data));
2626     else
2627         data->fields = HeapAlloc(GetProcessHeap(), 0,
2628          sizeof(struct field_value_data));
2629     if (data->fields)
2630     {
2631         data->fields[data->cFields].create = create;
2632         data->fields[data->cFields].detailed_value = NULL;
2633         data->fields[data->cFields].param = param;
2634         data->cFields++;
2635     }
2636 }
2637
2638 static void add_field_and_value_to_list(HWND hwnd, struct detail_data *data,
2639  LPWSTR field, LPWSTR value, create_detailed_value_func create, void *param)
2640 {
2641     LVITEMW item;
2642     int iItem = SendMessageW(hwnd, LVM_GETITEMCOUNT, 0, 0);
2643
2644     item.mask = LVIF_TEXT | LVIF_PARAM;
2645     item.iItem = iItem;
2646     item.iSubItem = 0;
2647     item.pszText = field;
2648     item.lParam = (LPARAM)data;
2649     SendMessageW(hwnd, LVM_INSERTITEMW, 0, (LPARAM)&item);
2650     if (value)
2651     {
2652         item.pszText = value;
2653         item.iSubItem = 1;
2654         SendMessageW(hwnd, LVM_SETITEMTEXTW, iItem, (LPARAM)&item);
2655     }
2656     add_field_value_data(data, create, param);
2657 }
2658
2659 static void add_string_id_and_value_to_list(HWND hwnd, struct detail_data *data,
2660  int id, LPWSTR value, create_detailed_value_func create, void *param)
2661 {
2662     WCHAR buf[MAX_STRING_LEN];
2663
2664     LoadStringW(hInstance, id, buf, sizeof(buf) / sizeof(buf[0]));
2665     add_field_and_value_to_list(hwnd, data, buf, value, create, param);
2666 }
2667
2668 struct v1_field
2669 {
2670     int id;
2671     field_format_func format;
2672     create_detailed_value_func create_detailed_value;
2673 };
2674
2675 static void add_v1_field(HWND hwnd, struct detail_data *data,
2676  const struct v1_field *field)
2677 {
2678     WCHAR *val = field->format(data->pCertViewInfo->pCertContext);
2679
2680     if (val)
2681     {
2682         add_string_id_and_value_to_list(hwnd, data, field->id, val,
2683          field->create_detailed_value, NULL);
2684         HeapFree(GetProcessHeap(), 0, val);
2685     }
2686 }
2687
2688 static const struct v1_field v1_fields[] = {
2689  { IDS_FIELD_VERSION, field_format_version, NULL },
2690  { IDS_FIELD_SERIAL_NUMBER, field_format_serial_number, NULL },
2691  { IDS_FIELD_ISSUER, field_format_issuer, field_format_detailed_issuer },
2692  { IDS_FIELD_VALID_FROM, field_format_from_date, NULL },
2693  { IDS_FIELD_VALID_TO, field_format_to_date, NULL },
2694  { IDS_FIELD_SUBJECT, field_format_subject, field_format_detailed_subject },
2695  { IDS_FIELD_PUBLIC_KEY, field_format_public_key,
2696    field_format_detailed_public_key }
2697 };
2698
2699 static void add_v1_fields(HWND hwnd, struct detail_data *data)
2700 {
2701     int i;
2702     PCCERT_CONTEXT cert = data->pCertViewInfo->pCertContext;
2703
2704     /* The last item in v1_fields is the public key, which is not in the loop
2705      * because it's a special case.
2706      */
2707     for (i = 0; i < sizeof(v1_fields) / sizeof(v1_fields[0]) - 1; i++)
2708         add_v1_field(hwnd, data, &v1_fields[i]);
2709     if (cert->pCertInfo->SubjectPublicKeyInfo.PublicKey.cbData)
2710         add_v1_field(hwnd, data, &v1_fields[i]);
2711 }
2712
2713 static WCHAR *crypt_format_extension(PCERT_EXTENSION ext, DWORD formatStrType)
2714 {
2715     WCHAR *str = NULL;
2716     DWORD size;
2717
2718     if (CryptFormatObject(X509_ASN_ENCODING, 0, formatStrType, NULL,
2719      ext->pszObjId, ext->Value.pbData, ext->Value.cbData, NULL, &size))
2720     {
2721         str = HeapAlloc(GetProcessHeap(), 0, size);
2722         CryptFormatObject(X509_ASN_ENCODING, 0, formatStrType, NULL,
2723          ext->pszObjId, ext->Value.pbData, ext->Value.cbData, str, &size);
2724     }
2725     return str;
2726 }
2727
2728 static WCHAR *field_format_extension_hex_with_ascii(PCERT_EXTENSION ext)
2729 {
2730     WCHAR *str = NULL;
2731
2732     if (ext->Value.cbData)
2733     {
2734         /* The output is formatted as:
2735          * <hex bytes>  <ascii bytes>\n
2736          * where <hex bytes> is a string of up to 8 bytes, output as %02x,
2737          * and <ascii bytes> is the ASCII equivalent of each byte, or '.' if
2738          * the byte is not printable.
2739          * So, for example, the extension value consisting of the following
2740          * bytes:
2741          *   0x30,0x14,0x31,0x12,0x30,0x10,0x06,0x03,0x55,0x04,0x03,
2742          *   0x13,0x09,0x4a,0x75,0x61,0x6e,0x20,0x4c,0x61,0x6e,0x67
2743          * is output as:
2744          *   30 14 31 12 30 10 06 03  0.1.0...
2745          *   55 04 03 13 09 4a 75 61  U....Jua
2746          *   6e 20 4c 61 6e 67        n Lang
2747          * The allocation size therefore requires:
2748          * - 4 characters per character in an 8-byte line
2749          *   (2 for the hex format, one for the space, one for the ASCII value)
2750          * - 3 more characters per 8-byte line (two spaces and a newline)
2751          * - 1 character for the terminating nul
2752          * FIXME: should use a fixed-width font for this
2753          */
2754         DWORD lines = (ext->Value.cbData + 7) / 8;
2755
2756         str = HeapAlloc(GetProcessHeap(), 0,
2757          (lines * 8 * 4 + lines * 3 + 1) * sizeof(WCHAR));
2758         if (str)
2759         {
2760             static const WCHAR fmt[] = { '%','0','2','x',' ',0 };
2761             DWORD i, j;
2762             WCHAR *ptr;
2763
2764             for (i = 0, ptr = str; i < ext->Value.cbData; i += 8)
2765             {
2766                 /* Output as hex bytes first */
2767                 for (j = i; j < min(i + 8, ext->Value.cbData); j++, ptr += 3)
2768                     sprintfW(ptr, fmt, ext->Value.pbData[j]);
2769                 /* Pad the hex output with spaces for alignment */
2770                 if (j == ext->Value.cbData && j % 8)
2771                 {
2772                     static const WCHAR pad[] = { ' ',' ',' ' };
2773
2774                     for (; j % 8; j++, ptr += sizeof(pad) / sizeof(pad[0]))
2775                         memcpy(ptr, pad, sizeof(pad));
2776                 }
2777                 /* The last sprintfW included a space, so just insert one
2778                  * more space between the hex bytes and the ASCII output
2779                  */
2780                 *ptr++ = ' ';
2781                 /* Output as ASCII bytes */
2782                 for (j = i; j < min(i + 8, ext->Value.cbData); j++, ptr++)
2783                 {
2784                     if (isprintW(ext->Value.pbData[j]) &&
2785                      !isspaceW(ext->Value.pbData[j]))
2786                         *ptr = ext->Value.pbData[j];
2787                     else
2788                         *ptr = '.';
2789                 }
2790                 *ptr++ = '\n';
2791             }
2792             *ptr++ = '\0';
2793         }
2794     }
2795     return str;
2796 }
2797
2798 static WCHAR *field_format_detailed_extension(PCCERT_CONTEXT cert, void *param)
2799 {
2800     PCERT_EXTENSION ext = param;
2801     LPWSTR str = crypt_format_extension(ext,
2802      CRYPT_FORMAT_STR_MULTI_LINE | CRYPT_FORMAT_STR_NO_HEX);
2803
2804     if (!str)
2805         str = field_format_extension_hex_with_ascii(ext);
2806     return str;
2807 }
2808
2809 static void add_cert_extension_detail(HWND hwnd, struct detail_data *data,
2810  PCERT_EXTENSION ext)
2811 {
2812     PCCRYPT_OID_INFO oidInfo = CryptFindOIDInfo(CRYPT_OID_INFO_OID_KEY,
2813      ext->pszObjId, 0);
2814     LPWSTR val = crypt_format_extension(ext, 0);
2815
2816     if (oidInfo)
2817         add_field_and_value_to_list(hwnd, data, (LPWSTR)oidInfo->pwszName,
2818          val, field_format_detailed_extension, ext);
2819     else
2820     {
2821         DWORD len = strlen(ext->pszObjId);
2822         LPWSTR oidW = HeapAlloc(GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR));
2823
2824         if (oidW)
2825         {
2826             DWORD i;
2827
2828             for (i = 0; i <= len; i++)
2829                 oidW[i] = ext->pszObjId[i];
2830             add_field_and_value_to_list(hwnd, data, oidW, val,
2831              field_format_detailed_extension, ext);
2832             HeapFree(GetProcessHeap(), 0, oidW);
2833         }
2834     }
2835     HeapFree(GetProcessHeap(), 0, val);
2836 }
2837
2838 static void add_all_extensions(HWND hwnd, struct detail_data *data)
2839 {
2840     DWORD i;
2841     PCCERT_CONTEXT cert = data->pCertViewInfo->pCertContext;
2842
2843     for (i = 0; i < cert->pCertInfo->cExtension; i++)
2844         add_cert_extension_detail(hwnd, data, &cert->pCertInfo->rgExtension[i]);
2845 }
2846
2847 static void add_critical_extensions(HWND hwnd, struct detail_data *data)
2848 {
2849     DWORD i;
2850     PCCERT_CONTEXT cert = data->pCertViewInfo->pCertContext;
2851
2852     for (i = 0; i < cert->pCertInfo->cExtension; i++)
2853         if (cert->pCertInfo->rgExtension[i].fCritical)
2854             add_cert_extension_detail(hwnd, data,
2855              &cert->pCertInfo->rgExtension[i]);
2856 }
2857
2858 typedef WCHAR * (*prop_to_value_func)(void *pb, DWORD cb);
2859
2860 struct prop_id_to_string_id
2861 {
2862     DWORD prop;
2863     int id;
2864     BOOL prop_is_string;
2865     prop_to_value_func prop_to_value;
2866 };
2867
2868 static WCHAR *format_enhanced_key_usage_value(void *pb, DWORD cb)
2869 {
2870     CERT_EXTENSION ext;
2871
2872     ext.pszObjId = (LPSTR)X509_ENHANCED_KEY_USAGE;
2873     ext.fCritical = FALSE;
2874     ext.Value.pbData = pb;
2875     ext.Value.cbData = cb;
2876     return crypt_format_extension(&ext, 0);
2877 }
2878
2879 /* Logically the access state should also be checked, and IDC_EDITPROPERTIES
2880  * disabled for read-only certificates, but native doesn't appear to do that.
2881  */
2882 static const struct prop_id_to_string_id prop_id_map[] = {
2883  { CERT_HASH_PROP_ID, IDS_PROP_HASH, FALSE, format_hex_string },
2884  { CERT_FRIENDLY_NAME_PROP_ID, IDS_PROP_FRIENDLY_NAME, TRUE, NULL },
2885  { CERT_DESCRIPTION_PROP_ID, IDS_PROP_DESCRIPTION, TRUE, NULL },
2886  { CERT_ENHKEY_USAGE_PROP_ID, IDS_PROP_ENHKEY_USAGE, FALSE,
2887    format_enhanced_key_usage_value },
2888 };
2889
2890 static void add_properties(HWND hwnd, struct detail_data *data)
2891 {
2892     DWORD i;
2893     PCCERT_CONTEXT cert = data->pCertViewInfo->pCertContext;
2894
2895     for (i = 0; i < sizeof(prop_id_map) / sizeof(prop_id_map[0]); i++)
2896     {
2897         DWORD cb;
2898
2899         if (CertGetCertificateContextProperty(cert, prop_id_map[i].prop, NULL,
2900          &cb))
2901         {
2902             BYTE *pb;
2903             WCHAR *val = NULL;
2904
2905             /* FIXME: MS adds a separate value for the signature hash
2906              * algorithm.
2907              */
2908             pb = HeapAlloc(GetProcessHeap(), 0, cb);
2909             if (pb)
2910             {
2911                 if (CertGetCertificateContextProperty(cert,
2912                  prop_id_map[i].prop, pb, &cb))
2913                 {
2914                     if (prop_id_map[i].prop_is_string)
2915                     {
2916                         val = (LPWSTR)pb;
2917                         /* Don't double-free pb */
2918                         pb = NULL;
2919                     }
2920                     else
2921                         val = prop_id_map[i].prop_to_value(pb, cb);
2922                 }
2923                 HeapFree(GetProcessHeap(), 0, pb);
2924             }
2925             add_string_id_and_value_to_list(hwnd, data, prop_id_map[i].id, val,
2926              NULL, NULL);
2927         }
2928     }
2929 }
2930
2931 static void add_all_fields(HWND hwnd, struct detail_data *data)
2932 {
2933     add_v1_fields(hwnd, data);
2934     add_all_extensions(hwnd, data);
2935     add_properties(hwnd, data);
2936 }
2937
2938 struct selection_list_item
2939 {
2940     int id;
2941     add_fields_func add;
2942 };
2943
2944 const struct selection_list_item listItems[] = {
2945  { IDS_FIELDS_ALL, add_all_fields },
2946  { IDS_FIELDS_V1, add_v1_fields },
2947  { IDS_FIELDS_EXTENSIONS, add_all_extensions },
2948  { IDS_FIELDS_CRITICAL_EXTENSIONS, add_critical_extensions },
2949  { IDS_FIELDS_PROPERTIES, add_properties },
2950 };
2951
2952 static void create_show_list(HWND hwnd, struct detail_data *data)
2953 {
2954     HWND cb = GetDlgItem(hwnd, IDC_DETAIL_SELECT);
2955     WCHAR buf[MAX_STRING_LEN];
2956     int i;
2957
2958     for (i = 0; i < sizeof(listItems) / sizeof(listItems[0]); i++)
2959     {
2960         int index;
2961
2962         LoadStringW(hInstance, listItems[i].id, buf,
2963          sizeof(buf) / sizeof(buf[0]));
2964         index = SendMessageW(cb, CB_INSERTSTRING, -1, (LPARAM)buf);
2965         SendMessageW(cb, CB_SETITEMDATA, index, (LPARAM)data);
2966     }
2967     SendMessageW(cb, CB_SETCURSEL, 0, 0);
2968 }
2969
2970 static void create_listview_columns(HWND hwnd)
2971 {
2972     HWND lv = GetDlgItem(hwnd, IDC_DETAIL_LIST);
2973     RECT rc;
2974     WCHAR buf[MAX_STRING_LEN];
2975     LVCOLUMNW column;
2976
2977     SendMessageW(lv, LVM_SETEXTENDEDLISTVIEWSTYLE, 0, LVS_EX_FULLROWSELECT);
2978     GetWindowRect(lv, &rc);
2979     LoadStringW(hInstance, IDS_FIELD, buf, sizeof(buf) / sizeof(buf[0]));
2980     column.mask = LVCF_WIDTH | LVCF_TEXT;
2981     column.cx = (rc.right - rc.left) / 2 - 2;
2982     column.pszText = buf;
2983     SendMessageW(lv, LVM_INSERTCOLUMNW, 0, (LPARAM)&column);
2984     LoadStringW(hInstance, IDS_VALUE, buf, sizeof(buf) / sizeof(buf[0]));
2985     SendMessageW(lv, LVM_INSERTCOLUMNW, 1, (LPARAM)&column);
2986 }
2987
2988 static void set_fields_selection(HWND hwnd, struct detail_data *data, int sel)
2989 {
2990     HWND list = GetDlgItem(hwnd, IDC_DETAIL_LIST);
2991
2992     if (sel >= 0 && sel < sizeof(listItems) / sizeof(listItems[0]))
2993     {
2994         SendMessageW(list, LVM_DELETEALLITEMS, 0, 0);
2995         listItems[sel].add(list, data);
2996     }
2997 }
2998
2999 static void create_cert_details_list(HWND hwnd, struct detail_data *data)
3000 {
3001     create_show_list(hwnd, data);
3002     create_listview_columns(hwnd);
3003     set_fields_selection(hwnd, data, 0);
3004 }
3005
3006 static void add_purpose(HWND hwnd, LPCSTR oid)
3007 {
3008     HWND lv = GetDlgItem(hwnd, IDC_CERTIFICATE_USAGES);
3009     PCRYPT_OID_INFO info = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
3010      sizeof(CRYPT_OID_INFO));
3011
3012     if (info)
3013     {
3014         char *oidCopy = HeapAlloc(GetProcessHeap(), 0, strlen(oid) + 1);
3015
3016         if (oidCopy)
3017         {
3018             LVITEMA item;
3019
3020             strcpy(oidCopy, oid);
3021             info->cbSize = sizeof(CRYPT_OID_INFO);
3022             info->pszOID = oidCopy;
3023             item.mask = LVIF_TEXT | LVIF_STATE | LVIF_PARAM;
3024             item.state = INDEXTOSTATEIMAGEMASK(CheckBitmapIndexChecked);
3025             item.stateMask = LVIS_STATEIMAGEMASK;
3026             item.iItem = SendMessageW(lv, LVM_GETITEMCOUNT, 0, 0);
3027             item.iSubItem = 0;
3028             item.lParam = (LPARAM)info;
3029             item.pszText = oidCopy;
3030             SendMessageA(lv, LVM_INSERTITEMA, 0, (LPARAM)&item);
3031         }
3032         else
3033             HeapFree(GetProcessHeap(), 0, info);
3034     }
3035 }
3036
3037 static BOOL is_valid_oid(LPCSTR oid)
3038 {
3039     BOOL ret;
3040
3041     if (oid[0] != '0' && oid[0] != '1' && oid[0] != '2')
3042         ret = FALSE;
3043     else if (oid[1] != '.')
3044         ret = FALSE;
3045     else if (!oid[2])
3046         ret = FALSE;
3047     else
3048     {
3049         const char *ptr;
3050         BOOL expectNum = TRUE;
3051
3052         for (ptr = oid + 2, ret = TRUE; ret && *ptr; ptr++)
3053         {
3054             if (expectNum)
3055             {
3056                 if (!isdigit(*ptr))
3057                     ret = FALSE;
3058                 else if (*(ptr + 1) == '.')
3059                     expectNum = FALSE;
3060             }
3061             else
3062             {
3063                 if (*ptr != '.')
3064                     ret = FALSE;
3065                 else if (!(*(ptr + 1)))
3066                     ret = FALSE;
3067                 else
3068                     expectNum = TRUE;
3069             }
3070         }
3071     }
3072     return ret;
3073 }
3074
3075 static BOOL is_oid_in_list(HWND hwnd, LPCSTR oid)
3076 {
3077     return find_oid_in_list(GetDlgItem(hwnd, IDC_CERTIFICATE_USAGES), oid)
3078      != -1;
3079 }
3080
3081 #define MAX_PURPOSE 255
3082
3083 static LRESULT CALLBACK add_purpose_dlg_proc(HWND hwnd, UINT msg,
3084  WPARAM wp, LPARAM lp)
3085 {
3086     LRESULT ret = 0;
3087     char buf[MAX_PURPOSE + 1];
3088
3089     switch (msg)
3090     {
3091     case WM_INITDIALOG:
3092         SendMessageW(GetDlgItem(hwnd, IDC_NEW_PURPOSE), EM_SETLIMITTEXT,
3093          MAX_PURPOSE, 0);
3094         ShowScrollBar(GetDlgItem(hwnd, IDC_NEW_PURPOSE), SB_VERT, FALSE);
3095         SetWindowLongPtrW(hwnd, DWLP_USER, lp);
3096         break;
3097     case WM_COMMAND:
3098         switch (HIWORD(wp))
3099         {
3100         case EN_CHANGE:
3101             if (LOWORD(wp) == IDC_NEW_PURPOSE)
3102             {
3103                 /* Show/hide scroll bar on description depending on how much
3104                  * text it has.
3105                  */
3106                 HWND description = GetDlgItem(hwnd, IDC_NEW_PURPOSE);
3107                 int lines = SendMessageW(description, EM_GETLINECOUNT, 0, 0);
3108
3109                 ShowScrollBar(description, SB_VERT, lines > 1);
3110             }
3111             break;
3112         case BN_CLICKED:
3113             switch (LOWORD(wp))
3114             {
3115             case IDOK:
3116                 SendMessageA(GetDlgItem(hwnd, IDC_NEW_PURPOSE), WM_GETTEXT,
3117                  sizeof(buf) / sizeof(buf[0]), (LPARAM)buf);
3118                 if (!buf[0])
3119                 {
3120                     /* An empty purpose is the same as cancelling */
3121                     EndDialog(hwnd, IDCANCEL);
3122                     ret = TRUE;
3123                 }
3124                 else if (!is_valid_oid(buf))
3125                 {
3126                     WCHAR title[MAX_STRING_LEN], error[MAX_STRING_LEN];
3127
3128                     LoadStringW(hInstance, IDS_CERTIFICATE_PURPOSE_ERROR, error,
3129                      sizeof(error) / sizeof(error[0]));
3130                     LoadStringW(hInstance, IDS_CERTIFICATE_PROPERTIES, title,
3131                      sizeof(title) / sizeof(title[0]));
3132                     MessageBoxW(hwnd, error, title, MB_ICONERROR | MB_OK);
3133                 }
3134                 else if (is_oid_in_list(
3135                  (HWND)GetWindowLongPtrW(hwnd, DWLP_USER), buf))
3136                 {
3137                     WCHAR title[MAX_STRING_LEN], error[MAX_STRING_LEN];
3138
3139                     LoadStringW(hInstance, IDS_CERTIFICATE_PURPOSE_EXISTS,
3140                      error, sizeof(error) / sizeof(error[0]));
3141                     LoadStringW(hInstance, IDS_CERTIFICATE_PROPERTIES, title,
3142                      sizeof(title) / sizeof(title[0]));
3143                     MessageBoxW(hwnd, error, title, MB_ICONEXCLAMATION | MB_OK);
3144                 }
3145                 else
3146                 {
3147                     HWND parent = (HWND)GetWindowLongPtrW(hwnd, DWLP_USER);
3148
3149                     add_purpose(parent, buf);
3150                     EndDialog(hwnd, wp);
3151                     ret = TRUE;
3152                 }
3153                 break;
3154             case IDCANCEL:
3155                 EndDialog(hwnd, wp);
3156                 ret = TRUE;
3157                 break;
3158             }
3159             break;
3160         }
3161         break;
3162     }
3163     return ret;
3164 }
3165
3166 static WCHAR *get_cert_property_as_string(PCCERT_CONTEXT cert, DWORD prop)
3167 {
3168     WCHAR *name = NULL;
3169     DWORD cb;
3170
3171     if (CertGetCertificateContextProperty(cert, prop, NULL, &cb))
3172     {
3173         name = HeapAlloc(GetProcessHeap(), 0, cb);
3174         if (name)
3175         {
3176             if (!CertGetCertificateContextProperty(cert, prop, (LPBYTE)name,
3177              &cb))
3178             {
3179                 HeapFree(GetProcessHeap(), 0, name);
3180                 name = NULL;
3181             }
3182         }
3183     }
3184     return name;
3185 }
3186
3187 static void redraw_states(HWND list, BOOL enabled)
3188 {
3189     int items = SendMessageW(list, LVM_GETITEMCOUNT, 0, 0), i;
3190
3191     for (i = 0; i < items; i++)
3192     {
3193         BOOL change = FALSE;
3194         int state;
3195
3196         state = SendMessageW(list, LVM_GETITEMSTATE, i, LVIS_STATEIMAGEMASK);
3197         /* This reverses the INDEXTOSTATEIMAGEMASK shift.  There doesn't appear
3198          * to be a handy macro for it.
3199          */
3200         state >>= 12;
3201         if (enabled)
3202         {
3203             if (state == CheckBitmapIndexDisabledChecked)
3204             {
3205                 state = CheckBitmapIndexChecked;
3206                 change = TRUE;
3207             }
3208             if (state == CheckBitmapIndexDisabledUnchecked)
3209             {
3210                 state = CheckBitmapIndexUnchecked;
3211                 change = TRUE;
3212             }
3213         }
3214         else
3215         {
3216             if (state == CheckBitmapIndexChecked)
3217             {
3218                 state = CheckBitmapIndexDisabledChecked;
3219                 change = TRUE;
3220             }
3221             if (state == CheckBitmapIndexUnchecked)
3222             {
3223                 state = CheckBitmapIndexDisabledUnchecked;
3224                 change = TRUE;
3225             }
3226         }
3227         if (change)
3228         {
3229             LVITEMW item;
3230
3231             item.state = INDEXTOSTATEIMAGEMASK(state);
3232             item.stateMask = LVIS_STATEIMAGEMASK;
3233             SendMessageW(list, LVM_SETITEMSTATE, i, (LPARAM)&item);
3234         }
3235     }
3236 }
3237
3238 typedef enum {
3239     PurposeEnableAll = 0,
3240     PurposeDisableAll,
3241     PurposeEnableSelected
3242 } PurposeSelection;
3243
3244 static void select_purposes(HWND hwnd, PurposeSelection selection)
3245 {
3246     HWND lv = GetDlgItem(hwnd, IDC_CERTIFICATE_USAGES);
3247
3248     switch (selection)
3249     {
3250     case PurposeEnableAll:
3251     case PurposeDisableAll:
3252         EnableWindow(lv, FALSE);
3253         redraw_states(lv, FALSE);
3254         EnableWindow(GetDlgItem(hwnd, IDC_ADD_PURPOSE), FALSE);
3255         break;
3256     case PurposeEnableSelected:
3257         EnableWindow(lv, TRUE);
3258         redraw_states(lv, TRUE);
3259         EnableWindow(GetDlgItem(hwnd, IDC_ADD_PURPOSE), TRUE);
3260     }
3261 }
3262
3263 struct edit_cert_data
3264 {
3265     PCCERT_CONTEXT cert;
3266     BOOL *pfPropertiesChanged;
3267     HIMAGELIST imageList;
3268 };
3269
3270 static void show_cert_usages(HWND hwnd, struct edit_cert_data *data)
3271 {
3272     PCCERT_CONTEXT cert = data->cert;
3273     HWND lv = GetDlgItem(hwnd, IDC_CERTIFICATE_USAGES);
3274     PCERT_ENHKEY_USAGE usage;
3275     DWORD size;
3276     RECT rc;
3277     LVCOLUMNW column;
3278     PurposeSelection purposeSelection;
3279
3280     GetWindowRect(lv, &rc);
3281     column.mask = LVCF_WIDTH;
3282     column.cx = rc.right - rc.left;
3283     SendMessageW(lv, LVM_INSERTCOLUMNW, 0, (LPARAM)&column);
3284     SendMessageW(lv, LVM_SETIMAGELIST, LVSIL_STATE, (LPARAM)data->imageList);
3285
3286     /* Get enhanced key usage.  Have to check for a property and an extension
3287      * separately, because CertGetEnhancedKeyUsage will succeed and return an
3288      * empty usage if neither is set.  Unfortunately an empty usage implies
3289      * no usage is allowed, so we have to distinguish between the two cases.
3290      */
3291     if (CertGetEnhancedKeyUsage(cert, CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG,
3292      NULL, &size))
3293     {
3294         usage = HeapAlloc(GetProcessHeap(), 0, size);
3295         if (!CertGetEnhancedKeyUsage(cert,
3296          CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG, usage, &size))
3297         {
3298             HeapFree(GetProcessHeap(), 0, usage);
3299             usage = NULL;
3300         }
3301         else if (usage->cUsageIdentifier)
3302             purposeSelection = PurposeEnableSelected;
3303         else
3304             purposeSelection = PurposeDisableAll;
3305     }
3306     else if (CertGetEnhancedKeyUsage(cert, CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG,
3307      NULL, &size))
3308     {
3309         usage = HeapAlloc(GetProcessHeap(), 0, size);
3310         if (!CertGetEnhancedKeyUsage(cert,
3311          CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG, usage, &size))
3312         {
3313             HeapFree(GetProcessHeap(), 0, usage);
3314             usage = NULL;
3315         }
3316         else if (usage->cUsageIdentifier)
3317             purposeSelection = PurposeEnableAll;
3318         else
3319             purposeSelection = PurposeDisableAll;
3320     }
3321     else
3322     {
3323         purposeSelection = PurposeEnableAll;
3324         usage = NULL;
3325     }
3326     if (usage)
3327     {
3328         DWORD i;
3329
3330         for (i = 0; i < usage->cUsageIdentifier; i++)
3331         {
3332             PCCRYPT_OID_INFO info = CryptFindOIDInfo(CRYPT_OID_INFO_OID_KEY,
3333              usage->rgpszUsageIdentifier[i], CRYPT_ENHKEY_USAGE_OID_GROUP_ID);
3334
3335             if (info)
3336                 add_known_usage(lv, info, CheckBitmapIndexDisabledChecked);
3337             else
3338                 add_purpose(hwnd, usage->rgpszUsageIdentifier[i]);
3339         }
3340         HeapFree(GetProcessHeap(), 0, usage);
3341     }
3342     else
3343         add_known_usages_to_list(lv, CheckBitmapIndexDisabledChecked);
3344     select_purposes(hwnd, purposeSelection);
3345     SendMessageW(GetDlgItem(hwnd, IDC_ENABLE_ALL_PURPOSES + purposeSelection),
3346      BM_CLICK, 0, 0);
3347 }
3348
3349 static void set_general_cert_properties(HWND hwnd, struct edit_cert_data *data)
3350 {
3351     PCCERT_CONTEXT cert = data->cert;
3352     WCHAR *str;
3353
3354     if ((str = get_cert_property_as_string(cert, CERT_FRIENDLY_NAME_PROP_ID)))
3355     {
3356         SendMessageW(GetDlgItem(hwnd, IDC_FRIENDLY_NAME), WM_SETTEXT, 0,
3357          (LPARAM)str);
3358         HeapFree(GetProcessHeap(), 0, str);
3359     }
3360     if ((str = get_cert_property_as_string(cert, CERT_DESCRIPTION_PROP_ID)))
3361     {
3362         SendMessageW(GetDlgItem(hwnd, IDC_DESCRIPTION), WM_SETTEXT, 0,
3363          (LPARAM)str);
3364         HeapFree(GetProcessHeap(), 0, str);
3365     }
3366     show_cert_usages(hwnd, data);
3367 }
3368
3369 static void set_cert_string_property(PCCERT_CONTEXT cert, DWORD prop,
3370  LPWSTR str)
3371 {
3372     if (str && strlenW(str))
3373     {
3374         CRYPT_DATA_BLOB blob;
3375
3376         blob.pbData = (BYTE *)str;
3377         blob.cbData = (strlenW(str) + 1) * sizeof(WCHAR);
3378         CertSetCertificateContextProperty(cert, prop, 0, &blob);
3379     }
3380     else
3381         CertSetCertificateContextProperty(cert, prop, 0, NULL);
3382 }
3383
3384 #define WM_REFRESH_VIEW WM_USER + 0
3385
3386 static BOOL CALLBACK refresh_propsheet_pages(HWND hwnd, LPARAM lParam)
3387 {
3388     if ((GetClassLongW(hwnd, GCW_ATOM) == WC_DIALOG))
3389         SendMessageW(hwnd, WM_REFRESH_VIEW, 0, 0);
3390     return TRUE;
3391 }
3392
3393 #define MAX_FRIENDLY_NAME 40
3394 #define MAX_DESCRIPTION 255
3395
3396 static void apply_general_changes(HWND hwnd)
3397 {
3398     WCHAR buf[MAX_DESCRIPTION + 1];
3399     struct edit_cert_data *data =
3400      (struct edit_cert_data *)GetWindowLongPtrW(hwnd, DWLP_USER);
3401
3402     SendMessageW(GetDlgItem(hwnd, IDC_FRIENDLY_NAME), WM_GETTEXT,
3403      sizeof(buf) / sizeof(buf[0]), (LPARAM)buf);
3404     set_cert_string_property(data->cert, CERT_FRIENDLY_NAME_PROP_ID, buf);
3405     SendMessageW(GetDlgItem(hwnd, IDC_DESCRIPTION), WM_GETTEXT,
3406      sizeof(buf) / sizeof(buf[0]), (LPARAM)buf);
3407     set_cert_string_property(data->cert, CERT_DESCRIPTION_PROP_ID, buf);
3408     if (IsDlgButtonChecked(hwnd, IDC_ENABLE_ALL_PURPOSES))
3409     {
3410         /* Setting a NULL usage removes the enhanced key usage property. */
3411         CertSetEnhancedKeyUsage(data->cert, NULL);
3412     }
3413     else if (IsDlgButtonChecked(hwnd, IDC_DISABLE_ALL_PURPOSES))
3414     {
3415         CERT_ENHKEY_USAGE usage = { 0, NULL };
3416
3417         CertSetEnhancedKeyUsage(data->cert, &usage);
3418     }
3419     else if (IsDlgButtonChecked(hwnd, IDC_ENABLE_SELECTED_PURPOSES))
3420     {
3421         HWND lv = GetDlgItem(hwnd, IDC_CERTIFICATE_USAGES);
3422         CERT_ENHKEY_USAGE usage = { 0, NULL };
3423         int purposes = SendMessageW(lv, LVM_GETITEMCOUNT, 0, 0), i;
3424         LVITEMW item;
3425
3426         item.mask = LVIF_STATE | LVIF_PARAM;
3427         item.iSubItem = 0;
3428         item.stateMask = LVIS_STATEIMAGEMASK;
3429         for (i = 0; i < purposes; i++)
3430         {
3431             item.iItem = i;
3432             if (SendMessageW(lv, LVM_GETITEMW, 0, (LPARAM)&item))
3433             {
3434                 int state = item.state >> 12;
3435
3436                 if (state == CheckBitmapIndexChecked)
3437                 {
3438                     CRYPT_OID_INFO *info = (CRYPT_OID_INFO *)item.lParam;
3439
3440                     if (usage.cUsageIdentifier)
3441                         usage.rgpszUsageIdentifier =
3442                          HeapReAlloc(GetProcessHeap(), 0,
3443                          usage.rgpszUsageIdentifier,
3444                          (usage.cUsageIdentifier + 1) * sizeof(LPSTR));
3445                     else
3446                         usage.rgpszUsageIdentifier =
3447                          HeapAlloc(GetProcessHeap(), 0, sizeof(LPSTR));
3448                     if (usage.rgpszUsageIdentifier)
3449                         usage.rgpszUsageIdentifier[usage.cUsageIdentifier++] =
3450                          (LPSTR)info->pszOID;
3451                 }
3452             }
3453         }
3454         CertSetEnhancedKeyUsage(data->cert, &usage);
3455         HeapFree(GetProcessHeap(), 0, usage.rgpszUsageIdentifier);
3456     }
3457     EnumChildWindows(GetParent(GetParent(hwnd)), refresh_propsheet_pages, 0);
3458     if (data->pfPropertiesChanged)
3459         *data->pfPropertiesChanged = TRUE;
3460 }
3461
3462 static LRESULT CALLBACK cert_properties_general_dlg_proc(HWND hwnd, UINT msg,
3463  WPARAM wp, LPARAM lp)
3464 {
3465     PROPSHEETPAGEW *page;
3466
3467     TRACE("(%p, %08x, %08lx, %08lx)\n", hwnd, msg, wp, lp);
3468
3469     switch (msg)
3470     {
3471     case WM_INITDIALOG:
3472     {
3473         HWND description = GetDlgItem(hwnd, IDC_DESCRIPTION);
3474         struct detail_data *detailData;
3475         struct edit_cert_data *editData;
3476
3477         page = (PROPSHEETPAGEW *)lp;
3478         detailData = (struct detail_data *)page->lParam;
3479         SendMessageW(GetDlgItem(hwnd, IDC_FRIENDLY_NAME), EM_SETLIMITTEXT,
3480          MAX_FRIENDLY_NAME, 0);
3481         SendMessageW(description, EM_SETLIMITTEXT, MAX_DESCRIPTION, 0);
3482         ShowScrollBar(description, SB_VERT, FALSE);
3483         editData = HeapAlloc(GetProcessHeap(), 0,
3484          sizeof(struct edit_cert_data));
3485         if (editData)
3486         {
3487             editData->imageList = ImageList_Create(16, 16,
3488              ILC_COLOR4 | ILC_MASK, 4, 0);
3489             if (editData->imageList)
3490             {
3491                 HBITMAP bmp;
3492                 COLORREF backColor = RGB(255, 0, 255);
3493
3494                 bmp = LoadBitmapW(hInstance, MAKEINTRESOURCEW(IDB_CHECKS));
3495                 ImageList_AddMasked(editData->imageList, bmp, backColor);
3496                 DeleteObject(bmp);
3497                 ImageList_SetBkColor(editData->imageList, CLR_NONE);
3498             }
3499             editData->cert = detailData->pCertViewInfo->pCertContext;
3500             editData->pfPropertiesChanged = detailData->pfPropertiesChanged;
3501             SetWindowLongPtrW(hwnd, DWLP_USER, (LPARAM)editData);
3502             set_general_cert_properties(hwnd, editData);
3503         }
3504         break;
3505     }
3506     case WM_NOTIFY:
3507     {
3508         NMHDR *hdr = (NMHDR *)lp;
3509         NMITEMACTIVATE *nm;
3510
3511         switch (hdr->code)
3512         {
3513         case NM_CLICK:
3514             nm = (NMITEMACTIVATE *)lp;
3515             toggle_usage(hwnd, nm->iItem);
3516             SendMessageW(GetParent(hwnd), PSM_CHANGED, (WPARAM)hwnd, 0);
3517             break;
3518         case PSN_APPLY:
3519             apply_general_changes(hwnd);
3520             break;
3521         }
3522         break;
3523     }
3524     case WM_COMMAND:
3525         switch (HIWORD(wp))
3526         {
3527         case EN_CHANGE:
3528             SendMessageW(GetParent(hwnd), PSM_CHANGED, (WPARAM)hwnd, 0);
3529             if (LOWORD(wp) == IDC_DESCRIPTION)
3530             {
3531                 /* Show/hide scroll bar on description depending on how much
3532                  * text it has.
3533                  */
3534                 HWND description = GetDlgItem(hwnd, IDC_DESCRIPTION);
3535                 int lines = SendMessageW(description, EM_GETLINECOUNT, 0, 0);
3536
3537                 ShowScrollBar(description, SB_VERT, lines > 1);
3538             }
3539             break;
3540         case BN_CLICKED:
3541             switch (LOWORD(wp))
3542             {
3543             case IDC_ADD_PURPOSE:
3544                 if (DialogBoxParamW(hInstance,
3545                  MAKEINTRESOURCEW(IDD_ADD_CERT_PURPOSE), hwnd,
3546                  add_purpose_dlg_proc, (LPARAM)hwnd) == IDOK)
3547                     SendMessageW(GetParent(hwnd), PSM_CHANGED, (WPARAM)hwnd, 0);
3548                 break;
3549             case IDC_ENABLE_ALL_PURPOSES:
3550             case IDC_DISABLE_ALL_PURPOSES:
3551             case IDC_ENABLE_SELECTED_PURPOSES:
3552                 SendMessageW(GetParent(hwnd), PSM_CHANGED, (WPARAM)hwnd, 0);
3553                 select_purposes(hwnd, LOWORD(wp) - IDC_ENABLE_ALL_PURPOSES);
3554                 break;
3555             }
3556             break;
3557         }
3558         break;
3559     }
3560     return 0;
3561 }
3562
3563 static UINT CALLBACK cert_properties_general_callback(HWND hwnd, UINT msg,
3564  PROPSHEETPAGEW *page)
3565 {
3566     HWND lv;
3567     int cItem, i;
3568     struct edit_cert_data *data;
3569
3570     switch (msg)
3571     {
3572     case PSPCB_RELEASE:
3573         lv = GetDlgItem(hwnd, IDC_CERTIFICATE_USAGES);
3574         cItem = SendMessageW(lv, LVM_GETITEMCOUNT, 0, 0);
3575         for (i = 0; i < cItem; i++)
3576         {
3577             LVITEMW item;
3578
3579             item.mask = LVIF_PARAM;
3580             item.iItem = i;
3581             item.iSubItem = 0;
3582             if (SendMessageW(lv, LVM_GETITEMW, 0, (LPARAM)&item) && item.lParam)
3583             {
3584                 PCRYPT_OID_INFO info = (PCRYPT_OID_INFO)item.lParam;
3585
3586                 if (info->cbSize == sizeof(CRYPT_OID_INFO) && !info->dwGroupId)
3587                 {
3588                     HeapFree(GetProcessHeap(), 0, (LPSTR)info->pszOID);
3589                     HeapFree(GetProcessHeap(), 0, info);
3590                 }
3591             }
3592         }
3593         data = (struct edit_cert_data *)GetWindowLongPtrW(hwnd, DWLP_USER);
3594         if (data)
3595         {
3596             ImageList_Destroy(data->imageList);
3597             HeapFree(GetProcessHeap(), 0, data);
3598         }
3599         break;
3600     }
3601     return 1;
3602 }
3603
3604 static void show_edit_cert_properties_dialog(HWND parent,
3605  struct detail_data *data)
3606 {
3607     PROPSHEETHEADERW hdr;
3608     PROPSHEETPAGEW page; /* FIXME: need to add a cross-certificate page */
3609
3610     TRACE("(%p)\n", data);
3611
3612     memset(&page, 0, sizeof(PROPSHEETPAGEW));
3613     page.dwSize = sizeof(page);
3614     page.dwFlags = PSP_USECALLBACK;
3615     page.pfnCallback = cert_properties_general_callback;
3616     page.hInstance = hInstance;
3617     page.u.pszTemplate = MAKEINTRESOURCEW(IDD_CERT_PROPERTIES_GENERAL);
3618     page.pfnDlgProc = cert_properties_general_dlg_proc;
3619     page.lParam = (LPARAM)data;
3620
3621     memset(&hdr, 0, sizeof(hdr));
3622     hdr.dwSize = sizeof(hdr);
3623     hdr.hwndParent = parent;
3624     hdr.dwFlags = PSH_PROPSHEETPAGE;
3625     hdr.hInstance = hInstance;
3626     hdr.pszCaption = MAKEINTRESOURCEW(IDS_CERTIFICATE_PROPERTIES);
3627     hdr.u3.ppsp = &page;
3628     hdr.nPages = 1;
3629     PropertySheetW(&hdr);
3630 }
3631
3632 static void free_detail_fields(struct detail_data *data)
3633 {
3634     DWORD i;
3635
3636     for (i = 0; i < data->cFields; i++)
3637         HeapFree(GetProcessHeap(), 0, data->fields[i].detailed_value);
3638     HeapFree(GetProcessHeap(), 0, data->fields);
3639     data->fields = NULL;
3640     data->cFields = 0;
3641 }
3642
3643 static void refresh_details_view(HWND hwnd)
3644 {
3645     HWND cb = GetDlgItem(hwnd, IDC_DETAIL_SELECT);
3646     int curSel;
3647     struct detail_data *data;
3648
3649     curSel = SendMessageW(cb, CB_GETCURSEL, 0, 0);
3650     /* Actually, any index will do, since they all store the same data value */
3651     data = (struct detail_data *)SendMessageW(cb, CB_GETITEMDATA, curSel, 0);
3652     free_detail_fields(data);
3653     set_fields_selection(hwnd, data, curSel);
3654 }
3655
3656 static LRESULT CALLBACK detail_dlg_proc(HWND hwnd, UINT msg, WPARAM wp,
3657  LPARAM lp)
3658 {
3659     PROPSHEETPAGEW *page;
3660     struct detail_data *data;
3661
3662     TRACE("(%p, %08x, %08lx, %08lx)\n", hwnd, msg, wp, lp);
3663
3664     switch (msg)
3665     {
3666     case WM_INITDIALOG:
3667         page = (PROPSHEETPAGEW *)lp;
3668         data = (struct detail_data *)page->lParam;
3669         create_cert_details_list(hwnd, data);
3670         if (!(data->pCertViewInfo->dwFlags & CRYPTUI_ENABLE_EDITPROPERTIES))
3671             EnableWindow(GetDlgItem(hwnd, IDC_EDITPROPERTIES), FALSE);
3672         if (data->pCertViewInfo->dwFlags & CRYPTUI_DISABLE_EXPORT)
3673             EnableWindow(GetDlgItem(hwnd, IDC_EXPORT), FALSE);
3674         break;
3675     case WM_NOTIFY:
3676     {
3677         NMITEMACTIVATE *nm;
3678         HWND list = GetDlgItem(hwnd, IDC_DETAIL_LIST);
3679
3680         nm = (NMITEMACTIVATE*)lp;
3681         if (nm->hdr.hwndFrom == list && nm->uNewState & LVN_ITEMACTIVATE
3682          && nm->hdr.code == LVN_ITEMCHANGED)
3683         {
3684             data = (struct detail_data *)nm->lParam;
3685             if (nm->iItem >= 0 && data && nm->iItem < data->cFields)
3686             {
3687                 WCHAR buf[MAX_STRING_LEN], *val = NULL;
3688                 HWND valueCtl = GetDlgItem(hwnd, IDC_DETAIL_VALUE);
3689
3690                 if (data->fields[nm->iItem].create)
3691                     val = data->fields[nm->iItem].create(
3692                      data->pCertViewInfo->pCertContext,
3693                      data->fields[nm->iItem].param);
3694                 else
3695                 {
3696                     LVITEMW item;
3697                     int res;
3698
3699                     item.cchTextMax = sizeof(buf) / sizeof(buf[0]);
3700                     item.mask = LVIF_TEXT;
3701                     item.pszText = buf;
3702                     item.iItem = nm->iItem;
3703                     item.iSubItem = 1;
3704                     res = SendMessageW(list, LVM_GETITEMW, 0, (LPARAM)&item);
3705                     if (res)
3706                         val = buf;
3707                 }
3708                 /* Select all the text in the control, the next update will
3709                  * replace it
3710                  */
3711                 SendMessageW(valueCtl, EM_SETSEL, 0, -1);
3712                 add_unformatted_text_to_control(valueCtl, val,
3713                  val ? strlenW(val) : 0);
3714                 if (val != buf)
3715                     HeapFree(GetProcessHeap(), 0, val);
3716             }
3717         }
3718         break;
3719     }
3720     case WM_COMMAND:
3721         switch (wp)
3722         {
3723         case IDC_EXPORT:
3724             FIXME("call CryptUIWizExport\n");
3725             break;
3726         case IDC_EDITPROPERTIES:
3727         {
3728             HWND cb = GetDlgItem(hwnd, IDC_DETAIL_SELECT);
3729             int curSel;
3730
3731             curSel = SendMessageW(cb, CB_GETCURSEL, 0, 0);
3732             /* Actually, any index will do, since they all store the same
3733              * data value
3734              */
3735             data = (struct detail_data *)SendMessageW(cb, CB_GETITEMDATA,
3736              curSel, 0);
3737             show_edit_cert_properties_dialog(GetParent(hwnd), data);
3738             break;
3739         }
3740         case ((CBN_SELCHANGE << 16) | IDC_DETAIL_SELECT):
3741             refresh_details_view(hwnd);
3742             break;
3743         }
3744         break;
3745     case WM_REFRESH_VIEW:
3746         refresh_details_view(hwnd);
3747         break;
3748     }
3749     return 0;
3750 }
3751
3752 static UINT CALLBACK detail_callback(HWND hwnd, UINT msg,
3753  PROPSHEETPAGEW *page)
3754 {
3755     struct detail_data *data;
3756
3757     switch (msg)
3758     {
3759     case PSPCB_RELEASE:
3760         data = (struct detail_data *)page->lParam;
3761         free_detail_fields(data);
3762         HeapFree(GetProcessHeap(), 0, data);
3763         break;
3764     }
3765     return 0;
3766 }
3767
3768 static BOOL init_detail_page(PCCRYPTUI_VIEWCERTIFICATE_STRUCTW pCertViewInfo,
3769  BOOL *pfPropertiesChanged, PROPSHEETPAGEW *page)
3770 {
3771     BOOL ret;
3772     struct detail_data *data = HeapAlloc(GetProcessHeap(), 0,
3773      sizeof(struct detail_data));
3774
3775     if (data)
3776     {
3777         data->pCertViewInfo = pCertViewInfo;
3778         data->pfPropertiesChanged = pfPropertiesChanged;
3779         data->cFields = 0;
3780         data->fields = NULL;
3781         memset(page, 0, sizeof(PROPSHEETPAGEW));
3782         page->dwSize = sizeof(PROPSHEETPAGEW);
3783         page->dwFlags = PSP_USECALLBACK;
3784         page->pfnCallback = detail_callback;
3785         page->hInstance = hInstance;
3786         page->u.pszTemplate = MAKEINTRESOURCEW(IDD_DETAIL);
3787         page->pfnDlgProc = detail_dlg_proc;
3788         page->lParam = (LPARAM)data;
3789         ret = TRUE;
3790     }
3791     else
3792         ret = FALSE;
3793     return ret;
3794 }
3795
3796 struct hierarchy_data
3797 {
3798     PCCRYPTUI_VIEWCERTIFICATE_STRUCTW pCertViewInfo;
3799     HIMAGELIST imageList;
3800     DWORD selectedCert;
3801 };
3802
3803 static LPARAM index_to_lparam(struct hierarchy_data *data, DWORD index)
3804 {
3805     CRYPT_PROVIDER_SGNR *provSigner = WTHelperGetProvSignerFromChain(
3806      (CRYPT_PROVIDER_DATA *)data->pCertViewInfo->u.pCryptProviderData,
3807      data->pCertViewInfo->idxSigner, data->pCertViewInfo->fCounterSigner,
3808      data->pCertViewInfo->idxCounterSigner);
3809
3810     /* Takes advantage of the fact that a pointer is 32-bit aligned, and
3811      * therefore always even.
3812      */
3813     if (index == provSigner->csCertChain - 1)
3814         return (LPARAM)data;
3815     return index << 1 | 1;
3816 }
3817
3818 static inline DWORD lparam_to_index(struct hierarchy_data *data, LPARAM lp)
3819 {
3820     CRYPT_PROVIDER_SGNR *provSigner = WTHelperGetProvSignerFromChain(
3821      (CRYPT_PROVIDER_DATA *)data->pCertViewInfo->u.pCryptProviderData,
3822      data->pCertViewInfo->idxSigner, data->pCertViewInfo->fCounterSigner,
3823      data->pCertViewInfo->idxCounterSigner);
3824
3825     if (!(lp & 1))
3826         return provSigner->csCertChain - 1;
3827     return lp >> 1;
3828 }
3829
3830 static struct hierarchy_data *get_hierarchy_data_from_tree_item(HWND tree,
3831  HTREEITEM hItem)
3832 {
3833     struct hierarchy_data *data = NULL;
3834     HTREEITEM root = NULL;
3835
3836     do {
3837         HTREEITEM parent = (HTREEITEM)SendMessageW(tree, TVM_GETNEXTITEM,
3838          TVGN_PARENT, (LPARAM)hItem);
3839
3840         if (!parent)
3841             root = hItem;
3842         hItem = parent;
3843     } while (hItem);
3844     if (root)
3845     {
3846         TVITEMW item;
3847
3848         item.mask = TVIF_PARAM;
3849         item.hItem = root;
3850         SendMessageW(tree, TVM_GETITEMW, 0, (LPARAM)&item);
3851         data = (struct hierarchy_data *)item.lParam;
3852     }
3853     return data;
3854 }
3855
3856 static WCHAR *get_cert_display_name(PCCERT_CONTEXT cert)
3857 {
3858     WCHAR *name = get_cert_property_as_string(cert, CERT_FRIENDLY_NAME_PROP_ID);
3859
3860     if (!name)
3861         name = get_cert_name_string(cert, CERT_NAME_SIMPLE_DISPLAY_TYPE, 0);
3862     return name;
3863 }
3864
3865 static void show_cert_chain(HWND hwnd, struct hierarchy_data *data)
3866 {
3867     HWND tree = GetDlgItem(hwnd, IDC_CERTPATH);
3868     CRYPT_PROVIDER_SGNR *provSigner = WTHelperGetProvSignerFromChain(
3869      (CRYPT_PROVIDER_DATA *)data->pCertViewInfo->u.pCryptProviderData,
3870      data->pCertViewInfo->idxSigner, data->pCertViewInfo->fCounterSigner,
3871      data->pCertViewInfo->idxCounterSigner);
3872     DWORD i;
3873     HTREEITEM parent = NULL;
3874
3875     SendMessageW(tree, TVM_SETIMAGELIST, TVSIL_NORMAL, (LPARAM)data->imageList);
3876     for (i = provSigner->csCertChain; i; i--)
3877     {
3878         LPWSTR name;
3879
3880         name = get_cert_display_name(provSigner->pasCertChain[i - 1].pCert);
3881         if (name)
3882         {
3883             TVINSERTSTRUCTW tvis;
3884
3885             tvis.hParent = parent;
3886             tvis.hInsertAfter = TVI_LAST;
3887             tvis.u.item.mask = TVIF_TEXT | TVIF_STATE | TVIF_IMAGE |
3888              TVIF_SELECTEDIMAGE | TVIF_PARAM;
3889             tvis.u.item.pszText = name;
3890             tvis.u.item.state = TVIS_EXPANDED;
3891             tvis.u.item.stateMask = TVIS_EXPANDED;
3892             if (i == 1 &&
3893              (provSigner->pChainContext->TrustStatus.dwErrorStatus &
3894              CERT_TRUST_IS_PARTIAL_CHAIN))
3895             {
3896                 /* The root of the chain has a special case:  if the chain is
3897                  * a partial chain, the icon is a warning icon rather than an
3898                  * error icon.
3899                  */
3900                 tvis.u.item.iImage = 2;
3901             }
3902             else if (provSigner->pasCertChain[i - 1].pChainElement->TrustStatus.
3903              dwErrorStatus == 0)
3904                 tvis.u.item.iImage = 0;
3905             else
3906                 tvis.u.item.iImage = 1;
3907             tvis.u.item.iSelectedImage = tvis.u.item.iImage;
3908             tvis.u.item.lParam = index_to_lparam(data, i - 1);
3909             parent = (HTREEITEM)SendMessageW(tree, TVM_INSERTITEMW, 0,
3910              (LPARAM)&tvis);
3911             HeapFree(GetProcessHeap(), 0, name);
3912         }
3913     }
3914 }
3915
3916 static void set_certificate_status(HWND hwnd, CRYPT_PROVIDER_CERT *cert)
3917 {
3918     /* Select all the text in the control, the next update will replace it */
3919     SendMessageW(hwnd, EM_SETSEL, 0, -1);
3920     /* Set the highest priority error messages first. */
3921     if (!(cert->dwConfidence & CERT_CONFIDENCE_SIG))
3922         add_string_resource_to_control(hwnd, IDS_CERTIFICATE_BAD_SIGNATURE);
3923     else if (!(cert->dwConfidence & CERT_CONFIDENCE_TIME))
3924         add_string_resource_to_control(hwnd, IDS_CERTIFICATE_BAD_TIME);
3925     else if (!(cert->dwConfidence & CERT_CONFIDENCE_TIMENEST))
3926         add_string_resource_to_control(hwnd, IDS_CERTIFICATE_BAD_TIMENEST);
3927     else if (cert->dwRevokedReason)
3928         add_string_resource_to_control(hwnd, IDS_CERTIFICATE_REVOKED);
3929     else
3930         add_string_resource_to_control(hwnd, IDS_CERTIFICATE_VALID);
3931 }
3932
3933 static void set_certificate_status_for_end_cert(HWND hwnd,
3934  PCCRYPTUI_VIEWCERTIFICATE_STRUCTW pCertViewInfo)
3935 {
3936     HWND status = GetDlgItem(hwnd, IDC_CERTIFICATESTATUSTEXT);
3937     CRYPT_PROVIDER_SGNR *provSigner = WTHelperGetProvSignerFromChain(
3938      (CRYPT_PROVIDER_DATA *)pCertViewInfo->u.pCryptProviderData,
3939      pCertViewInfo->idxSigner, pCertViewInfo->fCounterSigner,
3940      pCertViewInfo->idxCounterSigner);
3941     CRYPT_PROVIDER_CERT *provCert = WTHelperGetProvCertFromChain(provSigner,
3942      pCertViewInfo->idxCert);
3943
3944     set_certificate_status(status, provCert);
3945 }
3946
3947 static void show_cert_hierarchy(HWND hwnd, struct hierarchy_data *data)
3948 {
3949     /* Disable view certificate button until a certificate is selected */
3950     EnableWindow(GetDlgItem(hwnd, IDC_VIEWCERTIFICATE), FALSE);
3951     show_cert_chain(hwnd, data);
3952     set_certificate_status_for_end_cert(hwnd, data->pCertViewInfo);
3953 }
3954
3955 static void show_dialog_for_selected_cert(HWND hwnd)
3956 {
3957     HWND tree = GetDlgItem(hwnd, IDC_CERTPATH);
3958     TVITEMW item;
3959     struct hierarchy_data *data;
3960     DWORD selection;
3961
3962     memset(&item, 0, sizeof(item));
3963     item.mask = TVIF_HANDLE | TVIF_PARAM;
3964     item.hItem = (HTREEITEM)SendMessageW(tree, TVM_GETNEXTITEM, TVGN_CARET,
3965      (LPARAM)NULL);
3966     SendMessageW(tree, TVM_GETITEMW, 0, (LPARAM)&item);
3967     data = get_hierarchy_data_from_tree_item(tree, item.hItem);
3968     selection = lparam_to_index(data, item.lParam);
3969     if (selection != 0)
3970     {
3971         CRYPT_PROVIDER_SGNR *provSigner;
3972         CRYPTUI_VIEWCERTIFICATE_STRUCTW viewInfo;
3973         BOOL changed = FALSE;
3974
3975         provSigner = WTHelperGetProvSignerFromChain(
3976          (CRYPT_PROVIDER_DATA *)data->pCertViewInfo->u.pCryptProviderData,
3977          data->pCertViewInfo->idxSigner,
3978          data->pCertViewInfo->fCounterSigner,
3979          data->pCertViewInfo->idxCounterSigner);
3980         memset(&viewInfo, 0, sizeof(viewInfo));
3981         viewInfo.dwSize = sizeof(viewInfo);
3982         viewInfo.dwFlags = data->pCertViewInfo->dwFlags;
3983         viewInfo.szTitle = data->pCertViewInfo->szTitle;
3984         viewInfo.pCertContext = provSigner->pasCertChain[selection].pCert;
3985         viewInfo.cStores = data->pCertViewInfo->cStores;
3986         viewInfo.rghStores = data->pCertViewInfo->rghStores;
3987         viewInfo.cPropSheetPages = data->pCertViewInfo->cPropSheetPages;
3988         viewInfo.rgPropSheetPages = data->pCertViewInfo->rgPropSheetPages;
3989         viewInfo.nStartPage = data->pCertViewInfo->nStartPage;
3990         CryptUIDlgViewCertificateW(&viewInfo, &changed);
3991         if (changed)
3992         {
3993             /* Delete the contents of the tree */
3994             SendMessageW(tree, TVM_DELETEITEM, 0, (LPARAM)TVI_ROOT);
3995             /* Reinitialize the tree */
3996             show_cert_hierarchy(hwnd, data);
3997         }
3998     }
3999 }
4000
4001 static LRESULT CALLBACK hierarchy_dlg_proc(HWND hwnd, UINT msg, WPARAM wp,
4002  LPARAM lp)
4003 {
4004     PROPSHEETPAGEW *page;
4005     struct hierarchy_data *data;
4006     LRESULT ret = 0;
4007     HWND tree = GetDlgItem(hwnd, IDC_CERTPATH);
4008
4009     TRACE("(%p, %08x, %08lx, %08lx)\n", hwnd, msg, wp, lp);
4010
4011     switch (msg)
4012     {
4013     case WM_INITDIALOG:
4014         page = (PROPSHEETPAGEW *)lp;
4015         data = (struct hierarchy_data *)page->lParam;
4016         show_cert_hierarchy(hwnd, data);
4017         break;
4018     case WM_NOTIFY:
4019     {
4020         NMHDR *hdr;
4021
4022         hdr = (NMHDR *)lp;
4023         switch (hdr->code)
4024         {
4025         case TVN_SELCHANGEDW:
4026         {
4027             NMTREEVIEWW *nm = (NMTREEVIEWW*)lp;
4028             DWORD selection;
4029             CRYPT_PROVIDER_SGNR *provSigner;
4030
4031             data = get_hierarchy_data_from_tree_item(tree, nm->itemNew.hItem);
4032             selection = lparam_to_index(data, nm->itemNew.lParam);
4033             provSigner = WTHelperGetProvSignerFromChain(
4034              (CRYPT_PROVIDER_DATA *)data->pCertViewInfo->u.pCryptProviderData,
4035              data->pCertViewInfo->idxSigner,
4036              data->pCertViewInfo->fCounterSigner,
4037              data->pCertViewInfo->idxCounterSigner);
4038             EnableWindow(GetDlgItem(hwnd, IDC_VIEWCERTIFICATE), selection != 0);
4039             set_certificate_status(GetDlgItem(hwnd, IDC_CERTIFICATESTATUSTEXT),
4040              &provSigner->pasCertChain[selection]);
4041             break;
4042         }
4043         case NM_DBLCLK:
4044             show_dialog_for_selected_cert(hwnd);
4045             SetWindowLongPtrW(hwnd, DWLP_MSGRESULT, 1);
4046             ret = 1;
4047             break;
4048         }
4049         break;
4050     }
4051     case WM_COMMAND:
4052         switch (wp)
4053         {
4054         case IDC_VIEWCERTIFICATE:
4055             show_dialog_for_selected_cert(hwnd);
4056             break;
4057         }
4058         break;
4059     case WM_REFRESH_VIEW:
4060     {
4061         TVITEMW item;
4062
4063         /* Get hierarchy data */
4064         memset(&item, 0, sizeof(item));
4065         item.mask = TVIF_HANDLE | TVIF_PARAM;
4066         item.hItem = (HTREEITEM)SendMessageW(tree, TVM_GETNEXTITEM, TVGN_ROOT,
4067          (LPARAM)NULL);
4068         data = get_hierarchy_data_from_tree_item(tree, item.hItem);
4069         /* Delete the contents of the tree */
4070         SendMessageW(tree, TVM_DELETEITEM, 0, (LPARAM)TVI_ROOT);
4071         /* Reinitialize the tree */
4072         show_cert_hierarchy(hwnd, data);
4073         break;
4074     }
4075     }
4076     return ret;
4077 }
4078
4079 static UINT CALLBACK hierarchy_callback(HWND hwnd, UINT msg,
4080  PROPSHEETPAGEW *page)
4081 {
4082     struct hierarchy_data *data;
4083
4084     switch (msg)
4085     {
4086     case PSPCB_RELEASE:
4087         data = (struct hierarchy_data *)page->lParam;
4088         ImageList_Destroy(data->imageList);
4089         HeapFree(GetProcessHeap(), 0, data);
4090         break;
4091     }
4092     return 0;
4093 }
4094
4095 static BOOL init_hierarchy_page(PCCRYPTUI_VIEWCERTIFICATE_STRUCTW pCertViewInfo,
4096  PROPSHEETPAGEW *page)
4097 {
4098     struct hierarchy_data *data = HeapAlloc(GetProcessHeap(), 0,
4099      sizeof(struct hierarchy_data));
4100     BOOL ret = FALSE;
4101
4102     if (data)
4103     {
4104         data->imageList = ImageList_Create(16, 16, ILC_COLOR4 | ILC_MASK, 2, 0);
4105         if (data->imageList)
4106         {
4107             HBITMAP bmp;
4108             COLORREF backColor = RGB(255, 0, 255);
4109
4110             data->pCertViewInfo = pCertViewInfo;
4111             data->selectedCert = 0xffffffff;
4112
4113             bmp = LoadBitmapW(hInstance, MAKEINTRESOURCEW(IDB_SMALL_ICONS));
4114             ImageList_AddMasked(data->imageList, bmp, backColor);
4115             DeleteObject(bmp);
4116             ImageList_SetBkColor(data->imageList, CLR_NONE);
4117
4118             memset(page, 0, sizeof(PROPSHEETPAGEW));
4119             page->dwSize = sizeof(PROPSHEETPAGEW);
4120             page->dwFlags = PSP_USECALLBACK;
4121             page->hInstance = hInstance;
4122             page->u.pszTemplate = MAKEINTRESOURCEW(IDD_HIERARCHY);
4123             page->pfnDlgProc = hierarchy_dlg_proc;
4124             page->lParam = (LPARAM)data;
4125             page->pfnCallback = hierarchy_callback;
4126             ret = TRUE;
4127         }
4128         else
4129             HeapFree(GetProcessHeap(), 0, data);
4130     }
4131     return ret;
4132 }
4133
4134 static int CALLBACK cert_prop_sheet_proc(HWND hwnd, UINT msg, LPARAM lp)
4135 {
4136     RECT rc;
4137     POINT topLeft;
4138
4139     TRACE("(%p, %08x, %08lx)\n", hwnd, msg, lp);
4140
4141     switch (msg)
4142     {
4143     case PSCB_INITIALIZED:
4144         /* Get cancel button's position.. */
4145         GetWindowRect(GetDlgItem(hwnd, IDCANCEL), &rc);
4146         topLeft.x = rc.left;
4147         topLeft.y = rc.top;
4148         ScreenToClient(hwnd, &topLeft);
4149         /* hide the cancel button.. */
4150         ShowWindow(GetDlgItem(hwnd, IDCANCEL), FALSE);
4151         /* get the OK button's size.. */
4152         GetWindowRect(GetDlgItem(hwnd, IDOK), &rc);
4153         /* and move the OK button to the cancel button's original position. */
4154         MoveWindow(GetDlgItem(hwnd, IDOK), topLeft.x, topLeft.y,
4155          rc.right - rc.left, rc.bottom - rc.top, FALSE);
4156         GetWindowRect(GetDlgItem(hwnd, IDOK), &rc);
4157         break;
4158     }
4159     return 0;
4160 }
4161
4162 static BOOL show_cert_dialog(PCCRYPTUI_VIEWCERTIFICATE_STRUCTW pCertViewInfo,
4163  CRYPT_PROVIDER_CERT *provCert, BOOL *pfPropertiesChanged)
4164 {
4165     static const WCHAR riched[] = { 'r','i','c','h','e','d','2','0',0 };
4166     DWORD nPages;
4167     PROPSHEETPAGEW *pages;
4168     BOOL ret = FALSE;
4169     HMODULE lib = LoadLibraryW(riched);
4170
4171     nPages = pCertViewInfo->cPropSheetPages + 1; /* one for the General tab */
4172     if (!(pCertViewInfo->dwFlags & CRYPTUI_HIDE_DETAILPAGE))
4173         nPages++;
4174     if (!(pCertViewInfo->dwFlags & CRYPTUI_HIDE_HIERARCHYPAGE))
4175         nPages++;
4176     pages = HeapAlloc(GetProcessHeap(), 0, nPages * sizeof(PROPSHEETPAGEW));
4177     if (pages)
4178     {
4179         PROPSHEETHEADERW hdr;
4180         CRYPTUI_INITDIALOG_STRUCT *init = NULL;
4181         DWORD i;
4182
4183         memset(&hdr, 0, sizeof(hdr));
4184         hdr.dwSize = sizeof(hdr);
4185         hdr.dwFlags = PSH_NOAPPLYNOW | PSH_PROPSHEETPAGE | PSH_USECALLBACK;
4186         hdr.hInstance = hInstance;
4187         if (pCertViewInfo->szTitle)
4188             hdr.pszCaption = pCertViewInfo->szTitle;
4189         else
4190             hdr.pszCaption = MAKEINTRESOURCEW(IDS_CERTIFICATE);
4191         init_general_page(pCertViewInfo, &pages[hdr.nPages++]);
4192         if (!(pCertViewInfo->dwFlags & CRYPTUI_HIDE_DETAILPAGE))
4193         {
4194             if (init_detail_page(pCertViewInfo, pfPropertiesChanged,
4195              &pages[hdr.nPages]))
4196                 hdr.nPages++;
4197         }
4198         if (!(pCertViewInfo->dwFlags & CRYPTUI_HIDE_HIERARCHYPAGE))
4199         {
4200             if (init_hierarchy_page(pCertViewInfo, &pages[hdr.nPages]))
4201                 hdr.nPages++;
4202         }
4203         /* Copy each additional page, and create the init dialog struct for it
4204          */
4205         if (pCertViewInfo->cPropSheetPages)
4206         {
4207             init = HeapAlloc(GetProcessHeap(), 0,
4208              pCertViewInfo->cPropSheetPages *
4209              sizeof(CRYPTUI_INITDIALOG_STRUCT));
4210             if (init)
4211             {
4212                 for (i = 0; i < pCertViewInfo->cPropSheetPages; i++)
4213                 {
4214                     memcpy(&pages[hdr.nPages + i],
4215                      &pCertViewInfo->rgPropSheetPages[i],
4216                      sizeof(PROPSHEETPAGEW));
4217                     init[i].lParam = pCertViewInfo->rgPropSheetPages[i].lParam;
4218                     init[i].pCertContext = pCertViewInfo->pCertContext;
4219                     pages[hdr.nPages + i].lParam = (LPARAM)&init[i];
4220                 }
4221                 if (pCertViewInfo->nStartPage & 0x8000)
4222                 {
4223                     /* Start page index is relative to the number of default
4224                      * pages
4225                      */
4226                     hdr.u2.nStartPage = pCertViewInfo->nStartPage + hdr.nPages;
4227                 }
4228                 else
4229                     hdr.u2.nStartPage = pCertViewInfo->nStartPage;
4230                 hdr.nPages = nPages;
4231                 ret = TRUE;
4232             }
4233             else
4234                 SetLastError(ERROR_OUTOFMEMORY);
4235         }
4236         else
4237         {
4238             /* Ignore the relative flag if there aren't any additional pages */
4239             hdr.u2.nStartPage = pCertViewInfo->nStartPage & 0x7fff;
4240             ret = TRUE;
4241         }
4242         if (ret)
4243         {
4244             INT_PTR l;
4245
4246             hdr.u3.ppsp = pages;
4247             hdr.pfnCallback = cert_prop_sheet_proc;
4248             l = PropertySheetW(&hdr);
4249             if (l == 0)
4250             {
4251                 SetLastError(ERROR_CANCELLED);
4252                 ret = FALSE;
4253             }
4254         }
4255         HeapFree(GetProcessHeap(), 0, init);
4256         HeapFree(GetProcessHeap(), 0, pages);
4257     }
4258     else
4259         SetLastError(ERROR_OUTOFMEMORY);
4260     FreeLibrary(lib);
4261     return ret;
4262 }
4263
4264 /***********************************************************************
4265  *              CryptUIDlgViewCertificateW (CRYPTUI.@)
4266  */
4267 BOOL WINAPI CryptUIDlgViewCertificateW(
4268  PCCRYPTUI_VIEWCERTIFICATE_STRUCTW pCertViewInfo, BOOL *pfPropertiesChanged)
4269 {
4270     static GUID generic_cert_verify = WINTRUST_ACTION_GENERIC_CERT_VERIFY;
4271     CRYPTUI_VIEWCERTIFICATE_STRUCTW viewInfo;
4272     WINTRUST_DATA wvt;
4273     WINTRUST_CERT_INFO cert;
4274     BOOL ret = FALSE;
4275     CRYPT_PROVIDER_SGNR *signer;
4276     CRYPT_PROVIDER_CERT *provCert = NULL;
4277
4278     TRACE("(%p, %p)\n", pCertViewInfo, pfPropertiesChanged);
4279
4280     if (pCertViewInfo->dwSize != sizeof(CRYPTUI_VIEWCERTIFICATE_STRUCTW))
4281     {
4282         SetLastError(ERROR_INVALID_PARAMETER);
4283         return FALSE;
4284     }
4285     /* Make a local copy in case we have to call WinVerifyTrust ourselves */
4286     memcpy(&viewInfo, pCertViewInfo, sizeof(viewInfo));
4287     if (!viewInfo.u.hWVTStateData)
4288     {
4289         memset(&wvt, 0, sizeof(wvt));
4290         wvt.cbStruct = sizeof(wvt);
4291         wvt.dwUIChoice = WTD_UI_NONE;
4292         if (viewInfo.dwFlags &
4293          CRYPTUI_ENABLE_REVOCATION_CHECK_CHAIN_EXCLUDE_ROOT)
4294             wvt.fdwRevocationChecks |= WTD_REVOCATION_CHECK_CHAIN_EXCLUDE_ROOT;
4295         if (viewInfo.dwFlags & CRYPTUI_ENABLE_REVOCATION_CHECK_END_CERT)
4296             wvt.fdwRevocationChecks |= WTD_REVOCATION_CHECK_END_CERT;
4297         if (viewInfo.dwFlags & CRYPTUI_ENABLE_REVOCATION_CHECK_CHAIN)
4298             wvt.fdwRevocationChecks |= WTD_REVOCATION_CHECK_CHAIN;
4299         wvt.dwUnionChoice = WTD_CHOICE_CERT;
4300         memset(&cert, 0, sizeof(cert));
4301         cert.cbStruct = sizeof(cert);
4302         cert.psCertContext = (CERT_CONTEXT *)viewInfo.pCertContext;
4303         cert.chStores = viewInfo.cStores;
4304         cert.pahStores = viewInfo.rghStores;
4305         wvt.u.pCert = &cert;
4306         wvt.dwStateAction = WTD_STATEACTION_VERIFY;
4307         WinVerifyTrust(NULL, &generic_cert_verify, &wvt);
4308         viewInfo.u.pCryptProviderData =
4309          WTHelperProvDataFromStateData(wvt.hWVTStateData);
4310         signer = WTHelperGetProvSignerFromChain(
4311          (CRYPT_PROVIDER_DATA *)viewInfo.u.pCryptProviderData, 0, FALSE, 0);
4312         provCert = WTHelperGetProvCertFromChain(signer, 0);
4313         ret = TRUE;
4314     }
4315     else
4316     {
4317         viewInfo.u.pCryptProviderData =
4318          WTHelperProvDataFromStateData(viewInfo.u.hWVTStateData);
4319         signer = WTHelperGetProvSignerFromChain(
4320          (CRYPT_PROVIDER_DATA *)viewInfo.u.pCryptProviderData,
4321          viewInfo.idxSigner, viewInfo.fCounterSigner,
4322          viewInfo.idxCounterSigner);
4323         provCert = WTHelperGetProvCertFromChain(signer, viewInfo.idxCert);
4324         ret = TRUE;
4325     }
4326     if (ret)
4327     {
4328         ret = show_cert_dialog(&viewInfo, provCert, pfPropertiesChanged);
4329         if (!viewInfo.u.hWVTStateData)
4330         {
4331             wvt.dwStateAction = WTD_STATEACTION_CLOSE;
4332             WinVerifyTrust(NULL, &generic_cert_verify, &wvt);
4333         }
4334     }
4335     return ret;
4336 }
4337
4338 /***********************************************************************
4339  *              CryptUIDlgViewContext (CRYPTUI.@)
4340  */
4341 BOOL WINAPI CryptUIDlgViewContext(DWORD dwContextType, LPVOID pvContext,
4342  HWND hwnd, LPCWSTR pwszTitle, DWORD dwFlags, LPVOID pvReserved)
4343 {
4344     BOOL ret;
4345
4346     TRACE("(%d, %p, %p, %s, %08x, %p)\n", dwContextType, pvContext, hwnd,
4347      debugstr_w(pwszTitle), dwFlags, pvReserved);
4348
4349     switch (dwContextType)
4350     {
4351     case CERT_STORE_CERTIFICATE_CONTEXT:
4352     {
4353         CRYPTUI_VIEWCERTIFICATE_STRUCTW viewInfo;
4354
4355         memset(&viewInfo, 0, sizeof(viewInfo));
4356         viewInfo.dwSize = sizeof(viewInfo);
4357         viewInfo.hwndParent = hwnd;
4358         viewInfo.szTitle = pwszTitle;
4359         viewInfo.pCertContext = pvContext;
4360         ret = CryptUIDlgViewCertificateW(&viewInfo, NULL);
4361         break;
4362     }
4363     default:
4364         FIXME("unimplemented for context type %d\n", dwContextType);
4365         SetLastError(E_INVALIDARG);
4366         ret = FALSE;
4367     }
4368     return ret;
4369 }
4370
4371 /* Decodes a cert's basic constraints extension (either szOID_BASIC_CONSTRAINTS
4372  * or szOID_BASIC_CONSTRAINTS2, whichever is present) to determine if it
4373  * should be a CA.  If neither extension is present, returns
4374  * defaultIfNotSpecified.
4375  */
4376 static BOOL is_ca_cert(PCCERT_CONTEXT cert, BOOL defaultIfNotSpecified)
4377 {
4378     BOOL isCA = defaultIfNotSpecified;
4379     PCERT_EXTENSION ext = CertFindExtension(szOID_BASIC_CONSTRAINTS,
4380      cert->pCertInfo->cExtension, cert->pCertInfo->rgExtension);
4381
4382     if (ext)
4383     {
4384         CERT_BASIC_CONSTRAINTS_INFO *info;
4385         DWORD size = 0;
4386
4387         if (CryptDecodeObjectEx(X509_ASN_ENCODING, szOID_BASIC_CONSTRAINTS,
4388          ext->Value.pbData, ext->Value.cbData, CRYPT_DECODE_ALLOC_FLAG,
4389          NULL, (LPBYTE)&info, &size))
4390         {
4391             if (info->SubjectType.cbData == 1)
4392                 isCA = info->SubjectType.pbData[0] & CERT_CA_SUBJECT_FLAG;
4393             LocalFree(info);
4394         }
4395     }
4396     else
4397     {
4398         ext = CertFindExtension(szOID_BASIC_CONSTRAINTS2,
4399          cert->pCertInfo->cExtension, cert->pCertInfo->rgExtension);
4400         if (ext)
4401         {
4402             CERT_BASIC_CONSTRAINTS2_INFO info;
4403             DWORD size = sizeof(CERT_BASIC_CONSTRAINTS2_INFO);
4404
4405             if (CryptDecodeObjectEx(X509_ASN_ENCODING,
4406              szOID_BASIC_CONSTRAINTS2, ext->Value.pbData, ext->Value.cbData,
4407              0, NULL, &info, &size))
4408                 isCA = info.fCA;
4409         }
4410     }
4411     return isCA;
4412 }
4413
4414 static HCERTSTORE choose_store_for_cert(PCCERT_CONTEXT cert)
4415 {
4416     LPCWSTR storeName;
4417
4418     if (is_ca_cert(cert, TRUE))
4419         storeName = ca;
4420     else
4421         storeName = addressBook;
4422     return CertOpenStore(CERT_STORE_PROV_SYSTEM_W, 0, 0,
4423      CERT_SYSTEM_STORE_CURRENT_USER, storeName);
4424 }
4425
4426 static BOOL import_cert(PCCERT_CONTEXT cert, HCERTSTORE hDestCertStore)
4427 {
4428     HCERTSTORE store;
4429     BOOL ret;
4430
4431     if (!cert)
4432     {
4433         SetLastError(E_INVALIDARG);
4434         return FALSE;
4435     }
4436     if (hDestCertStore) store = hDestCertStore;
4437     else
4438     {
4439         if (!(store = choose_store_for_cert(cert)))
4440         {
4441             WARN("unable to open certificate store\n");
4442             return FALSE;
4443         }
4444     }
4445     ret = CertAddCertificateContextToStore(store, cert,
4446      CERT_STORE_ADD_REPLACE_EXISTING_INHERIT_PROPERTIES, NULL);
4447     if (!hDestCertStore) CertCloseStore(store, 0);
4448     return ret;
4449 }
4450
4451 static BOOL import_crl(PCCRL_CONTEXT crl, HCERTSTORE hDestCertStore)
4452 {
4453     HCERTSTORE store;
4454     BOOL ret;
4455
4456     if (!crl)
4457     {
4458         SetLastError(E_INVALIDARG);
4459         return FALSE;
4460     }
4461     if (hDestCertStore) store = hDestCertStore;
4462     else
4463     {
4464         if (!(store = CertOpenStore(CERT_STORE_PROV_SYSTEM_W, 0, 0,
4465          CERT_SYSTEM_STORE_CURRENT_USER, ca)))
4466         {
4467             WARN("unable to open certificate store\n");
4468             return FALSE;
4469         }
4470     }
4471     ret = CertAddCRLContextToStore(store, crl,
4472      CERT_STORE_ADD_REPLACE_EXISTING_INHERIT_PROPERTIES, NULL);
4473     if (!hDestCertStore) CertCloseStore(store, 0);
4474     return ret;
4475 }
4476
4477 static BOOL import_ctl(PCCTL_CONTEXT ctl, HCERTSTORE hDestCertStore)
4478 {
4479     HCERTSTORE store;
4480     BOOL ret;
4481
4482     if (!ctl)
4483     {
4484         SetLastError(E_INVALIDARG);
4485         return FALSE;
4486     }
4487     if (hDestCertStore) store = hDestCertStore;
4488     else
4489     {
4490         static const WCHAR trust[] = { 'T','r','u','s','t',0 };
4491
4492         if (!(store = CertOpenStore(CERT_STORE_PROV_SYSTEM_W, 0, 0,
4493          CERT_SYSTEM_STORE_CURRENT_USER, trust)))
4494         {
4495             WARN("unable to open certificate store\n");
4496             return FALSE;
4497         }
4498     }
4499     ret = CertAddCTLContextToStore(store, ctl,
4500      CERT_STORE_ADD_REPLACE_EXISTING_INHERIT_PROPERTIES, NULL);
4501     if (!hDestCertStore) CertCloseStore(store, 0);
4502     return ret;
4503 }
4504
4505 /* Checks type, a type such as CERT_QUERY_CONTENT_CERT returned by
4506  * CryptQueryObject, against the allowed types.  Returns TRUE if the
4507  * type is allowed, FALSE otherwise.
4508  */
4509 static BOOL check_context_type(DWORD dwFlags, DWORD type)
4510 {
4511     BOOL ret;
4512
4513     if (dwFlags &
4514      (CRYPTUI_WIZ_IMPORT_ALLOW_CERT | CRYPTUI_WIZ_IMPORT_ALLOW_CRL |
4515      CRYPTUI_WIZ_IMPORT_ALLOW_CTL))
4516     {
4517         switch (type)
4518         {
4519         case CERT_QUERY_CONTENT_CERT:
4520         case CERT_QUERY_CONTENT_SERIALIZED_CERT:
4521             ret = dwFlags & CRYPTUI_WIZ_IMPORT_ALLOW_CERT;
4522             break;
4523         case CERT_QUERY_CONTENT_CRL:
4524         case CERT_QUERY_CONTENT_SERIALIZED_CRL:
4525             ret = dwFlags & CRYPTUI_WIZ_IMPORT_ALLOW_CRL;
4526             break;
4527         case CERT_QUERY_CONTENT_CTL:
4528         case CERT_QUERY_CONTENT_SERIALIZED_CTL:
4529             ret = dwFlags & CRYPTUI_WIZ_IMPORT_ALLOW_CTL;
4530             break;
4531         default:
4532             /* The remaining types contain more than one type, so allow
4533              * any combination.
4534              */
4535             ret = TRUE;
4536         }
4537     }
4538     else
4539     {
4540         /* No allowed types specified, so any type is allowed */
4541         ret = TRUE;
4542     }
4543     if (!ret)
4544         SetLastError(E_INVALIDARG);
4545     return ret;
4546 }
4547
4548
4549 static void import_warning(DWORD dwFlags, HWND hwnd, LPCWSTR szTitle,
4550  int warningID)
4551 {
4552     if (!(dwFlags & CRYPTUI_WIZ_NO_UI))
4553     {
4554         WCHAR title[MAX_STRING_LEN], error[MAX_STRING_LEN];
4555         LPCWSTR pTitle;
4556
4557         if (szTitle)
4558             pTitle = szTitle;
4559         else
4560         {
4561             LoadStringW(hInstance, IDS_IMPORT_WIZARD, title,
4562              sizeof(title) / sizeof(title[0]));
4563             pTitle = title;
4564         }
4565         LoadStringW(hInstance, warningID, error,
4566          sizeof(error) / sizeof(error[0]));
4567         MessageBoxW(hwnd, error, pTitle, MB_ICONERROR | MB_OK);
4568     }
4569 }
4570
4571 static void import_warn_type_mismatch(DWORD dwFlags, HWND hwnd, LPCWSTR szTitle)
4572 {
4573     import_warning(dwFlags, hwnd, szTitle, IDS_IMPORT_TYPE_MISMATCH);
4574 }
4575
4576 static BOOL check_store_context_type(DWORD dwFlags, HCERTSTORE store)
4577 {
4578     BOOL ret;
4579
4580     if (dwFlags &
4581      (CRYPTUI_WIZ_IMPORT_ALLOW_CERT | CRYPTUI_WIZ_IMPORT_ALLOW_CRL |
4582      CRYPTUI_WIZ_IMPORT_ALLOW_CTL))
4583     {
4584         PCCERT_CONTEXT cert;
4585         PCCRL_CONTEXT crl;
4586         PCCTL_CONTEXT ctl;
4587
4588         ret = TRUE;
4589         if ((cert = CertEnumCertificatesInStore(store, NULL)))
4590         {
4591             CertFreeCertificateContext(cert);
4592             if (!(dwFlags & CRYPTUI_WIZ_IMPORT_ALLOW_CERT))
4593                 ret = FALSE;
4594         }
4595         if (ret && (crl = CertEnumCRLsInStore(store, NULL)))
4596         {
4597             CertFreeCRLContext(crl);
4598             if (!(dwFlags & CRYPTUI_WIZ_IMPORT_ALLOW_CRL))
4599                 ret = FALSE;
4600         }
4601         if (ret && (ctl = CertEnumCTLsInStore(store, NULL)))
4602         {
4603             CertFreeCTLContext(ctl);
4604             if (!(dwFlags & CRYPTUI_WIZ_IMPORT_ALLOW_CTL))
4605                 ret = FALSE;
4606         }
4607     }
4608     else
4609         ret = TRUE;
4610     if (!ret)
4611         SetLastError(E_INVALIDARG);
4612     return ret;
4613 }
4614
4615 static BOOL import_store(DWORD dwFlags, HWND hwnd, LPCWSTR szTitle,
4616  HCERTSTORE source, HCERTSTORE dest)
4617 {
4618     BOOL ret;
4619
4620     if ((ret = check_store_context_type(dwFlags, source)))
4621     {
4622         PCCERT_CONTEXT cert = NULL;
4623         PCCRL_CONTEXT crl = NULL;
4624         PCCTL_CONTEXT ctl = NULL;
4625
4626         do {
4627             cert = CertEnumCertificatesInStore(source, cert);
4628             if (cert)
4629                 ret = import_cert(cert, dest);
4630         } while (ret && cert);
4631         do {
4632             crl = CertEnumCRLsInStore(source, crl);
4633             if (crl)
4634                 ret = import_crl(crl, dest);
4635         } while (ret && crl);
4636         do {
4637             ctl = CertEnumCTLsInStore(source, ctl);
4638             if (ctl)
4639                 ret = import_ctl(ctl, dest);
4640         } while (ret && ctl);
4641     }
4642     else
4643         import_warn_type_mismatch(dwFlags, hwnd, szTitle);
4644     return ret;
4645 }
4646
4647 static HCERTSTORE open_store_from_file(DWORD dwFlags, LPCWSTR fileName,
4648  DWORD *pContentType)
4649 {
4650     HCERTSTORE store = NULL;
4651     DWORD contentType = 0, expectedContentTypeFlags;
4652
4653     if (dwFlags &
4654      (CRYPTUI_WIZ_IMPORT_ALLOW_CERT | CRYPTUI_WIZ_IMPORT_ALLOW_CRL |
4655      CRYPTUI_WIZ_IMPORT_ALLOW_CTL))
4656     {
4657         expectedContentTypeFlags =
4658          CERT_QUERY_CONTENT_FLAG_SERIALIZED_STORE |
4659          CERT_QUERY_CONTENT_FLAG_PKCS7_SIGNED |
4660          CERT_QUERY_CONTENT_FLAG_PFX;
4661         if (dwFlags & CRYPTUI_WIZ_IMPORT_ALLOW_CERT)
4662             expectedContentTypeFlags |=
4663              CERT_QUERY_CONTENT_FLAG_CERT |
4664              CERT_QUERY_CONTENT_FLAG_SERIALIZED_CERT;
4665         if (dwFlags & CRYPTUI_WIZ_IMPORT_ALLOW_CRL)
4666             expectedContentTypeFlags |=
4667              CERT_QUERY_CONTENT_FLAG_SERIALIZED_CRL |
4668              CERT_QUERY_CONTENT_FLAG_CRL;
4669         if (dwFlags & CRYPTUI_WIZ_IMPORT_ALLOW_CTL)
4670             expectedContentTypeFlags |=
4671              CERT_QUERY_CONTENT_FLAG_CTL |
4672              CERT_QUERY_CONTENT_FLAG_SERIALIZED_CTL;
4673     }
4674     else
4675         expectedContentTypeFlags =
4676          CERT_QUERY_CONTENT_FLAG_CERT |
4677          CERT_QUERY_CONTENT_FLAG_CTL |
4678          CERT_QUERY_CONTENT_FLAG_CRL |
4679          CERT_QUERY_CONTENT_FLAG_SERIALIZED_STORE |
4680          CERT_QUERY_CONTENT_FLAG_SERIALIZED_CERT |
4681          CERT_QUERY_CONTENT_FLAG_SERIALIZED_CTL |
4682          CERT_QUERY_CONTENT_FLAG_SERIALIZED_CRL |
4683          CERT_QUERY_CONTENT_FLAG_PKCS7_SIGNED |
4684          CERT_QUERY_CONTENT_FLAG_PFX;
4685
4686     CryptQueryObject(CERT_QUERY_OBJECT_FILE, fileName,
4687      expectedContentTypeFlags, CERT_QUERY_FORMAT_FLAG_ALL, 0, NULL,
4688      &contentType, NULL, &store, NULL, NULL);
4689     if (pContentType)
4690         *pContentType = contentType;
4691     return store;
4692 }
4693
4694 static BOOL import_file(DWORD dwFlags, HWND hwnd, LPCWSTR szTitle,
4695  LPCWSTR fileName, HCERTSTORE dest)
4696 {
4697     HCERTSTORE source;
4698     BOOL ret;
4699
4700     if ((source = open_store_from_file(dwFlags, fileName, NULL)))
4701     {
4702         ret = import_store(dwFlags, hwnd, szTitle, source, dest);
4703         CertCloseStore(source, 0);
4704     }
4705     else
4706         ret = FALSE;
4707     return ret;
4708 }
4709
4710 struct ImportWizData
4711 {
4712     HFONT titleFont;
4713     DWORD dwFlags;
4714     LPCWSTR pwszWizardTitle;
4715     CRYPTUI_WIZ_IMPORT_SRC_INFO importSrc;
4716     LPWSTR fileName;
4717     DWORD contentType;
4718     BOOL freeSource;
4719     HCERTSTORE hDestCertStore;
4720     BOOL freeDest;
4721     BOOL autoDest;
4722     BOOL success;
4723 };
4724
4725 static LRESULT CALLBACK import_welcome_dlg_proc(HWND hwnd, UINT msg, WPARAM wp,
4726  LPARAM lp)
4727 {
4728     LRESULT ret = 0;
4729
4730     switch (msg)
4731     {
4732     case WM_INITDIALOG:
4733     {
4734         struct ImportWizData *data;
4735         PROPSHEETPAGEW *page = (PROPSHEETPAGEW *)lp;
4736         WCHAR fontFace[MAX_STRING_LEN];
4737         HDC hDC = GetDC(hwnd);
4738         int height;
4739
4740         data = (struct ImportWizData *)page->lParam;
4741         LoadStringW(hInstance, IDS_WIZARD_TITLE_FONT, fontFace,
4742          sizeof(fontFace) / sizeof(fontFace[0]));
4743         height = -MulDiv(12, GetDeviceCaps(hDC, LOGPIXELSY), 72);
4744         data->titleFont = CreateFontW(height, 0, 0, 0, FW_BOLD, 0, 0, 0,
4745          DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS,
4746          DEFAULT_QUALITY, DEFAULT_PITCH | FF_DONTCARE, fontFace);
4747         SendMessageW(GetDlgItem(hwnd, IDC_IMPORT_TITLE), WM_SETFONT,
4748          (WPARAM)data->titleFont, TRUE);
4749         ReleaseDC(hwnd, hDC);
4750         break;
4751     }
4752     case WM_NOTIFY:
4753     {
4754         NMHDR *hdr = (NMHDR *)lp;
4755
4756         switch (hdr->code)
4757         {
4758         case PSN_SETACTIVE:
4759             PostMessageW(GetParent(hwnd), PSM_SETWIZBUTTONS, 0, PSWIZB_NEXT);
4760             ret = TRUE;
4761             break;
4762         }
4763         break;
4764     }
4765     }
4766     return ret;
4767 }
4768
4769 static const WCHAR filter_cert[] = { '*','.','c','e','r',';','*','.',
4770  'c','r','t',0 };
4771 static const WCHAR filter_pfx[] = { '*','.','p','f','x',';','*','.',
4772  'p','1','2',0 };
4773 static const WCHAR filter_crl[] = { '*','.','c','r','l',0 };
4774 static const WCHAR filter_ctl[] = { '*','.','s','t','l',0 };
4775 static const WCHAR filter_serialized_store[] = { '*','.','s','s','t',0 };
4776 static const WCHAR filter_cms[] = { '*','.','s','p','c',';','*','.',
4777  'p','7','b',0 };
4778 static const WCHAR filter_all[] = { '*','.','*',0 };
4779
4780 struct StringToFilter
4781 {
4782     int     id;
4783     DWORD   allowFlags;
4784     LPCWSTR filter;
4785 } import_filters[] = {
4786  { IDS_IMPORT_FILTER_CERT, CRYPTUI_WIZ_IMPORT_ALLOW_CERT, filter_cert },
4787  { IDS_IMPORT_FILTER_PFX, 0, filter_pfx },
4788  { IDS_IMPORT_FILTER_CRL, CRYPTUI_WIZ_IMPORT_ALLOW_CRL, filter_crl },
4789  { IDS_IMPORT_FILTER_CTL, CRYPTUI_WIZ_IMPORT_ALLOW_CTL, filter_ctl },
4790  { IDS_IMPORT_FILTER_SERIALIZED_STORE, 0, filter_serialized_store },
4791  { IDS_IMPORT_FILTER_CMS, 0, filter_cms },
4792  { IDS_IMPORT_FILTER_ALL, 0, filter_all },
4793 };
4794
4795 static WCHAR *make_import_file_filter(DWORD dwFlags)
4796 {
4797     DWORD i;
4798     int len, totalLen = 2;
4799     LPWSTR filter = NULL, str;
4800
4801     for (i = 0; i < sizeof(import_filters) / sizeof(import_filters[0]); i++)
4802     {
4803         if (!import_filters[i].allowFlags || !dwFlags ||
4804          (dwFlags & import_filters[i].allowFlags))
4805         {
4806             len = LoadStringW(hInstance, import_filters[i].id, (LPWSTR)&str, 0);
4807             totalLen += len + strlenW(import_filters[i].filter) + 2;
4808         }
4809     }
4810     filter = HeapAlloc(GetProcessHeap(), 0, totalLen * sizeof(WCHAR));
4811     if (filter)
4812     {
4813         LPWSTR ptr;
4814
4815         ptr = filter;
4816         for (i = 0; i < sizeof(import_filters) / sizeof(import_filters[0]); i++)
4817         {
4818             if (!import_filters[i].allowFlags || !dwFlags ||
4819              (dwFlags & import_filters[i].allowFlags))
4820             {
4821                 len = LoadStringW(hInstance, import_filters[i].id,
4822                  (LPWSTR)&str, 0);
4823                 memcpy(ptr, str, len * sizeof(WCHAR));
4824                 ptr += len;
4825                 *ptr++ = 0;
4826                 strcpyW(ptr, import_filters[i].filter);
4827                 ptr += strlenW(import_filters[i].filter) + 1;
4828             }
4829         }
4830         *ptr++ = 0;
4831     }
4832     return filter;
4833 }
4834
4835 static BOOL import_validate_filename(HWND hwnd, struct ImportWizData *data,
4836  LPCWSTR fileName)
4837 {
4838     HANDLE file;
4839     BOOL ret = FALSE;
4840
4841     file = CreateFileW(fileName, GENERIC_READ, FILE_SHARE_READ, NULL,
4842      OPEN_EXISTING, 0, NULL);
4843     if (file != INVALID_HANDLE_VALUE)
4844     {
4845         HCERTSTORE source = open_store_from_file(data->dwFlags, fileName,
4846          &data->contentType);
4847         int warningID = 0;
4848
4849         if (!source)
4850             warningID = IDS_IMPORT_BAD_FORMAT;
4851         else if (!check_store_context_type(data->dwFlags, source))
4852             warningID = IDS_IMPORT_TYPE_MISMATCH;
4853         else
4854         {
4855             data->importSrc.dwSubjectChoice =
4856              CRYPTUI_WIZ_IMPORT_SUBJECT_CERT_STORE;
4857             data->importSrc.u.hCertStore = source;
4858             data->freeSource = TRUE;
4859             ret = TRUE;
4860         }
4861         if (warningID)
4862         {
4863             import_warning(data->dwFlags, hwnd, data->pwszWizardTitle,
4864              warningID);
4865         }
4866         CloseHandle(file);
4867     }
4868     else
4869     {
4870         WCHAR title[MAX_STRING_LEN], error[MAX_STRING_LEN];
4871         LPCWSTR pTitle;
4872         LPWSTR msgBuf, fullError;
4873
4874         if (data->pwszWizardTitle)
4875             pTitle = data->pwszWizardTitle;
4876         else
4877         {
4878             LoadStringW(hInstance, IDS_IMPORT_WIZARD, title,
4879              sizeof(title) / sizeof(title[0]));
4880             pTitle = title;
4881         }
4882         LoadStringW(hInstance, IDS_IMPORT_OPEN_FAILED, error,
4883          sizeof(error) / sizeof(error[0]));
4884         FormatMessageW(
4885          FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, NULL,
4886          GetLastError(), 0, (LPWSTR) &msgBuf, 0, NULL);
4887         fullError = HeapAlloc(GetProcessHeap(), 0,
4888          (strlenW(error) + strlenW(fileName) + strlenW(msgBuf) + 3)
4889          * sizeof(WCHAR));
4890         if (fullError)
4891         {
4892             LPWSTR ptr = fullError;
4893
4894             strcpyW(ptr, error);
4895             ptr += strlenW(error);
4896             strcpyW(ptr, fileName);
4897             ptr += strlenW(fileName);
4898             *ptr++ = ':';
4899             *ptr++ = '\n';
4900             strcpyW(ptr, msgBuf);
4901             MessageBoxW(hwnd, fullError, pTitle, MB_ICONERROR | MB_OK);
4902             HeapFree(GetProcessHeap(), 0, fullError);
4903         }
4904         LocalFree(msgBuf);
4905     }
4906     return ret;
4907 }
4908
4909 static LRESULT CALLBACK import_file_dlg_proc(HWND hwnd, UINT msg, WPARAM wp,
4910  LPARAM lp)
4911 {
4912     LRESULT ret = 0;
4913     struct ImportWizData *data;
4914
4915     switch (msg)
4916     {
4917     case WM_INITDIALOG:
4918     {
4919         PROPSHEETPAGEW *page = (PROPSHEETPAGEW *)lp;
4920
4921         data = (struct ImportWizData *)page->lParam;
4922         SetWindowLongPtrW(hwnd, DWLP_USER, (LPARAM)data);
4923         break;
4924     }
4925     case WM_NOTIFY:
4926     {
4927         NMHDR *hdr = (NMHDR *)lp;
4928
4929         switch (hdr->code)
4930         {
4931         case PSN_SETACTIVE:
4932             PostMessageW(GetParent(hwnd), PSM_SETWIZBUTTONS, 0,
4933              PSWIZB_BACK | PSWIZB_NEXT);
4934             ret = TRUE;
4935             break;
4936         case PSN_WIZNEXT:
4937         {
4938             HWND fileNameEdit = GetDlgItem(hwnd, IDC_IMPORT_FILENAME);
4939             DWORD len = SendMessageW(fileNameEdit, WM_GETTEXTLENGTH, 0, 0);
4940
4941             data = (struct ImportWizData *)GetWindowLongPtrW(hwnd, DWLP_USER);
4942             if (!len)
4943             {
4944                 import_warning(data->dwFlags, hwnd, data->pwszWizardTitle,
4945                  IDS_IMPORT_EMPTY_FILE);
4946                 SetWindowLongPtrW(hwnd, DWLP_MSGRESULT, 1);
4947                 ret = 1;
4948             }
4949             else
4950             {
4951                 LPWSTR fileName = HeapAlloc(GetProcessHeap(), 0,
4952                  (len + 1) * sizeof(WCHAR));
4953
4954                 if (fileName)
4955                 {
4956                     SendMessageW(fileNameEdit, WM_GETTEXT, len + 1,
4957                      (LPARAM)fileName);
4958                     if (!import_validate_filename(hwnd, data, fileName))
4959                     {
4960                         HeapFree(GetProcessHeap(), 0, fileName);
4961                         SetWindowLongPtrW(hwnd, DWLP_MSGRESULT, 1);
4962                         ret = 1;
4963                     }
4964                     else
4965                         data->fileName = fileName;
4966                 }
4967             }
4968             break;
4969         }
4970         }
4971         break;
4972     }
4973     case WM_COMMAND:
4974         switch (wp)
4975         {
4976         case IDC_IMPORT_BROWSE_FILE:
4977         {
4978             OPENFILENAMEW ofn;
4979             WCHAR fileBuf[MAX_PATH];
4980
4981             data = (struct ImportWizData *)GetWindowLongPtrW(hwnd, DWLP_USER);
4982             memset(&ofn, 0, sizeof(ofn));
4983             ofn.lStructSize = sizeof(ofn);
4984             ofn.hwndOwner = hwnd;
4985             ofn.lpstrFilter = make_import_file_filter(data->dwFlags);
4986             ofn.lpstrFile = fileBuf;
4987             ofn.nMaxFile = sizeof(fileBuf) / sizeof(fileBuf[0]);
4988             fileBuf[0] = 0;
4989             if (GetOpenFileNameW(&ofn))
4990                 SendMessageW(GetDlgItem(hwnd, IDC_IMPORT_FILENAME), WM_SETTEXT,
4991                  0, (LPARAM)ofn.lpstrFile);
4992             HeapFree(GetProcessHeap(), 0, (LPWSTR)ofn.lpstrFilter);
4993             break;
4994         }
4995         }
4996         break;
4997     }
4998     return ret;
4999 }
5000
5001 static LRESULT CALLBACK import_store_dlg_proc(HWND hwnd, UINT msg, WPARAM wp,
5002  LPARAM lp)
5003 {
5004     LRESULT ret = 0;
5005     struct ImportWizData *data;
5006
5007     switch (msg)
5008     {
5009     case WM_INITDIALOG:
5010     {
5011         PROPSHEETPAGEW *page = (PROPSHEETPAGEW *)lp;
5012
5013         data = (struct ImportWizData *)page->lParam;
5014         SetWindowLongPtrW(hwnd, DWLP_USER, (LPARAM)data);
5015         if (!data->hDestCertStore)
5016         {
5017             SendMessageW(GetDlgItem(hwnd, IDC_IMPORT_AUTO_STORE), BM_CLICK,
5018              0, 0);
5019             EnableWindow(GetDlgItem(hwnd, IDC_IMPORT_STORE), FALSE);
5020             EnableWindow(GetDlgItem(hwnd, IDC_IMPORT_BROWSE_STORE), FALSE);
5021             EnableWindow(GetDlgItem(hwnd, IDC_IMPORT_SPECIFY_STORE), FALSE);
5022         }
5023         else
5024         {
5025             WCHAR storeTitle[MAX_STRING_LEN];
5026
5027             SendMessageW(GetDlgItem(hwnd, IDC_IMPORT_SPECIFY_STORE), BM_CLICK,
5028              0, 0);
5029             EnableWindow(GetDlgItem(hwnd, IDC_IMPORT_STORE), TRUE);
5030             EnableWindow(GetDlgItem(hwnd, IDC_IMPORT_BROWSE_STORE), TRUE);
5031             EnableWindow(GetDlgItem(hwnd, IDC_IMPORT_SPECIFY_STORE),
5032              !(data->dwFlags & CRYPTUI_WIZ_IMPORT_NO_CHANGE_DEST_STORE));
5033             LoadStringW(hInstance, IDS_IMPORT_DEST_DETERMINED,
5034              storeTitle, sizeof(storeTitle) / sizeof(storeTitle[0]));
5035             SendMessageW(GetDlgItem(hwnd, IDC_IMPORT_STORE), WM_SETTEXT,
5036              0, (LPARAM)storeTitle);
5037         }
5038         break;
5039     }
5040     case WM_NOTIFY:
5041     {
5042         NMHDR *hdr = (NMHDR *)lp;
5043
5044         switch (hdr->code)
5045         {
5046         case PSN_SETACTIVE:
5047             PostMessageW(GetParent(hwnd), PSM_SETWIZBUTTONS, 0,
5048              PSWIZB_BACK | PSWIZB_NEXT);
5049             ret = TRUE;
5050             break;
5051         case PSN_WIZNEXT:
5052         {
5053             data = (struct ImportWizData *)GetWindowLongPtrW(hwnd, DWLP_USER);
5054             if (IsDlgButtonChecked(hwnd, IDC_IMPORT_SPECIFY_STORE) &&
5055              !data->hDestCertStore)
5056             {
5057                 import_warning(data->dwFlags, hwnd, data->pwszWizardTitle,
5058                  IDS_IMPORT_SELECT_STORE);
5059                 SetWindowLongPtrW(hwnd, DWLP_MSGRESULT, 1);
5060                 ret = 1;
5061             }
5062             break;
5063         }
5064         }
5065         break;
5066     }
5067     case WM_COMMAND:
5068         switch (wp)
5069         {
5070         case IDC_IMPORT_AUTO_STORE:
5071             data = (struct ImportWizData *)GetWindowLongPtrW(hwnd, DWLP_USER);
5072             data->autoDest = TRUE;
5073             EnableWindow(GetDlgItem(hwnd, IDC_IMPORT_STORE), FALSE);
5074             EnableWindow(GetDlgItem(hwnd, IDC_IMPORT_BROWSE_STORE), FALSE);
5075             break;
5076         case IDC_IMPORT_SPECIFY_STORE:
5077             data = (struct ImportWizData *)GetWindowLongPtrW(hwnd, DWLP_USER);
5078             data->autoDest = FALSE;
5079             EnableWindow(GetDlgItem(hwnd, IDC_IMPORT_STORE), TRUE);
5080             EnableWindow(GetDlgItem(hwnd, IDC_IMPORT_BROWSE_STORE), TRUE);
5081             break;
5082         case IDC_IMPORT_BROWSE_STORE:
5083         {
5084             CRYPTUI_ENUM_SYSTEM_STORE_ARGS enumArgs = {
5085              CERT_SYSTEM_STORE_CURRENT_USER, NULL };
5086             CRYPTUI_ENUM_DATA enumData = { 0, NULL, 1, &enumArgs };
5087             CRYPTUI_SELECTSTORE_INFO_W selectInfo;
5088             HCERTSTORE store;
5089
5090             data = (struct ImportWizData *)GetWindowLongPtrW(hwnd, DWLP_USER);
5091             selectInfo.dwSize = sizeof(selectInfo);
5092             selectInfo.parent = hwnd;
5093             selectInfo.dwFlags = CRYPTUI_ENABLE_SHOW_PHYSICAL_STORE;
5094             selectInfo.pwszTitle = selectInfo.pwszTitle = NULL;
5095             selectInfo.pEnumData = &enumData;
5096             selectInfo.pfnSelectedStoreCallback = NULL;
5097             if ((store = CryptUIDlgSelectStoreW(&selectInfo)))
5098             {
5099                 WCHAR storeTitle[MAX_STRING_LEN];
5100
5101                 LoadStringW(hInstance, IDS_IMPORT_DEST_DETERMINED,
5102                  storeTitle, sizeof(storeTitle) / sizeof(storeTitle[0]));
5103                 SendMessageW(GetDlgItem(hwnd, IDC_IMPORT_STORE), WM_SETTEXT,
5104                  0, (LPARAM)storeTitle);
5105                 data->hDestCertStore = store;
5106                 data->freeDest = TRUE;
5107             }
5108             break;
5109         }
5110         }
5111         break;
5112     }
5113     return ret;
5114 }
5115
5116 static void show_import_details(HWND lv, struct ImportWizData *data)
5117 {
5118     WCHAR text[MAX_STRING_LEN];
5119     LVITEMW item;
5120     int contentID;
5121
5122     item.mask = LVIF_TEXT;
5123     item.iItem = SendMessageW(lv, LVM_GETITEMCOUNT, 0, 0);
5124     item.iSubItem = 0;
5125     LoadStringW(hInstance, IDS_IMPORT_STORE_SELECTION, text,
5126      sizeof(text)/ sizeof(text[0]));
5127     item.pszText = text;
5128     SendMessageW(lv, LVM_INSERTITEMW, 0, (LPARAM)&item);
5129     item.iSubItem = 1;
5130     if (data->autoDest)
5131         LoadStringW(hInstance, IDS_IMPORT_DEST_AUTOMATIC, text,
5132          sizeof(text)/ sizeof(text[0]));
5133     else
5134         LoadStringW(hInstance, IDS_IMPORT_DEST_DETERMINED, text,
5135          sizeof(text)/ sizeof(text[0]));
5136     SendMessageW(lv, LVM_SETITEMTEXTW, item.iItem, (LPARAM)&item);
5137     item.iItem = SendMessageW(lv, LVM_GETITEMCOUNT, 0, 0);
5138     item.iSubItem = 0;
5139     LoadStringW(hInstance, IDS_IMPORT_CONTENT, text,
5140      sizeof(text)/ sizeof(text[0]));
5141     SendMessageW(lv, LVM_INSERTITEMW, 0, (LPARAM)&item);
5142     switch (data->contentType)
5143     {
5144     case CERT_QUERY_CONTENT_CERT:
5145     case CERT_QUERY_CONTENT_SERIALIZED_CERT:
5146         contentID = IDS_IMPORT_CONTENT_CERT;
5147         break;
5148     case CERT_QUERY_CONTENT_CRL:
5149     case CERT_QUERY_CONTENT_SERIALIZED_CRL:
5150         contentID = IDS_IMPORT_CONTENT_CRL;
5151         break;
5152     case CERT_QUERY_CONTENT_CTL:
5153     case CERT_QUERY_CONTENT_SERIALIZED_CTL:
5154         contentID = IDS_IMPORT_CONTENT_CTL;
5155         break;
5156     case CERT_QUERY_CONTENT_PKCS7_SIGNED:
5157         contentID = IDS_IMPORT_CONTENT_CMS;
5158         break;
5159     case CERT_QUERY_CONTENT_FLAG_PFX:
5160         contentID = IDS_IMPORT_CONTENT_PFX;
5161         break;
5162     default:
5163         contentID = IDS_IMPORT_CONTENT_STORE;
5164         break;
5165     }
5166     LoadStringW(hInstance, contentID, text, sizeof(text)/ sizeof(text[0]));
5167     item.iSubItem = 1;
5168     SendMessageW(lv, LVM_SETITEMTEXTW, item.iItem, (LPARAM)&item);
5169     if (data->fileName)
5170     {
5171         item.iItem = SendMessageW(lv, LVM_GETITEMCOUNT, 0, 0);
5172         item.iSubItem = 0;
5173         LoadStringW(hInstance, IDS_IMPORT_FILE, text,
5174          sizeof(text)/ sizeof(text[0]));
5175         SendMessageW(lv, LVM_INSERTITEMW, 0, (LPARAM)&item);
5176         item.iSubItem = 1;
5177         item.pszText = data->fileName;
5178         SendMessageW(lv, LVM_SETITEMTEXTW, item.iItem, (LPARAM)&item);
5179     }
5180 }
5181
5182 static BOOL do_import(DWORD dwFlags, HWND hwndParent, LPCWSTR pwszWizardTitle,
5183  PCCRYPTUI_WIZ_IMPORT_SRC_INFO pImportSrc, HCERTSTORE hDestCertStore)
5184 {
5185     BOOL ret;
5186
5187     switch (pImportSrc->dwSubjectChoice)
5188     {
5189     case CRYPTUI_WIZ_IMPORT_SUBJECT_FILE:
5190         ret = import_file(dwFlags, hwndParent, pwszWizardTitle,
5191          pImportSrc->u.pwszFileName, hDestCertStore);
5192         break;
5193     case CRYPTUI_WIZ_IMPORT_SUBJECT_CERT_CONTEXT:
5194         if ((ret = check_context_type(dwFlags, CERT_QUERY_CONTENT_CERT)))
5195             ret = import_cert(pImportSrc->u.pCertContext, hDestCertStore);
5196         else
5197             import_warn_type_mismatch(dwFlags, hwndParent, pwszWizardTitle);
5198         break;
5199     case CRYPTUI_WIZ_IMPORT_SUBJECT_CRL_CONTEXT:
5200         if ((ret = check_context_type(dwFlags, CERT_QUERY_CONTENT_CRL)))
5201             ret = import_crl(pImportSrc->u.pCRLContext, hDestCertStore);
5202         else
5203             import_warn_type_mismatch(dwFlags, hwndParent, pwszWizardTitle);
5204         break;
5205     case CRYPTUI_WIZ_IMPORT_SUBJECT_CTL_CONTEXT:
5206         if ((ret = check_context_type(dwFlags, CERT_QUERY_CONTENT_CTL)))
5207             ret = import_ctl(pImportSrc->u.pCTLContext, hDestCertStore);
5208         else
5209             import_warn_type_mismatch(dwFlags, hwndParent, pwszWizardTitle);
5210         break;
5211     case CRYPTUI_WIZ_IMPORT_SUBJECT_CERT_STORE:
5212         ret = import_store(dwFlags, hwndParent, pwszWizardTitle,
5213          pImportSrc->u.hCertStore, hDestCertStore);
5214         break;
5215     default:
5216         WARN("unknown source type: %u\n", pImportSrc->dwSubjectChoice);
5217         SetLastError(E_INVALIDARG);
5218         ret = FALSE;
5219     }
5220     return ret;
5221 }
5222
5223 static LRESULT CALLBACK import_finish_dlg_proc(HWND hwnd, UINT msg, WPARAM wp,
5224  LPARAM lp)
5225 {
5226     LRESULT ret = 0;
5227     struct ImportWizData *data;
5228
5229     switch (msg)
5230     {
5231     case WM_INITDIALOG:
5232     {
5233         PROPSHEETPAGEW *page = (PROPSHEETPAGEW *)lp;
5234         HWND lv = GetDlgItem(hwnd, IDC_IMPORT_SETTINGS);
5235         RECT rc;
5236         LVCOLUMNW column;
5237
5238         data = (struct ImportWizData *)page->lParam;
5239         SetWindowLongPtrW(hwnd, DWLP_USER, (LPARAM)data);
5240         SendMessageW(GetDlgItem(hwnd, IDC_IMPORT_TITLE), WM_SETFONT,
5241          (WPARAM)data->titleFont, TRUE);
5242         GetWindowRect(lv, &rc);
5243         column.mask = LVCF_WIDTH;
5244         column.cx = (rc.right - rc.left) / 2 - 2;
5245         SendMessageW(lv, LVM_INSERTCOLUMNW, 0, (LPARAM)&column);
5246         SendMessageW(lv, LVM_INSERTCOLUMNW, 1, (LPARAM)&column);
5247         show_import_details(lv, data);
5248         break;
5249     }
5250     case WM_NOTIFY:
5251     {
5252         NMHDR *hdr = (NMHDR *)lp;
5253
5254         switch (hdr->code)
5255         {
5256         case PSN_SETACTIVE:
5257         {
5258             HWND lv = GetDlgItem(hwnd, IDC_IMPORT_SETTINGS);
5259
5260             data = (struct ImportWizData *)GetWindowLongPtrW(hwnd, DWLP_USER);
5261             SendMessageW(lv, LVM_DELETEALLITEMS, 0, 0);
5262             show_import_details(lv, data);
5263             PostMessageW(GetParent(hwnd), PSM_SETWIZBUTTONS, 0,
5264              PSWIZB_BACK | PSWIZB_FINISH);
5265             ret = TRUE;
5266             break;
5267         }
5268         case PSN_WIZFINISH:
5269         {
5270             data = (struct ImportWizData *)GetWindowLongPtrW(hwnd, DWLP_USER);
5271             if ((data->success = do_import(data->dwFlags, hwnd,
5272              data->pwszWizardTitle, &data->importSrc, data->hDestCertStore)))
5273             {
5274                 WCHAR title[MAX_STRING_LEN], message[MAX_STRING_LEN];
5275                 LPCWSTR pTitle;
5276
5277                 if (data->pwszWizardTitle)
5278                     pTitle = data->pwszWizardTitle;
5279                 else
5280                 {
5281                     LoadStringW(hInstance, IDS_IMPORT_WIZARD, title,
5282                      sizeof(title) / sizeof(title[0]));
5283                     pTitle = title;
5284                 }
5285                 LoadStringW(hInstance, IDS_IMPORT_SUCCEEDED, message,
5286                  sizeof(message) / sizeof(message[0]));
5287                 MessageBoxW(hwnd, message, pTitle, MB_OK);
5288             }
5289             else
5290                 import_warning(data->dwFlags, hwnd, data->pwszWizardTitle,
5291                  IDS_IMPORT_SUCCEEDED);
5292             break;
5293         }
5294         }
5295         break;
5296     }
5297     }
5298     return ret;
5299 }
5300
5301 static BOOL show_import_ui(DWORD dwFlags, HWND hwndParent,
5302  LPCWSTR pwszWizardTitle, PCCRYPTUI_WIZ_IMPORT_SRC_INFO pImportSrc,
5303  HCERTSTORE hDestCertStore)
5304 {
5305     PROPSHEETHEADERW hdr;
5306     PROPSHEETPAGEW pages[4];
5307     struct ImportWizData data;
5308     int nPages = 0;
5309
5310     data.dwFlags = dwFlags;
5311     data.pwszWizardTitle = pwszWizardTitle;
5312     if (pImportSrc)
5313         memcpy(&data.importSrc, pImportSrc, sizeof(data.importSrc));
5314     else
5315         memset(&data.importSrc, 0, sizeof(data.importSrc));
5316     data.fileName = NULL;
5317     data.freeSource = FALSE;
5318     data.hDestCertStore = hDestCertStore;
5319     data.freeDest = FALSE;
5320     data.autoDest = TRUE;
5321     data.success = TRUE;
5322
5323     memset(&pages, 0, sizeof(pages));
5324
5325     pages[nPages].dwSize = sizeof(pages[0]);
5326     pages[nPages].hInstance = hInstance;
5327     pages[nPages].u.pszTemplate = MAKEINTRESOURCEW(IDD_IMPORT_WELCOME);
5328     pages[nPages].pfnDlgProc = import_welcome_dlg_proc;
5329     pages[nPages].dwFlags = PSP_HIDEHEADER;
5330     pages[nPages].lParam = (LPARAM)&data;
5331     nPages++;
5332
5333     if (!pImportSrc ||
5334      pImportSrc->dwSubjectChoice == CRYPTUI_WIZ_IMPORT_SUBJECT_FILE)
5335     {
5336         pages[nPages].dwSize = sizeof(pages[0]);
5337         pages[nPages].hInstance = hInstance;
5338         pages[nPages].u.pszTemplate = MAKEINTRESOURCEW(IDD_IMPORT_FILE);
5339         pages[nPages].pfnDlgProc = import_file_dlg_proc;
5340         pages[nPages].dwFlags = PSP_USEHEADERTITLE | PSP_USEHEADERSUBTITLE;
5341         pages[nPages].pszHeaderTitle = MAKEINTRESOURCEW(IDS_IMPORT_FILE_TITLE);
5342         pages[nPages].pszHeaderSubTitle =
5343          MAKEINTRESOURCEW(IDS_IMPORT_FILE_SUBTITLE);
5344         pages[nPages].lParam = (LPARAM)&data;
5345         nPages++;
5346     }
5347     else
5348     {
5349         switch (pImportSrc->dwSubjectChoice)
5350         {
5351         case CRYPTUI_WIZ_IMPORT_SUBJECT_CERT_CONTEXT:
5352             data.contentType = CERT_QUERY_CONTENT_CERT;
5353             break;
5354         case CRYPTUI_WIZ_IMPORT_SUBJECT_CRL_CONTEXT:
5355             data.contentType = CERT_QUERY_CONTENT_CRL;
5356             break;
5357         case CRYPTUI_WIZ_IMPORT_SUBJECT_CTL_CONTEXT:
5358             data.contentType = CERT_QUERY_CONTENT_CTL;
5359             break;
5360         case CRYPTUI_WIZ_IMPORT_SUBJECT_CERT_STORE:
5361             data.contentType = CERT_QUERY_CONTENT_SERIALIZED_STORE;
5362             break;
5363         }
5364     }
5365
5366     pages[nPages].dwSize = sizeof(pages[0]);
5367     pages[nPages].hInstance = hInstance;
5368     pages[nPages].u.pszTemplate = MAKEINTRESOURCEW(IDD_IMPORT_STORE);
5369     pages[nPages].pfnDlgProc = import_store_dlg_proc;
5370     pages[nPages].dwFlags = PSP_USEHEADERTITLE | PSP_USEHEADERSUBTITLE;
5371     pages[nPages].pszHeaderTitle = MAKEINTRESOURCEW(IDS_IMPORT_STORE_TITLE);
5372     pages[nPages].pszHeaderSubTitle =
5373      MAKEINTRESOURCEW(IDS_IMPORT_STORE_SUBTITLE);
5374     pages[nPages].lParam = (LPARAM)&data;
5375     nPages++;
5376
5377     pages[nPages].dwSize = sizeof(pages[0]);
5378     pages[nPages].hInstance = hInstance;
5379     pages[nPages].u.pszTemplate = MAKEINTRESOURCEW(IDD_IMPORT_FINISH);
5380     pages[nPages].pfnDlgProc = import_finish_dlg_proc;
5381     pages[nPages].dwFlags = PSP_HIDEHEADER;
5382     pages[nPages].lParam = (LPARAM)&data;
5383     nPages++;
5384
5385     memset(&hdr, 0, sizeof(hdr));
5386     hdr.dwSize = sizeof(hdr);
5387     hdr.hwndParent = hwndParent;
5388     hdr.dwFlags = PSH_PROPSHEETPAGE | PSH_WIZARD97_NEW | PSH_HEADER |
5389      PSH_WATERMARK;
5390     hdr.hInstance = hInstance;
5391     if (pwszWizardTitle)
5392         hdr.pszCaption = pwszWizardTitle;
5393     else
5394         hdr.pszCaption = MAKEINTRESOURCEW(IDS_IMPORT_WIZARD);
5395     hdr.u3.ppsp = pages;
5396     hdr.nPages = nPages;
5397     hdr.u4.pszbmWatermark = MAKEINTRESOURCEW(IDB_CERT_WATERMARK);
5398     hdr.u5.pszbmHeader = MAKEINTRESOURCEW(IDB_CERT_HEADER);
5399     PropertySheetW(&hdr);
5400     HeapFree(GetProcessHeap(), 0, data.fileName);
5401     if (data.freeSource &&
5402      data.importSrc.dwSubjectChoice == CRYPTUI_WIZ_IMPORT_SUBJECT_CERT_STORE)
5403         CertCloseStore(data.importSrc.u.hCertStore, 0);
5404     DeleteObject(data.titleFont);
5405     return data.success;
5406 }
5407
5408 BOOL WINAPI CryptUIWizImport(DWORD dwFlags, HWND hwndParent, LPCWSTR pwszWizardTitle,
5409                              PCCRYPTUI_WIZ_IMPORT_SRC_INFO pImportSrc, HCERTSTORE hDestCertStore)
5410 {
5411     BOOL ret;
5412
5413     TRACE("(0x%08x, %p, %s, %p, %p)\n", dwFlags, hwndParent, debugstr_w(pwszWizardTitle),
5414           pImportSrc, hDestCertStore);
5415
5416     if (pImportSrc &&
5417      pImportSrc->dwSize != sizeof(CRYPTUI_WIZ_IMPORT_SRC_INFO))
5418     {
5419         SetLastError(E_INVALIDARG);
5420         return FALSE;
5421     }
5422
5423     if (!(dwFlags & CRYPTUI_WIZ_NO_UI))
5424         ret = show_import_ui(dwFlags, hwndParent, pwszWizardTitle, pImportSrc,
5425          hDestCertStore);
5426     else if (pImportSrc)
5427         ret = do_import(dwFlags, hwndParent, pwszWizardTitle, pImportSrc,
5428          hDestCertStore);
5429     else
5430     {
5431         /* Can't have no UI without specifying source */
5432         SetLastError(E_INVALIDARG);
5433         ret = FALSE;
5434     }
5435
5436     return ret;
5437 }
5438
5439 struct ExportWizData
5440 {
5441     HFONT titleFont;
5442     DWORD dwFlags;
5443     LPCWSTR pwszWizardTitle;
5444     PCCRYPTUI_WIZ_EXPORT_INFO pExportInfo;
5445     void *pvoid;
5446     DWORD exportFormat;
5447     BOOL includeChain;
5448     BOOL strongEncryption;
5449     BOOL deletePrivateKey;
5450 };
5451
5452 static LRESULT CALLBACK export_welcome_dlg_proc(HWND hwnd, UINT msg, WPARAM wp,
5453  LPARAM lp)
5454 {
5455     LRESULT ret = 0;
5456
5457     switch (msg)
5458     {
5459     case WM_INITDIALOG:
5460     {
5461         struct ExportWizData *data;
5462         PROPSHEETPAGEW *page = (PROPSHEETPAGEW *)lp;
5463         WCHAR fontFace[MAX_STRING_LEN];
5464         HDC hDC = GetDC(hwnd);
5465         int height;
5466
5467         data = (struct ExportWizData *)page->lParam;
5468         LoadStringW(hInstance, IDS_WIZARD_TITLE_FONT, fontFace,
5469          sizeof(fontFace) / sizeof(fontFace[0]));
5470         height = -MulDiv(12, GetDeviceCaps(hDC, LOGPIXELSY), 72);
5471         data->titleFont = CreateFontW(height, 0, 0, 0, FW_BOLD, 0, 0, 0,
5472          DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS,
5473          DEFAULT_QUALITY, DEFAULT_PITCH | FF_DONTCARE, fontFace);
5474         SendMessageW(GetDlgItem(hwnd, IDC_EXPORT_TITLE), WM_SETFONT,
5475          (WPARAM)data->titleFont, TRUE);
5476         ReleaseDC(hwnd, hDC);
5477         break;
5478     }
5479     case WM_NOTIFY:
5480     {
5481         NMHDR *hdr = (NMHDR *)lp;
5482
5483         switch (hdr->code)
5484         {
5485         case PSN_SETACTIVE:
5486             PostMessageW(GetParent(hwnd), PSM_SETWIZBUTTONS, 0, PSWIZB_NEXT);
5487             ret = TRUE;
5488             break;
5489         }
5490         break;
5491     }
5492     }
5493     return ret;
5494 }
5495
5496 static LRESULT CALLBACK export_format_dlg_proc(HWND hwnd, UINT msg, WPARAM wp,
5497  LPARAM lp)
5498 {
5499     LRESULT ret = 0;
5500     struct ExportWizData *data;
5501
5502     switch (msg)
5503     {
5504     case WM_INITDIALOG:
5505     {
5506         PROPSHEETPAGEW *page = (PROPSHEETPAGEW *)lp;
5507
5508         data = (struct ExportWizData *)page->lParam;
5509         SetWindowLongPtrW(hwnd, DWLP_USER, (LPARAM)data);
5510         SendMessageW(GetDlgItem(hwnd, IDC_EXPORT_FORMAT_DER), BM_CLICK, 0, 0);
5511         break;
5512     }
5513     case WM_NOTIFY:
5514     {
5515         NMHDR *hdr = (NMHDR *)lp;
5516
5517         switch (hdr->code)
5518         {
5519         case PSN_SETACTIVE:
5520             PostMessageW(GetParent(hwnd), PSM_SETWIZBUTTONS, 0,
5521              PSWIZB_BACK | PSWIZB_NEXT);
5522             ret = TRUE;
5523             break;
5524         case PSN_WIZNEXT:
5525         {
5526             data = (struct ExportWizData *)GetWindowLongPtrW(hwnd, DWLP_USER);
5527             if (IsDlgButtonChecked(hwnd, IDC_EXPORT_FORMAT_DER))
5528                 data->exportFormat = CRYPTUI_WIZ_EXPORT_FORMAT_DER;
5529             else if (IsDlgButtonChecked(hwnd, IDC_EXPORT_FORMAT_BASE64))
5530                 data->exportFormat = CRYPTUI_WIZ_EXPORT_FORMAT_BASE64;
5531             else if (IsDlgButtonChecked(hwnd, IDC_EXPORT_FORMAT_CMS))
5532             {
5533                 data->exportFormat = CRYPTUI_WIZ_EXPORT_FORMAT_PKCS7;
5534                 if (IsDlgButtonChecked(hwnd, IDC_EXPORT_CMS_INCLUDE_CHAIN))
5535                     data->includeChain = TRUE;
5536             }
5537             else
5538             {
5539                 data->exportFormat = CRYPTUI_WIZ_EXPORT_FORMAT_PFX;
5540                 if (IsDlgButtonChecked(hwnd, IDC_EXPORT_PFX_INCLUDE_CHAIN))
5541                     data->includeChain = TRUE;
5542                 if (IsDlgButtonChecked(hwnd, IDC_EXPORT_PFX_STRONG_ENCRYPTION))
5543                     data->strongEncryption = TRUE;
5544                 if (IsDlgButtonChecked(hwnd, IDC_EXPORT_PFX_DELETE_PRIVATE_KEY))
5545                     data->deletePrivateKey = TRUE;
5546             }
5547             break;
5548         }
5549         }
5550         break;
5551     }
5552     }
5553     return ret;
5554 }
5555
5556 static LRESULT CALLBACK export_file_dlg_proc(HWND hwnd, UINT msg, WPARAM wp,
5557  LPARAM lp)
5558 {
5559     LRESULT ret = 0;
5560     struct ExportWizData *data;
5561
5562     switch (msg)
5563     {
5564     case WM_INITDIALOG:
5565     {
5566         PROPSHEETPAGEW *page = (PROPSHEETPAGEW *)lp;
5567
5568         data = (struct ExportWizData *)page->lParam;
5569         SetWindowLongPtrW(hwnd, DWLP_USER, (LPARAM)data);
5570         if (data->pExportInfo->dwSubjectChoice ==
5571          CRYPTUI_WIZ_EXPORT_CERT_CONTEXT)
5572         {
5573             DWORD size;
5574
5575             /* If there's a CRYPT_KEY_PROV_INFO set for this cert, assume the
5576              * cert has a private key.
5577              */
5578             if (CertGetCertificateContextProperty(
5579              data->pExportInfo->u.pCertContext, CERT_KEY_PROV_INFO_PROP_ID,
5580              NULL, &size))
5581                 EnableWindow(GetDlgItem(hwnd, IDC_EXPORT_FORMAT_PFX), TRUE);
5582         }
5583         break;
5584     }
5585     case WM_NOTIFY:
5586     {
5587         NMHDR *hdr = (NMHDR *)lp;
5588
5589         switch (hdr->code)
5590         {
5591         case PSN_SETACTIVE:
5592             PostMessageW(GetParent(hwnd), PSM_SETWIZBUTTONS, 0,
5593              PSWIZB_BACK | PSWIZB_NEXT);
5594             ret = TRUE;
5595             break;
5596         }
5597         break;
5598     }
5599     }
5600     return ret;
5601 }
5602
5603 static LRESULT CALLBACK export_finish_dlg_proc(HWND hwnd, UINT msg, WPARAM wp,
5604  LPARAM lp)
5605 {
5606     LRESULT ret = 0;
5607     struct ExportWizData *data;
5608
5609     switch (msg)
5610     {
5611     case WM_INITDIALOG:
5612     {
5613         PROPSHEETPAGEW *page = (PROPSHEETPAGEW *)lp;
5614         HWND lv = GetDlgItem(hwnd, IDC_EXPORT_SETTINGS);
5615         RECT rc;
5616         LVCOLUMNW column;
5617
5618         data = (struct ExportWizData *)page->lParam;
5619         SetWindowLongPtrW(hwnd, DWLP_USER, (LPARAM)data);
5620         SendMessageW(GetDlgItem(hwnd, IDC_EXPORT_TITLE), WM_SETFONT,
5621          (WPARAM)data->titleFont, TRUE);
5622         GetWindowRect(lv, &rc);
5623         column.mask = LVCF_WIDTH;
5624         column.cx = (rc.right - rc.left) / 2 - 2;
5625         SendMessageW(lv, LVM_INSERTCOLUMNW, 0, (LPARAM)&column);
5626         SendMessageW(lv, LVM_INSERTCOLUMNW, 1, (LPARAM)&column);
5627         break;
5628     }
5629     case WM_NOTIFY:
5630     {
5631         NMHDR *hdr = (NMHDR *)lp;
5632
5633         switch (hdr->code)
5634         {
5635         case PSN_SETACTIVE:
5636         {
5637             HWND lv = GetDlgItem(hwnd, IDC_EXPORT_SETTINGS);
5638
5639             data = (struct ExportWizData *)GetWindowLongPtrW(hwnd, DWLP_USER);
5640             SendMessageW(lv, LVM_DELETEALLITEMS, 0, 0);
5641             PostMessageW(GetParent(hwnd), PSM_SETWIZBUTTONS, 0,
5642              PSWIZB_BACK | PSWIZB_FINISH);
5643             ret = TRUE;
5644             break;
5645         }
5646         }
5647         break;
5648     }
5649     }
5650     return ret;
5651 }
5652
5653 static BOOL show_export_ui(DWORD dwFlags, HWND hwndParent,
5654  LPCWSTR pwszWizardTitle, PCCRYPTUI_WIZ_EXPORT_INFO pExportInfo, void *pvoid)
5655 {
5656     PROPSHEETHEADERW hdr;
5657     PROPSHEETPAGEW pages[4];
5658     struct ExportWizData data;
5659     int nPages = 0;
5660     BOOL showFormatPage = TRUE;
5661
5662     data.dwFlags = dwFlags;
5663     data.pwszWizardTitle = pwszWizardTitle;
5664     data.pExportInfo = pExportInfo;
5665     data.pvoid = pvoid;
5666     data.exportFormat = 0;
5667     data.includeChain = FALSE;
5668     data.strongEncryption = FALSE;
5669     data.deletePrivateKey = FALSE;
5670
5671     memset(&pages, 0, sizeof(pages));
5672
5673     pages[nPages].dwSize = sizeof(pages[0]);
5674     pages[nPages].hInstance = hInstance;
5675     pages[nPages].u.pszTemplate = MAKEINTRESOURCEW(IDD_EXPORT_WELCOME);
5676     pages[nPages].pfnDlgProc = export_welcome_dlg_proc;
5677     pages[nPages].dwFlags = PSP_HIDEHEADER;
5678     pages[nPages].lParam = (LPARAM)&data;
5679     nPages++;
5680
5681     switch (pExportInfo->dwSubjectChoice)
5682     {
5683     case CRYPTUI_WIZ_EXPORT_CRL_CONTEXT:
5684     case CRYPTUI_WIZ_EXPORT_CTL_CONTEXT:
5685         showFormatPage = FALSE;
5686         data.exportFormat = CRYPTUI_WIZ_EXPORT_FORMAT_DER;
5687         break;
5688     case CRYPTUI_WIZ_EXPORT_CERT_STORE:
5689         showFormatPage = FALSE;
5690         data.exportFormat = CRYPTUI_WIZ_EXPORT_FORMAT_SERIALIZED_CERT_STORE;
5691         break;
5692     case CRYPTUI_WIZ_EXPORT_CERT_STORE_CERTIFICATES_ONLY:
5693         showFormatPage = FALSE;
5694         data.exportFormat = CRYPTUI_WIZ_EXPORT_FORMAT_PKCS7;
5695         break;
5696     }
5697     if (showFormatPage)
5698     {
5699         pages[nPages].dwSize = sizeof(pages[0]);
5700         pages[nPages].hInstance = hInstance;
5701         pages[nPages].u.pszTemplate = MAKEINTRESOURCEW(IDD_EXPORT_FORMAT);
5702         pages[nPages].pfnDlgProc = export_format_dlg_proc;
5703         pages[nPages].dwFlags = PSP_USEHEADERTITLE | PSP_USEHEADERSUBTITLE;
5704         pages[nPages].pszHeaderTitle =
5705          MAKEINTRESOURCEW(IDS_EXPORT_FORMAT_TITLE);
5706         pages[nPages].pszHeaderSubTitle =
5707          MAKEINTRESOURCEW(IDS_EXPORT_FORMAT_SUBTITLE);
5708         pages[nPages].lParam = (LPARAM)&data;
5709         nPages++;
5710     }
5711
5712     pages[nPages].dwSize = sizeof(pages[0]);
5713     pages[nPages].hInstance = hInstance;
5714     pages[nPages].u.pszTemplate = MAKEINTRESOURCEW(IDD_EXPORT_FILE);
5715     pages[nPages].pfnDlgProc = export_file_dlg_proc;
5716     pages[nPages].dwFlags = PSP_USEHEADERTITLE | PSP_USEHEADERSUBTITLE;
5717     pages[nPages].pszHeaderTitle = MAKEINTRESOURCEW(IDS_EXPORT_FILE_TITLE);
5718     pages[nPages].pszHeaderSubTitle =
5719      MAKEINTRESOURCEW(IDS_EXPORT_FILE_SUBTITLE);
5720     pages[nPages].lParam = (LPARAM)&data;
5721     nPages++;
5722
5723     pages[nPages].dwSize = sizeof(pages[0]);
5724     pages[nPages].hInstance = hInstance;
5725     pages[nPages].u.pszTemplate = MAKEINTRESOURCEW(IDD_EXPORT_FINISH);
5726     pages[nPages].pfnDlgProc = export_finish_dlg_proc;
5727     pages[nPages].dwFlags = PSP_HIDEHEADER;
5728     pages[nPages].lParam = (LPARAM)&data;
5729     nPages++;
5730
5731     memset(&hdr, 0, sizeof(hdr));
5732     hdr.dwSize = sizeof(hdr);
5733     hdr.hwndParent = hwndParent;
5734     hdr.dwFlags = PSH_PROPSHEETPAGE | PSH_WIZARD97_NEW | PSH_HEADER |
5735      PSH_WATERMARK;
5736     hdr.hInstance = hInstance;
5737     if (pwszWizardTitle)
5738         hdr.pszCaption = pwszWizardTitle;
5739     else
5740         hdr.pszCaption = MAKEINTRESOURCEW(IDS_EXPORT_WIZARD);
5741     hdr.u3.ppsp = pages;
5742     hdr.nPages = nPages;
5743     hdr.u4.pszbmWatermark = MAKEINTRESOURCEW(IDB_CERT_WATERMARK);
5744     hdr.u5.pszbmHeader = MAKEINTRESOURCEW(IDB_CERT_HEADER);
5745     PropertySheetW(&hdr);
5746     DeleteObject(data.titleFont);
5747     return FALSE;
5748 }
5749
5750 BOOL WINAPI CryptUIWizExport(DWORD dwFlags, HWND hwndParent,
5751  LPCWSTR pwszWizardTitle, PCCRYPTUI_WIZ_EXPORT_INFO pExportInfo, void *pvoid)
5752 {
5753     BOOL ret;
5754
5755     TRACE("(%08x, %p, %s, %p, %p)\n", dwFlags, hwndParent,
5756      debugstr_w(pwszWizardTitle), pExportInfo, pvoid);
5757
5758     if (!(dwFlags & CRYPTUI_WIZ_NO_UI))
5759         ret = show_export_ui(dwFlags, hwndParent, pwszWizardTitle, pExportInfo,
5760          pvoid);
5761     else
5762     {
5763         FIXME("stub\n");
5764         ret = FALSE;
5765     }
5766     return ret;
5767 }