jscript: Add index, input and lastIndex properties to regexp functions results.
[wine] / dlls / crypt32 / str.c
1 /*
2  * Copyright 2006 Juan Lang for CodeWeavers
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 #include <stdarg.h>
19
20 #define NONAMELESSUNION
21
22 #include "windef.h"
23 #include "winbase.h"
24 #include "winnls.h"
25 #include "winuser.h"
26 #include "wincrypt.h"
27 #include "wine/debug.h"
28 #include "wine/unicode.h"
29
30 WINE_DEFAULT_DEBUG_CHANNEL(crypt);
31
32 static inline BOOL is_quotable_char(char c)
33 {
34     switch(c)
35     {
36     case '+':
37     case ',':
38     case '"':
39     case '=':
40     case '<':
41     case '>':
42     case ';':
43     case '#':
44         return TRUE;
45     default:
46         return FALSE;
47     }
48 }
49
50 DWORD WINAPI CertRDNValueToStrA(DWORD dwValueType, PCERT_RDN_VALUE_BLOB pValue,
51  LPSTR psz, DWORD csz)
52 {
53     DWORD ret = 0, len, i;
54     BOOL needsQuotes = FALSE;
55
56     TRACE("(%d, %p, %p, %d)\n", dwValueType, pValue, psz, csz);
57
58     switch (dwValueType)
59     {
60     case CERT_RDN_ANY_TYPE:
61         break;
62     case CERT_RDN_NUMERIC_STRING:
63     case CERT_RDN_PRINTABLE_STRING:
64     case CERT_RDN_TELETEX_STRING:
65     case CERT_RDN_VIDEOTEX_STRING:
66     case CERT_RDN_IA5_STRING:
67     case CERT_RDN_GRAPHIC_STRING:
68     case CERT_RDN_VISIBLE_STRING:
69     case CERT_RDN_GENERAL_STRING:
70         len = pValue->cbData;
71         if (pValue->cbData && isspace(pValue->pbData[0]))
72             needsQuotes = TRUE;
73         if (pValue->cbData && isspace(pValue->pbData[pValue->cbData - 1]))
74             needsQuotes = TRUE;
75         for (i = 0; i < pValue->cbData; i++)
76         {
77             if (is_quotable_char(pValue->pbData[i]))
78                 needsQuotes = TRUE;
79             if (pValue->pbData[i] == '"')
80                 len += 1;
81         }
82         if (needsQuotes)
83             len += 2;
84         if (!psz || !csz)
85             ret = len;
86         else
87         {
88             char *ptr = psz;
89
90             if (needsQuotes)
91                 *ptr++ = '"';
92             for (i = 0; i < pValue->cbData && ptr - psz < csz; ptr++, i++)
93             {
94                 *ptr = pValue->pbData[i];
95                 if (pValue->pbData[i] == '"' && ptr - psz < csz - 1)
96                     *(++ptr) = '"';
97             }
98             if (needsQuotes && ptr - psz < csz)
99                 *ptr++ = '"';
100             ret = ptr - psz;
101         }
102         break;
103     case CERT_RDN_BMP_STRING:
104         len = WideCharToMultiByte(CP_ACP, 0, (LPCWSTR)pValue->pbData,
105          pValue->cbData / sizeof(WCHAR), NULL, 0, NULL, NULL);
106         if (pValue->cbData && isspaceW(((LPCWSTR)pValue->pbData)[0]))
107             needsQuotes = TRUE;
108         if (pValue->cbData &&
109          isspaceW(((LPCWSTR)pValue->pbData)[pValue->cbData / sizeof(WCHAR)-1]))
110             needsQuotes = TRUE;
111         for (i = 0; i < pValue->cbData / sizeof(WCHAR); i++)
112         {
113             if (is_quotable_char(((LPCWSTR)pValue->pbData)[i]))
114                 needsQuotes = TRUE;
115             if (((LPCWSTR)pValue->pbData)[i] == '"')
116                 len += 1;
117         }
118         if (needsQuotes)
119             len += 2;
120         if (!psz || !csz)
121             ret = len;
122         else
123         {
124             char *dst = psz;
125
126             if (needsQuotes)
127                 *dst++ = '"';
128             for (i = 0; i < pValue->cbData / sizeof(WCHAR) &&
129              dst - psz < csz; dst++, i++)
130             {
131                 LPCWSTR src = (LPCWSTR)pValue->pbData + i;
132
133                 WideCharToMultiByte(CP_ACP, 0, src, 1, dst,
134                  csz - (dst - psz) - 1, NULL, NULL);
135                 if (*src == '"' && dst - psz < csz - 1)
136                     *(++dst) = '"';
137             }
138             if (needsQuotes && dst - psz < csz)
139                 *dst++ = '"';
140             ret = dst - psz;
141         }
142         break;
143     default:
144         FIXME("string type %d unimplemented\n", dwValueType);
145     }
146     if (psz && csz)
147     {
148         *(psz + ret) = '\0';
149         csz--;
150         ret++;
151     }
152     else
153         ret++;
154     TRACE("returning %d (%s)\n", ret, debugstr_a(psz));
155     return ret;
156 }
157
158 DWORD WINAPI CertRDNValueToStrW(DWORD dwValueType, PCERT_RDN_VALUE_BLOB pValue,
159  LPWSTR psz, DWORD csz)
160 {
161     DWORD ret = 0, len, i;
162     BOOL needsQuotes = FALSE;
163
164     TRACE("(%d, %p, %p, %d)\n", dwValueType, pValue, psz, csz);
165
166     switch (dwValueType)
167     {
168     case CERT_RDN_ANY_TYPE:
169         break;
170     case CERT_RDN_NUMERIC_STRING:
171     case CERT_RDN_PRINTABLE_STRING:
172     case CERT_RDN_TELETEX_STRING:
173     case CERT_RDN_VIDEOTEX_STRING:
174     case CERT_RDN_IA5_STRING:
175     case CERT_RDN_GRAPHIC_STRING:
176     case CERT_RDN_VISIBLE_STRING:
177     case CERT_RDN_GENERAL_STRING:
178     case CERT_RDN_BMP_STRING:
179         len = pValue->cbData;
180         if (pValue->cbData && isspace(pValue->pbData[0]))
181             needsQuotes = TRUE;
182         if (pValue->cbData && isspace(pValue->pbData[pValue->cbData - 1]))
183             needsQuotes = TRUE;
184         for (i = 0; i < pValue->cbData; i++)
185         {
186             if (is_quotable_char(pValue->pbData[i]))
187                 needsQuotes = TRUE;
188             if (pValue->pbData[i] == '"')
189                 len += 1;
190         }
191         if (needsQuotes)
192             len += 2;
193         if (!psz || !csz)
194             ret = len;
195         else
196         {
197             WCHAR *ptr = psz;
198
199             if (needsQuotes)
200                 *ptr++ = '"';
201             for (i = 0; i < pValue->cbData && ptr - psz < csz; ptr++, i++)
202             {
203                 *ptr = pValue->pbData[i];
204                 if (pValue->pbData[i] == '"' && ptr - psz < csz - 1)
205                     *(++ptr) = '"';
206             }
207             if (needsQuotes && ptr - psz < csz)
208                 *ptr++ = '"';
209             ret = ptr - psz;
210         }
211         break;
212     default:
213         FIXME("string type %d unimplemented\n", dwValueType);
214     }
215     if (psz && csz)
216     {
217         *(psz + ret) = '\0';
218         csz--;
219         ret++;
220     }
221     else
222         ret++;
223     TRACE("returning %d (%s)\n", ret, debugstr_w(psz));
224     return ret;
225 }
226
227 /* Adds the prefix prefix to the string pointed to by psz, followed by the
228  * character '='.  Copies no more than csz characters.  Returns the number of
229  * characters copied.  If psz is NULL, returns the number of characters that
230  * would be copied.
231  */
232 static DWORD CRYPT_AddPrefixA(LPCSTR prefix, LPSTR psz, DWORD csz)
233 {
234     DWORD chars;
235
236     TRACE("(%s, %p, %d)\n", debugstr_a(prefix), psz, csz);
237
238     if (psz)
239     {
240         chars = min(strlen(prefix), csz);
241         memcpy(psz, prefix, chars);
242         *(psz + chars) = '=';
243         chars++;
244     }
245     else
246         chars = lstrlenA(prefix) + 1;
247     return chars;
248 }
249
250 DWORD WINAPI CertNameToStrA(DWORD dwCertEncodingType, PCERT_NAME_BLOB pName,
251  DWORD dwStrType, LPSTR psz, DWORD csz)
252 {
253     static const DWORD unsupportedFlags = CERT_NAME_STR_NO_QUOTING_FLAG |
254      CERT_NAME_STR_ENABLE_T61_UNICODE_FLAG;
255     static const char commaSep[] = ", ";
256     static const char semiSep[] = "; ";
257     static const char crlfSep[] = "\r\n";
258     static const char plusSep[] = " + ";
259     static const char spaceSep[] = " ";
260     DWORD ret = 0, bytes = 0;
261     BOOL bRet;
262     CERT_NAME_INFO *info;
263
264     TRACE("(%d, %p, %08x, %p, %d)\n", dwCertEncodingType, pName, dwStrType,
265      psz, csz);
266     if (dwStrType & unsupportedFlags)
267         FIXME("unsupported flags: %08x\n", dwStrType & unsupportedFlags);
268
269     bRet = CryptDecodeObjectEx(dwCertEncodingType, X509_NAME, pName->pbData,
270      pName->cbData, CRYPT_DECODE_ALLOC_FLAG, NULL, &info, &bytes);
271     if (bRet)
272     {
273         DWORD i, j, sepLen, rdnSepLen;
274         LPCSTR sep, rdnSep;
275         BOOL reverse = dwStrType & CERT_NAME_STR_REVERSE_FLAG;
276         const CERT_RDN *rdn = info->rgRDN;
277
278         if(reverse && info->cRDN > 1) rdn += (info->cRDN - 1);
279
280         if (dwStrType & CERT_NAME_STR_SEMICOLON_FLAG)
281             sep = semiSep;
282         else if (dwStrType & CERT_NAME_STR_CRLF_FLAG)
283             sep = crlfSep;
284         else
285             sep = commaSep;
286         sepLen = strlen(sep);
287         if (dwStrType & CERT_NAME_STR_NO_PLUS_FLAG)
288             rdnSep = spaceSep;
289         else
290             rdnSep = plusSep;
291         rdnSepLen = strlen(rdnSep);
292         for (i = 0; (!psz || ret < csz) && i < info->cRDN; i++)
293         {
294             for (j = 0; (!psz || ret < csz) && j < rdn->cRDNAttr; j++)
295             {
296                 DWORD chars;
297                 char prefixBuf[10]; /* big enough for GivenName */
298                 LPCSTR prefix = NULL;
299
300                 if ((dwStrType & 0x000000ff) == CERT_OID_NAME_STR)
301                     prefix = rdn->rgRDNAttr[j].pszObjId;
302                 else if ((dwStrType & 0x000000ff) == CERT_X500_NAME_STR)
303                 {
304                     PCCRYPT_OID_INFO oidInfo = CryptFindOIDInfo(
305                      CRYPT_OID_INFO_OID_KEY,
306                      rdn->rgRDNAttr[j].pszObjId,
307                      CRYPT_RDN_ATTR_OID_GROUP_ID);
308
309                     if (oidInfo)
310                     {
311                         WideCharToMultiByte(CP_ACP, 0, oidInfo->pwszName, -1,
312                          prefixBuf, sizeof(prefixBuf), NULL, NULL);
313                         prefix = prefixBuf;
314                     }
315                     else
316                         prefix = rdn->rgRDNAttr[j].pszObjId;
317                 }
318                 if (prefix)
319                 {
320                     /* - 1 is needed to account for the NULL terminator. */
321                     chars = CRYPT_AddPrefixA(prefix,
322                      psz ? psz + ret : NULL, psz ? csz - ret - 1 : 0);
323                     ret += chars;
324                 }
325                 /* FIXME: handle quoting */
326                 chars = CertRDNValueToStrA(
327                  rdn->rgRDNAttr[j].dwValueType,
328                  &rdn->rgRDNAttr[j].Value, psz ? psz + ret : NULL,
329                  psz ? csz - ret : 0);
330                 if (chars)
331                     ret += chars - 1;
332                 if (j < rdn->cRDNAttr - 1)
333                 {
334                     if (psz && ret < csz - rdnSepLen - 1)
335                         memcpy(psz + ret, rdnSep, rdnSepLen);
336                     ret += rdnSepLen;
337                 }
338             }
339             if (i < info->cRDN - 1)
340             {
341                 if (psz && ret < csz - sepLen - 1)
342                     memcpy(psz + ret, sep, sepLen);
343                 ret += sepLen;
344             }
345             if(reverse) rdn--;
346             else rdn++;
347         }
348         LocalFree(info);
349     }
350     if (psz && csz)
351     {
352         *(psz + ret) = '\0';
353         ret++;
354     }
355     else
356         ret++;
357     TRACE("Returning %s\n", debugstr_a(psz));
358     return ret;
359 }
360
361 /* Adds the prefix prefix to the wide-character string pointed to by psz,
362  * followed by the character '='.  Copies no more than csz characters.  Returns
363  * the number of characters copied.  If psz is NULL, returns the number of
364  * characters that would be copied.
365  * Assumes the characters in prefix are ASCII (not multibyte characters.)
366  */
367 static DWORD CRYPT_AddPrefixAToW(LPCSTR prefix, LPWSTR psz, DWORD csz)
368 {
369     DWORD chars;
370
371     TRACE("(%s, %p, %d)\n", debugstr_a(prefix), psz, csz);
372
373     if (psz)
374     {
375         DWORD i;
376
377         chars = min(strlen(prefix), csz);
378         for (i = 0; i < chars; i++)
379             *(psz + i) = prefix[i];
380         *(psz + chars) = '=';
381         chars++;
382     }
383     else
384         chars = lstrlenA(prefix) + 1;
385     return chars;
386 }
387
388 /* Adds the prefix prefix to the string pointed to by psz, followed by the
389  * character '='.  Copies no more than csz characters.  Returns the number of
390  * characters copied.  If psz is NULL, returns the number of characters that
391  * would be copied.
392  */
393 static DWORD CRYPT_AddPrefixW(LPCWSTR prefix, LPWSTR psz, DWORD csz)
394 {
395     DWORD chars;
396
397     TRACE("(%s, %p, %d)\n", debugstr_w(prefix), psz, csz);
398
399     if (psz)
400     {
401         chars = min(strlenW(prefix), csz);
402         memcpy(psz, prefix, chars * sizeof(WCHAR));
403         *(psz + chars) = '=';
404         chars++;
405     }
406     else
407         chars = lstrlenW(prefix) + 1;
408     return chars;
409 }
410
411 static const WCHAR indent[] = { ' ',' ',' ',' ',' ',0 };
412
413 DWORD cert_name_to_str_with_indent(DWORD dwCertEncodingType, DWORD indentLevel,
414  const CERT_NAME_BLOB *pName, DWORD dwStrType, LPWSTR psz, DWORD csz)
415 {
416     static const DWORD unsupportedFlags = CERT_NAME_STR_NO_QUOTING_FLAG |
417      CERT_NAME_STR_ENABLE_T61_UNICODE_FLAG;
418     static const WCHAR commaSep[] = { ',',' ',0 };
419     static const WCHAR semiSep[] = { ';',' ',0 };
420     static const WCHAR crlfSep[] = { '\r','\n',0 };
421     static const WCHAR plusSep[] = { ' ','+',' ',0 };
422     static const WCHAR spaceSep[] = { ' ',0 };
423     DWORD ret = 0, bytes = 0;
424     BOOL bRet;
425     CERT_NAME_INFO *info;
426
427     if (dwStrType & unsupportedFlags)
428         FIXME("unsupported flags: %08x\n", dwStrType & unsupportedFlags);
429
430     bRet = CryptDecodeObjectEx(dwCertEncodingType, X509_NAME, pName->pbData,
431      pName->cbData, CRYPT_DECODE_ALLOC_FLAG, NULL, &info, &bytes);
432     if (bRet)
433     {
434         DWORD i, j, sepLen, rdnSepLen;
435         LPCWSTR sep, rdnSep;
436         BOOL reverse = dwStrType & CERT_NAME_STR_REVERSE_FLAG;
437         const CERT_RDN *rdn = info->rgRDN;
438
439         if(reverse && info->cRDN > 1) rdn += (info->cRDN - 1);
440
441         if (dwStrType & CERT_NAME_STR_SEMICOLON_FLAG)
442             sep = semiSep;
443         else if (dwStrType & CERT_NAME_STR_CRLF_FLAG)
444             sep = crlfSep;
445         else
446             sep = commaSep;
447         sepLen = lstrlenW(sep);
448         if (dwStrType & CERT_NAME_STR_NO_PLUS_FLAG)
449             rdnSep = spaceSep;
450         else
451             rdnSep = plusSep;
452         rdnSepLen = lstrlenW(rdnSep);
453         for (i = 0; (!psz || ret < csz) && i < info->cRDN; i++)
454         {
455             for (j = 0; (!psz || ret < csz) && j < rdn->cRDNAttr; j++)
456             {
457                 DWORD chars;
458                 LPCSTR prefixA = NULL;
459                 LPCWSTR prefixW = NULL;
460
461                 if ((dwStrType & 0x000000ff) == CERT_OID_NAME_STR)
462                     prefixA = rdn->rgRDNAttr[j].pszObjId;
463                 else if ((dwStrType & 0x000000ff) == CERT_X500_NAME_STR)
464                 {
465                     PCCRYPT_OID_INFO oidInfo = CryptFindOIDInfo(
466                      CRYPT_OID_INFO_OID_KEY,
467                      rdn->rgRDNAttr[j].pszObjId,
468                      CRYPT_RDN_ATTR_OID_GROUP_ID);
469
470                     if (oidInfo)
471                         prefixW = oidInfo->pwszName;
472                     else
473                         prefixA = rdn->rgRDNAttr[j].pszObjId;
474                 }
475                 if (dwStrType & CERT_NAME_STR_CRLF_FLAG)
476                 {
477                     DWORD k;
478
479                     for (k = 0; k < indentLevel; k++)
480                     {
481                         if (psz)
482                         {
483                             chars = min(strlenW(indent), csz - ret - 1);
484                             memcpy(psz + ret, indent, chars * sizeof(WCHAR));
485                         }
486                         else
487                             chars = strlenW(indent);
488                         ret += chars;
489                     }
490                 }
491                 if (prefixW)
492                 {
493                     /* - 1 is needed to account for the NULL terminator. */
494                     chars = CRYPT_AddPrefixW(prefixW,
495                      psz ? psz + ret : NULL, psz ? csz - ret - 1 : 0);
496                     ret += chars;
497                 }
498                 else if (prefixA)
499                 {
500                     /* - 1 is needed to account for the NULL terminator. */
501                     chars = CRYPT_AddPrefixAToW(prefixA,
502                      psz ? psz + ret : NULL, psz ? csz - ret - 1 : 0);
503                     ret += chars;
504                 }
505                 /* FIXME: handle quoting */
506                 chars = CertRDNValueToStrW(
507                  rdn->rgRDNAttr[j].dwValueType,
508                  &rdn->rgRDNAttr[j].Value, psz ? psz + ret : NULL,
509                  psz ? csz - ret : 0);
510                 if (chars)
511                     ret += chars - 1;
512                 if (j < rdn->cRDNAttr - 1)
513                 {
514                     if (psz && ret < csz - rdnSepLen - 1)
515                         memcpy(psz + ret, rdnSep, rdnSepLen * sizeof(WCHAR));
516                     ret += rdnSepLen;
517                 }
518             }
519             if (i < info->cRDN - 1)
520             {
521                 if (psz && ret < csz - sepLen - 1)
522                     memcpy(psz + ret, sep, sepLen * sizeof(WCHAR));
523                 ret += sepLen;
524             }
525             if(reverse) rdn--;
526             else rdn++;
527         }
528         LocalFree(info);
529     }
530     if (psz && csz)
531     {
532         *(psz + ret) = '\0';
533         ret++;
534     }
535     else
536         ret++;
537     return ret;
538 }
539
540 DWORD WINAPI CertNameToStrW(DWORD dwCertEncodingType, PCERT_NAME_BLOB pName,
541  DWORD dwStrType, LPWSTR psz, DWORD csz)
542 {
543     BOOL ret;
544
545     TRACE("(%d, %p, %08x, %p, %d)\n", dwCertEncodingType, pName, dwStrType,
546      psz, csz);
547
548     ret = cert_name_to_str_with_indent(dwCertEncodingType, 0, pName, dwStrType,
549      psz, csz);
550     TRACE("Returning %s\n", debugstr_w(psz));
551     return ret;
552 }
553
554 BOOL WINAPI CertStrToNameA(DWORD dwCertEncodingType, LPCSTR pszX500,
555  DWORD dwStrType, void *pvReserved, BYTE *pbEncoded, DWORD *pcbEncoded,
556  LPCSTR *ppszError)
557 {
558     BOOL ret;
559     int len;
560
561     TRACE("(%08x, %s, %08x, %p, %p, %p, %p)\n", dwCertEncodingType,
562      debugstr_a(pszX500), dwStrType, pvReserved, pbEncoded, pcbEncoded,
563      ppszError);
564
565     len = MultiByteToWideChar(CP_ACP, 0, pszX500, -1, NULL, 0);
566     if (len)
567     {
568         LPWSTR x500, errorStr;
569
570         if ((x500 = CryptMemAlloc(len * sizeof(WCHAR))))
571         {
572             MultiByteToWideChar(CP_ACP, 0, pszX500, -1, x500, len);
573             ret = CertStrToNameW(dwCertEncodingType, x500, dwStrType,
574              pvReserved, pbEncoded, pcbEncoded,
575              ppszError ? (LPCWSTR *)&errorStr : NULL);
576             if (ppszError)
577             {
578                 if (!ret)
579                 {
580                     LONG i;
581
582                     *ppszError = pszX500;
583                     for (i = 0; i < errorStr - x500; i++)
584                         *ppszError = CharNextA(*ppszError);
585                 }
586                 else
587                     *ppszError = NULL;
588             }
589             CryptMemFree(x500);
590         }
591         else
592         {
593             SetLastError(ERROR_OUTOFMEMORY);
594             ret = FALSE;
595         }
596     }
597     else
598     {
599         SetLastError(CRYPT_E_INVALID_X500_STRING);
600         if (ppszError)
601             *ppszError = pszX500;
602         ret = FALSE;
603     }
604     return ret;
605 }
606
607 struct KeynameKeeper
608 {
609     WCHAR  buf[10]; /* big enough for L"GivenName" */
610     LPWSTR keyName; /* usually = buf, but may be allocated */
611     DWORD  keyLen;
612 };
613
614 static void CRYPT_InitializeKeynameKeeper(struct KeynameKeeper *keeper)
615 {
616     keeper->keyName = keeper->buf;
617     keeper->keyLen = sizeof(keeper->buf) / sizeof(keeper->buf[0]);
618 }
619
620 static void CRYPT_FreeKeynameKeeper(struct KeynameKeeper *keeper)
621 {
622     if (keeper->keyName != keeper->buf)
623         CryptMemFree(keeper->keyName);
624 }
625
626 struct X500TokenW
627 {
628     LPCWSTR start;
629     LPCWSTR end;
630 };
631
632 static void CRYPT_KeynameKeeperFromTokenW(struct KeynameKeeper *keeper,
633  const struct X500TokenW *key)
634 {
635     DWORD len = key->end - key->start;
636
637     if (len > keeper->keyLen)
638     {
639         if (keeper->keyName == keeper->buf)
640             keeper->keyName = CryptMemAlloc(len * sizeof(WCHAR));
641         else
642             keeper->keyName = CryptMemRealloc(keeper->keyName,
643              len * sizeof(WCHAR));
644         keeper->keyLen = len;
645     }
646     memcpy(keeper->keyName, key->start, (key->end - key->start) *
647      sizeof(WCHAR));
648     keeper->keyName[len] = '\0';
649     TRACE("Keyname is %s\n", debugstr_w(keeper->keyName));
650 }
651
652 static BOOL CRYPT_GetNextKeyW(LPCWSTR str, struct X500TokenW *token,
653  LPCWSTR *ppszError)
654 {
655     BOOL ret = TRUE;
656
657     while (*str && isspaceW(*str))
658         str++;
659     if (*str)
660     {
661         token->start = str;
662         while (*str && *str != '=' && !isspaceW(*str))
663             str++;
664         if (*str && (*str == '=' || isspaceW(*str)))
665             token->end = str;
666         else
667         {
668             TRACE("missing equals char at %s\n", debugstr_w(token->start));
669             if (ppszError)
670                 *ppszError = token->start;
671             SetLastError(CRYPT_E_INVALID_X500_STRING);
672             ret = FALSE;
673         }
674     }
675     else
676         token->start = NULL;
677     return ret;
678 }
679
680 /* Assumes separators are characters in the 0-255 range */
681 static BOOL CRYPT_GetNextValueW(LPCWSTR str, DWORD dwFlags, LPCWSTR separators,
682  struct X500TokenW *token, LPCWSTR *ppszError)
683 {
684     BOOL ret = TRUE;
685
686     TRACE("(%s, %s, %p, %p)\n", debugstr_w(str), debugstr_w(separators), token,
687      ppszError);
688
689     while (*str && isspaceW(*str))
690         str++;
691     if (*str)
692     {
693         token->start = str;
694         if (!(dwFlags & CERT_NAME_STR_NO_QUOTING_FLAG) && *str == '"')
695         {
696             token->end = NULL;
697             str++;
698             while (!token->end && ret)
699             {
700                 while (*str && *str != '"')
701                     str++;
702                 if (*str == '"')
703                 {
704                     if (*(str + 1) != '"')
705                         token->end = str + 1;
706                     else
707                         str += 2;
708                 }
709                 else
710                 {
711                     TRACE("unterminated quote at %s\n", debugstr_w(str));
712                     if (ppszError)
713                         *ppszError = str;
714                     SetLastError(CRYPT_E_INVALID_X500_STRING);
715                     ret = FALSE;
716                 }
717             }
718         }
719         else
720         {
721             WCHAR map[256] = { 0 };
722
723             while (*separators)
724                 map[*separators++] = 1;
725             while (*str && (*str >= 0xff || !map[*str]))
726                 str++;
727             token->end = str;
728         }
729     }
730     else
731     {
732         TRACE("missing value at %s\n", debugstr_w(str));
733         if (ppszError)
734             *ppszError = str;
735         SetLastError(CRYPT_E_INVALID_X500_STRING);
736         ret = FALSE;
737     }
738     return ret;
739 }
740
741 /* Encodes the string represented by value as the string type type into the
742  * CERT_NAME_BLOB output.  If there is an error and ppszError is not NULL,
743  * *ppszError is set to the first failing character.  If there is no error,
744  * output's pbData must be freed with LocalFree.
745  */
746 static BOOL CRYPT_EncodeValueWithType(DWORD dwCertEncodingType,
747  const struct X500TokenW *value, PCERT_NAME_BLOB output, DWORD type,
748  LPCWSTR *ppszError)
749 {
750     CERT_NAME_VALUE nameValue = { type, { 0, NULL } };
751     BOOL ret = TRUE;
752
753     if (value->end > value->start)
754     {
755         nameValue.Value.pbData = CryptMemAlloc((value->end - value->start) *
756          sizeof(WCHAR));
757         if (!nameValue.Value.pbData)
758         {
759             SetLastError(ERROR_OUTOFMEMORY);
760             ret = FALSE;
761         }
762     }
763     if (ret)
764     {
765         if (value->end > value->start)
766         {
767             LONG i;
768             LPWSTR ptr = (LPWSTR)nameValue.Value.pbData;
769
770             for (i = 0; i < value->end - value->start; i++)
771             {
772                 *ptr++ = value->start[i];
773                 if (value->start[i] == '"')
774                     i++;
775             }
776             nameValue.Value.cbData = (LPBYTE)ptr - nameValue.Value.pbData;
777         }
778         ret = CryptEncodeObjectEx(dwCertEncodingType, X509_UNICODE_NAME_VALUE,
779          &nameValue, CRYPT_ENCODE_ALLOC_FLAG, NULL, &output->pbData,
780          &output->cbData);
781         if (!ret && ppszError)
782         {
783             if (type == CERT_RDN_NUMERIC_STRING &&
784              GetLastError() == CRYPT_E_INVALID_NUMERIC_STRING)
785                 *ppszError = value->start + output->cbData;
786             else if (type == CERT_RDN_PRINTABLE_STRING &&
787              GetLastError() == CRYPT_E_INVALID_PRINTABLE_STRING)
788                 *ppszError = value->start + output->cbData;
789             else if (type == CERT_RDN_IA5_STRING &&
790              GetLastError() == CRYPT_E_INVALID_IA5_STRING)
791                 *ppszError = value->start + output->cbData;
792         }
793         CryptMemFree(nameValue.Value.pbData);
794     }
795     return ret;
796 }
797
798 static BOOL CRYPT_EncodeValue(DWORD dwCertEncodingType,
799  const struct X500TokenW *value, PCERT_NAME_BLOB output, const DWORD *types,
800  LPCWSTR *ppszError)
801 {
802     DWORD i;
803     BOOL ret;
804
805     ret = FALSE;
806     for (i = 0; !ret && types[i]; i++)
807         ret = CRYPT_EncodeValueWithType(dwCertEncodingType, value, output,
808          types[i], ppszError);
809     return ret;
810 }
811
812 static BOOL CRYPT_ValueToRDN(DWORD dwCertEncodingType, PCERT_NAME_INFO info,
813  PCCRYPT_OID_INFO keyOID, struct X500TokenW *value, LPCWSTR *ppszError)
814 {
815     BOOL ret = FALSE;
816
817     TRACE("OID %s, value %s\n", debugstr_a(keyOID->pszOID),
818      debugstr_wn(value->start, value->end - value->start));
819
820     if (!info->rgRDN)
821         info->rgRDN = CryptMemAlloc(sizeof(CERT_RDN));
822     else
823         info->rgRDN = CryptMemRealloc(info->rgRDN,
824          (info->cRDN + 1) * sizeof(CERT_RDN));
825     if (info->rgRDN)
826     {
827         /* FIXME: support multiple RDN attrs */
828         info->rgRDN[info->cRDN].rgRDNAttr =
829          CryptMemAlloc(sizeof(CERT_RDN_ATTR));
830         if (info->rgRDN[info->cRDN].rgRDNAttr)
831         {
832             static const DWORD defaultTypes[] = { CERT_RDN_PRINTABLE_STRING,
833              CERT_RDN_BMP_STRING, 0 };
834             const DWORD *types;
835
836             info->rgRDN[info->cRDN].cRDNAttr = 1;
837             info->rgRDN[info->cRDN].rgRDNAttr[0].pszObjId =
838              (LPSTR)keyOID->pszOID;
839             info->rgRDN[info->cRDN].rgRDNAttr[0].dwValueType =
840              CERT_RDN_ENCODED_BLOB;
841             if (keyOID->ExtraInfo.cbData)
842                 types = (const DWORD *)keyOID->ExtraInfo.pbData;
843             else
844                 types = defaultTypes;
845
846             /* Remove surrounding quotes */
847             if (value->start[0] == '"')
848             {
849                 value->start++;
850                 value->end--;
851             }
852             ret = CRYPT_EncodeValue(dwCertEncodingType, value,
853              &info->rgRDN[info->cRDN].rgRDNAttr[0].Value, types, ppszError);
854         }
855         else
856             SetLastError(ERROR_OUTOFMEMORY);
857         info->cRDN++;
858     }
859     else
860         SetLastError(ERROR_OUTOFMEMORY);
861     return ret;
862 }
863
864 BOOL WINAPI CertStrToNameW(DWORD dwCertEncodingType, LPCWSTR pszX500,
865  DWORD dwStrType, void *pvReserved, BYTE *pbEncoded, DWORD *pcbEncoded,
866  LPCWSTR *ppszError)
867 {
868     CERT_NAME_INFO info = { 0, NULL };
869     LPCWSTR str;
870     struct KeynameKeeper keeper;
871     DWORD i;
872     BOOL ret = TRUE;
873
874     TRACE("(%08x, %s, %08x, %p, %p, %p, %p)\n", dwCertEncodingType,
875      debugstr_w(pszX500), dwStrType, pvReserved, pbEncoded, pcbEncoded,
876      ppszError);
877
878     CRYPT_InitializeKeynameKeeper(&keeper);
879     str = pszX500;
880     while (str && *str && ret)
881     {
882         struct X500TokenW token;
883
884         ret = CRYPT_GetNextKeyW(str, &token, ppszError);
885         if (ret && token.start)
886         {
887             PCCRYPT_OID_INFO keyOID;
888
889             CRYPT_KeynameKeeperFromTokenW(&keeper, &token);
890             keyOID = CryptFindOIDInfo(CRYPT_OID_INFO_NAME_KEY, keeper.keyName,
891              CRYPT_RDN_ATTR_OID_GROUP_ID);
892             if (!keyOID)
893             {
894                 if (ppszError)
895                     *ppszError = token.start;
896                 SetLastError(CRYPT_E_INVALID_X500_STRING);
897                 ret = FALSE;
898             }
899             else
900             {
901                 str = token.end;
902                 while (isspace(*str))
903                     str++;
904                 if (*str != '=')
905                 {
906                     if (ppszError)
907                         *ppszError = str;
908                     SetLastError(CRYPT_E_INVALID_X500_STRING);
909                     ret = FALSE;
910                 }
911                 else
912                 {
913                     static const WCHAR commaSep[] = { ',',0 };
914                     static const WCHAR semiSep[] = { ';',0 };
915                     static const WCHAR crlfSep[] = { '\r','\n',0 };
916                     static const WCHAR allSeps[] = { ',',';','\r','\n',0 };
917                     LPCWSTR sep;
918
919                     str++;
920                     if (dwStrType & CERT_NAME_STR_COMMA_FLAG)
921                         sep = commaSep;
922                     else if (dwStrType & CERT_NAME_STR_SEMICOLON_FLAG)
923                         sep = semiSep;
924                     else if (dwStrType & CERT_NAME_STR_CRLF_FLAG)
925                         sep = crlfSep;
926                     else
927                         sep = allSeps;
928                     ret = CRYPT_GetNextValueW(str, dwStrType, sep, &token,
929                      ppszError);
930                     if (ret)
931                     {
932                         str = token.end;
933                         ret = CRYPT_ValueToRDN(dwCertEncodingType, &info,
934                          keyOID, &token, ppszError);
935                     }
936                 }
937             }
938         }
939     }
940     CRYPT_FreeKeynameKeeper(&keeper);
941     if (ret)
942     {
943         if (ppszError)
944             *ppszError = NULL;
945         ret = CryptEncodeObjectEx(dwCertEncodingType, X509_NAME, &info,
946          0, NULL, pbEncoded, pcbEncoded);
947     }
948     for (i = 0; i < info.cRDN; i++)
949     {
950         DWORD j;
951
952         for (j = 0; j < info.rgRDN[i].cRDNAttr; j++)
953             LocalFree(info.rgRDN[i].rgRDNAttr[j].Value.pbData);
954         CryptMemFree(info.rgRDN[i].rgRDNAttr);
955     }
956     CryptMemFree(info.rgRDN);
957     return ret;
958 }
959
960 DWORD WINAPI CertGetNameStringA(PCCERT_CONTEXT pCertContext, DWORD dwType,
961  DWORD dwFlags, void *pvTypePara, LPSTR pszNameString, DWORD cchNameString)
962 {
963     DWORD ret;
964
965     TRACE("(%p, %d, %08x, %p, %p, %d)\n", pCertContext, dwType, dwFlags,
966      pvTypePara, pszNameString, cchNameString);
967
968     if (pszNameString)
969     {
970         LPWSTR wideName;
971         DWORD nameLen;
972
973         nameLen = CertGetNameStringW(pCertContext, dwType, dwFlags, pvTypePara,
974          NULL, 0);
975         wideName = CryptMemAlloc(nameLen * sizeof(WCHAR));
976         if (wideName)
977         {
978             CertGetNameStringW(pCertContext, dwType, dwFlags, pvTypePara,
979              wideName, nameLen);
980             nameLen = WideCharToMultiByte(CP_ACP, 0, wideName, nameLen,
981              pszNameString, cchNameString, NULL, NULL);
982             if (nameLen <= cchNameString)
983                 ret = nameLen;
984             else
985             {
986                 pszNameString[cchNameString - 1] = '\0';
987                 ret = cchNameString;
988             }
989             CryptMemFree(wideName);
990         }
991         else
992         {
993             *pszNameString = '\0';
994             ret = 1;
995         }
996     }
997     else
998         ret = CertGetNameStringW(pCertContext, dwType, dwFlags, pvTypePara,
999          NULL, 0);
1000     return ret;
1001 }
1002
1003 /* Searches cert's extensions for the alternate name extension with OID
1004  * altNameOID, and if found, searches it for the alternate name type entryType.
1005  * If found, returns a pointer to the entry, otherwise returns NULL.
1006  * Regardless of whether an entry of the desired type is found, if the
1007  * alternate name extension is present, sets *info to the decoded alternate
1008  * name extension, which you must free using LocalFree.
1009  * The return value is a pointer within *info, so don't free *info before
1010  * you're done with the return value.
1011  */
1012 static PCERT_ALT_NAME_ENTRY cert_find_alt_name_entry(PCCERT_CONTEXT cert,
1013  LPCSTR altNameOID, DWORD entryType, PCERT_ALT_NAME_INFO *info)
1014 {
1015     PCERT_ALT_NAME_ENTRY entry = NULL;
1016     PCERT_EXTENSION ext = CertFindExtension(altNameOID,
1017      cert->pCertInfo->cExtension, cert->pCertInfo->rgExtension);
1018
1019     if (ext)
1020     {
1021         DWORD bytes = 0;
1022
1023         if (CryptDecodeObjectEx(cert->dwCertEncodingType, X509_ALTERNATE_NAME,
1024          ext->Value.pbData, ext->Value.cbData, CRYPT_DECODE_ALLOC_FLAG, NULL,
1025          info, &bytes))
1026         {
1027             DWORD i;
1028
1029             for (i = 0; !entry && i < (*info)->cAltEntry; i++)
1030                 if ((*info)->rgAltEntry[i].dwAltNameChoice == entryType)
1031                     entry = &(*info)->rgAltEntry[i];
1032         }
1033     }
1034     else
1035         *info = NULL;
1036     return entry;
1037 }
1038
1039 static DWORD cert_get_name_from_rdn_attr(DWORD encodingType,
1040  const CERT_NAME_BLOB *name, LPCSTR oid, LPWSTR pszNameString, DWORD cchNameString)
1041 {
1042     CERT_NAME_INFO *nameInfo;
1043     DWORD bytes = 0, ret = 0;
1044
1045     if (CryptDecodeObjectEx(encodingType, X509_NAME, name->pbData,
1046      name->cbData, CRYPT_DECODE_ALLOC_FLAG, NULL, &nameInfo, &bytes))
1047     {
1048         PCERT_RDN_ATTR nameAttr = CertFindRDNAttr(oid, nameInfo);
1049
1050         if (nameAttr)
1051             ret = CertRDNValueToStrW(nameAttr->dwValueType, &nameAttr->Value,
1052              pszNameString, cchNameString);
1053         LocalFree(nameInfo);
1054     }
1055     return ret;
1056 }
1057
1058 DWORD WINAPI CertGetNameStringW(PCCERT_CONTEXT pCertContext, DWORD dwType,
1059  DWORD dwFlags, void *pvTypePara, LPWSTR pszNameString, DWORD cchNameString)
1060 {
1061     DWORD ret = 0;
1062     PCERT_NAME_BLOB name;
1063     LPCSTR altNameOID;
1064
1065     TRACE("(%p, %d, %08x, %p, %p, %d)\n", pCertContext, dwType,
1066      dwFlags, pvTypePara, pszNameString, cchNameString);
1067
1068     if (dwFlags & CERT_NAME_ISSUER_FLAG)
1069     {
1070         name = &pCertContext->pCertInfo->Issuer;
1071         altNameOID = szOID_ISSUER_ALT_NAME;
1072     }
1073     else
1074     {
1075         name = &pCertContext->pCertInfo->Subject;
1076         altNameOID = szOID_SUBJECT_ALT_NAME;
1077     }
1078
1079     switch (dwType)
1080     {
1081     case CERT_NAME_EMAIL_TYPE:
1082     {
1083         CERT_ALT_NAME_INFO *info;
1084         PCERT_ALT_NAME_ENTRY entry = cert_find_alt_name_entry(pCertContext,
1085          altNameOID, CERT_ALT_NAME_RFC822_NAME, &info);
1086
1087         if (entry)
1088         {
1089             if (!pszNameString)
1090                 ret = strlenW(entry->u.pwszRfc822Name) + 1;
1091             else if (cchNameString)
1092             {
1093                 ret = min(strlenW(entry->u.pwszRfc822Name), cchNameString - 1);
1094                 memcpy(pszNameString, entry->u.pwszRfc822Name,
1095                  ret * sizeof(WCHAR));
1096                 pszNameString[ret++] = 0;
1097             }
1098         }
1099         if (info)
1100             LocalFree(info);
1101         if (!ret)
1102             ret = cert_get_name_from_rdn_attr(pCertContext->dwCertEncodingType,
1103              name, szOID_RSA_emailAddr, pszNameString, cchNameString);
1104         break;
1105     }
1106     case CERT_NAME_RDN_TYPE:
1107         if (name->cbData)
1108             ret = CertNameToStrW(pCertContext->dwCertEncodingType, name,
1109              *(DWORD *)pvTypePara, pszNameString, cchNameString);
1110         else
1111         {
1112             CERT_ALT_NAME_INFO *info;
1113             PCERT_ALT_NAME_ENTRY entry = cert_find_alt_name_entry(pCertContext,
1114              altNameOID, CERT_ALT_NAME_DIRECTORY_NAME, &info);
1115
1116             if (entry)
1117                 ret = CertNameToStrW(pCertContext->dwCertEncodingType,
1118                  &entry->u.DirectoryName, *(DWORD *)pvTypePara, pszNameString,
1119                  cchNameString);
1120             if (info)
1121                 LocalFree(info);
1122         }
1123         break;
1124     case CERT_NAME_ATTR_TYPE:
1125         ret = cert_get_name_from_rdn_attr(pCertContext->dwCertEncodingType,
1126          name, pvTypePara, pszNameString, cchNameString);
1127         if (!ret)
1128         {
1129             CERT_ALT_NAME_INFO *altInfo;
1130             PCERT_ALT_NAME_ENTRY entry = cert_find_alt_name_entry(pCertContext,
1131              altNameOID, CERT_ALT_NAME_DIRECTORY_NAME, &altInfo);
1132
1133             if (entry)
1134                 ret = cert_name_to_str_with_indent(X509_ASN_ENCODING, 0,
1135                  &entry->u.DirectoryName, 0, pszNameString, cchNameString);
1136             if (altInfo)
1137                 LocalFree(altInfo);
1138         }
1139         break;
1140     case CERT_NAME_SIMPLE_DISPLAY_TYPE:
1141     {
1142         static const LPCSTR simpleAttributeOIDs[] = { szOID_COMMON_NAME,
1143          szOID_ORGANIZATIONAL_UNIT_NAME, szOID_ORGANIZATION_NAME,
1144          szOID_RSA_emailAddr };
1145         CERT_NAME_INFO *nameInfo = NULL;
1146         DWORD bytes = 0, i;
1147
1148         if (CryptDecodeObjectEx(pCertContext->dwCertEncodingType, X509_NAME,
1149          name->pbData, name->cbData, CRYPT_DECODE_ALLOC_FLAG, NULL, &nameInfo,
1150          &bytes))
1151         {
1152             PCERT_RDN_ATTR nameAttr = NULL;
1153
1154             for (i = 0; !nameAttr && i < sizeof(simpleAttributeOIDs) /
1155              sizeof(simpleAttributeOIDs[0]); i++)
1156                 nameAttr = CertFindRDNAttr(simpleAttributeOIDs[i], nameInfo);
1157             if (nameAttr)
1158                 ret = CertRDNValueToStrW(nameAttr->dwValueType,
1159                  &nameAttr->Value, pszNameString, cchNameString);
1160             LocalFree(nameInfo);
1161         }
1162         if (!ret)
1163         {
1164             CERT_ALT_NAME_INFO *altInfo;
1165             PCERT_ALT_NAME_ENTRY entry = cert_find_alt_name_entry(pCertContext,
1166              altNameOID, CERT_ALT_NAME_RFC822_NAME, &altInfo);
1167
1168             if (altInfo)
1169             {
1170                 if (!entry && altInfo->cAltEntry)
1171                     entry = &altInfo->rgAltEntry[0];
1172                 if (entry)
1173                 {
1174                     if (!pszNameString)
1175                         ret = strlenW(entry->u.pwszRfc822Name) + 1;
1176                     else if (cchNameString)
1177                     {
1178                         ret = min(strlenW(entry->u.pwszRfc822Name),
1179                          cchNameString - 1);
1180                         memcpy(pszNameString, entry->u.pwszRfc822Name,
1181                          ret * sizeof(WCHAR));
1182                         pszNameString[ret++] = 0;
1183                     }
1184                 }
1185                 LocalFree(altInfo);
1186             }
1187         }
1188         break;
1189     }
1190     case CERT_NAME_FRIENDLY_DISPLAY_TYPE:
1191     {
1192         DWORD cch = cchNameString;
1193
1194         if (CertGetCertificateContextProperty(pCertContext,
1195          CERT_FRIENDLY_NAME_PROP_ID, pszNameString, &cch))
1196             ret = cch;
1197         else
1198             ret = CertGetNameStringW(pCertContext,
1199              CERT_NAME_SIMPLE_DISPLAY_TYPE, dwFlags, pvTypePara, pszNameString,
1200              cchNameString);
1201         break;
1202     }
1203     case CERT_NAME_DNS_TYPE:
1204     {
1205         CERT_ALT_NAME_INFO *info;
1206         PCERT_ALT_NAME_ENTRY entry = cert_find_alt_name_entry(pCertContext,
1207          altNameOID, CERT_ALT_NAME_DNS_NAME, &info);
1208
1209         if (entry)
1210         {
1211             if (!pszNameString)
1212                 ret = strlenW(entry->u.pwszDNSName) + 1;
1213             else if (cchNameString)
1214             {
1215                 ret = min(strlenW(entry->u.pwszDNSName), cchNameString - 1);
1216                 memcpy(pszNameString, entry->u.pwszDNSName, ret * sizeof(WCHAR));
1217                 pszNameString[ret++] = 0;
1218             }
1219         }
1220         if (info)
1221             LocalFree(info);
1222         if (!ret)
1223             ret = cert_get_name_from_rdn_attr(pCertContext->dwCertEncodingType,
1224              name, szOID_COMMON_NAME, pszNameString, cchNameString);
1225         break;
1226     }
1227     case CERT_NAME_URL_TYPE:
1228     {
1229         CERT_ALT_NAME_INFO *info;
1230         PCERT_ALT_NAME_ENTRY entry = cert_find_alt_name_entry(pCertContext,
1231          altNameOID, CERT_ALT_NAME_URL, &info);
1232
1233         if (entry)
1234         {
1235             if (!pszNameString)
1236                 ret = strlenW(entry->u.pwszURL) + 1;
1237             else if (cchNameString)
1238             {
1239                 ret = min(strlenW(entry->u.pwszURL), cchNameString - 1);
1240                 memcpy(pszNameString, entry->u.pwszURL, ret * sizeof(WCHAR));
1241                 pszNameString[ret++] = 0;
1242             }
1243         }
1244         if (info)
1245             LocalFree(info);
1246         break;
1247     }
1248     default:
1249         FIXME("unimplemented for type %d\n", dwType);
1250         ret = 0;
1251     }
1252     if (!ret)
1253     {
1254         if (!pszNameString)
1255             ret = 1;
1256         else if (cchNameString)
1257         {
1258             pszNameString[0] = 0;
1259             ret = 1;
1260         }
1261     }
1262     return ret;
1263 }