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