Imported Upstream version 3.13.6
[platform/upstream/nss.git] / mozilla / security / nss / lib / certdb / alg1485.c
1 /* alg1485.c - implementation of RFCs 1485, 1779 and 2253.
2  *
3  * ***** BEGIN LICENSE BLOCK *****
4  * Version: MPL 1.1/GPL 2.0/LGPL 2.1
5  *
6  * The contents of this file are subject to the Mozilla Public License Version
7  * 1.1 (the "License"); you may not use this file except in compliance with
8  * the License. You may obtain a copy of the License at
9  * http://www.mozilla.org/MPL/
10  *
11  * Software distributed under the License is distributed on an "AS IS" basis,
12  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
13  * for the specific language governing rights and limitations under the
14  * License.
15  *
16  * The Original Code is the Netscape security libraries.
17  *
18  * The Initial Developer of the Original Code is
19  * Netscape Communications Corporation.
20  * Portions created by the Initial Developer are Copyright (C) 1994-2000
21  * the Initial Developer. All Rights Reserved.
22  *
23  * Contributor(s):
24  *
25  * Alternatively, the contents of this file may be used under the terms of
26  * either the GNU General Public License Version 2 or later (the "GPL"), or
27  * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
28  * in which case the provisions of the GPL or the LGPL are applicable instead
29  * of those above. If you wish to allow use of your version of this file only
30  * under the terms of either the GPL or the LGPL, and not to allow others to
31  * use your version of this file under the terms of the MPL, indicate your
32  * decision by deleting the provisions above and replace them with the notice
33  * and other provisions required by the GPL or the LGPL. If you do not delete
34  * the provisions above, a recipient may use your version of this file under
35  * the terms of any one of the MPL, the GPL or the LGPL.
36  *
37  * ***** END LICENSE BLOCK ***** */
38
39 #include "prprf.h"
40 #include "cert.h"
41 #include "certi.h"
42 #include "xconst.h"
43 #include "genname.h"
44 #include "secitem.h"
45 #include "secerr.h"
46
47 typedef struct NameToKindStr {
48     const char * name;
49     unsigned int maxLen; /* max bytes in UTF8 encoded string value */
50     SECOidTag    kind;
51     int          valueType;
52 } NameToKind;
53
54 /* local type for directory string--could be printable_string or utf8 */
55 #define SEC_ASN1_DS SEC_ASN1_HIGH_TAG_NUMBER
56
57 /* Add new entries to this table, and maybe to function ParseRFC1485AVA */
58 static const NameToKind name2kinds[] = {
59 /* IANA registered type names
60  * (See: http://www.iana.org/assignments/ldap-parameters) 
61  */
62 /* RFC 3280, 4630 MUST SUPPORT */
63     { "CN",             64, SEC_OID_AVA_COMMON_NAME,    SEC_ASN1_DS},
64     { "ST",            128, SEC_OID_AVA_STATE_OR_PROVINCE,
65                                                         SEC_ASN1_DS},
66     { "O",              64, SEC_OID_AVA_ORGANIZATION_NAME,
67                                                         SEC_ASN1_DS},
68     { "OU",             64, SEC_OID_AVA_ORGANIZATIONAL_UNIT_NAME,
69                                                         SEC_ASN1_DS},
70     { "dnQualifier", 32767, SEC_OID_AVA_DN_QUALIFIER, SEC_ASN1_PRINTABLE_STRING},
71     { "C",               2, SEC_OID_AVA_COUNTRY_NAME, SEC_ASN1_PRINTABLE_STRING},
72     { "serialNumber",   64, SEC_OID_AVA_SERIAL_NUMBER,SEC_ASN1_PRINTABLE_STRING},
73
74 /* RFC 3280, 4630 SHOULD SUPPORT */
75     { "L",             128, SEC_OID_AVA_LOCALITY,       SEC_ASN1_DS},
76     { "title",          64, SEC_OID_AVA_TITLE,          SEC_ASN1_DS},
77     { "SN",             64, SEC_OID_AVA_SURNAME,        SEC_ASN1_DS},
78     { "givenName",      64, SEC_OID_AVA_GIVEN_NAME,     SEC_ASN1_DS},
79     { "initials",       64, SEC_OID_AVA_INITIALS,       SEC_ASN1_DS},
80     { "generationQualifier",
81                         64, SEC_OID_AVA_GENERATION_QUALIFIER,
82                                                         SEC_ASN1_DS},
83 /* RFC 3280, 4630 MAY SUPPORT */
84     { "DC",            128, SEC_OID_AVA_DC,             SEC_ASN1_IA5_STRING},
85     { "MAIL",          256, SEC_OID_RFC1274_MAIL,       SEC_ASN1_IA5_STRING},
86     { "UID",           256, SEC_OID_RFC1274_UID,        SEC_ASN1_DS},
87
88 /* ------------------ "strict" boundary ---------------------------------
89  * In strict mode, cert_NameToAscii does not encode any of the attributes
90  * below this line. The first SECOidTag below this line must be used to
91  * conditionally define the "endKind" in function AppendAVA() below.
92  * Most new attribute names should be added below this line.
93  * Maybe this line should be up higher?  Say, after the 3280 MUSTs and 
94  * before the 3280 SHOULDs?
95  */
96
97 /* values from draft-ietf-ldapbis-user-schema-05 (not in RFC 3280) */
98     { "postalAddress", 128, SEC_OID_AVA_POSTAL_ADDRESS, SEC_ASN1_DS},
99     { "postalCode",     40, SEC_OID_AVA_POSTAL_CODE,    SEC_ASN1_DS},
100     { "postOfficeBox",  40, SEC_OID_AVA_POST_OFFICE_BOX,SEC_ASN1_DS},
101     { "houseIdentifier",64, SEC_OID_AVA_HOUSE_IDENTIFIER,SEC_ASN1_DS},
102 /* end of IANA registered type names */
103
104 /* legacy keywords */
105     { "E",             128, SEC_OID_PKCS9_EMAIL_ADDRESS,SEC_ASN1_IA5_STRING},
106     { "STREET",        128, SEC_OID_AVA_STREET_ADDRESS, SEC_ASN1_DS},
107     { "pseudonym",      64, SEC_OID_AVA_PSEUDONYM,      SEC_ASN1_DS},
108
109 /* values defined by the CAB Forum for EV */
110     { "incorporationLocality", 128, SEC_OID_EV_INCORPORATION_LOCALITY,
111                                                         SEC_ASN1_DS},
112     { "incorporationState",    128, SEC_OID_EV_INCORPORATION_STATE,
113                                                         SEC_ASN1_DS},
114     { "incorporationCountry",    2, SEC_OID_EV_INCORPORATION_COUNTRY,
115                                                     SEC_ASN1_PRINTABLE_STRING},
116     { "businessCategory",       64, SEC_OID_BUSINESS_CATEGORY, SEC_ASN1_DS},
117
118     { 0,               256, SEC_OID_UNKNOWN,            0},
119 };
120
121 /* Table facilitates conversion of ASCII hex to binary. */
122 static const PRInt16 x2b[256] = {
123 /* #0x */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 
124 /* #1x */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 
125 /* #2x */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 
126 /* #3x */  0,  1,  2,  3,  4,  5,  6,  7,  8,  9, -1, -1, -1, -1, -1, -1, 
127 /* #4x */ -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, 
128 /* #5x */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 
129 /* #6x */ -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, 
130 /* #7x */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 
131 /* #8x */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 
132 /* #9x */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 
133 /* #ax */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 
134 /* #bx */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 
135 /* #cx */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 
136 /* #dx */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 
137 /* #ex */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 
138 /* #fx */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
139 };
140
141 #define IS_HEX(c) (x2b[(PRUint8)(c)] >= 0)
142
143 #define C_DOUBLE_QUOTE '\042'
144
145 #define C_BACKSLASH '\134'
146
147 #define C_EQUAL '='
148
149 #define OPTIONAL_SPACE(c) \
150     (((c) == ' ') || ((c) == '\r') || ((c) == '\n'))
151
152 #define SPECIAL_CHAR(c)                                         \
153     (((c) == ',') || ((c) == '=') || ((c) == C_DOUBLE_QUOTE) || \
154      ((c) == '\r') || ((c) == '\n') || ((c) == '+') ||          \
155      ((c) == '<') || ((c) == '>') || ((c) == '#') ||            \
156      ((c) == ';') || ((c) == C_BACKSLASH))
157
158
159 #define IS_PRINTABLE(c)                                         \
160     ((((c) >= 'a') && ((c) <= 'z')) ||                          \
161      (((c) >= 'A') && ((c) <= 'Z')) ||                          \
162      (((c) >= '0') && ((c) <= '9')) ||                          \
163      ((c) == ' ') ||                                            \
164      ((c) == '\'') ||                                           \
165      ((c) == '\050') ||                         /* ( */         \
166      ((c) == '\051') ||                         /* ) */         \
167      (((c) >= '+') && ((c) <= '/')) ||          /* + , - . / */ \
168      ((c) == ':') ||                                            \
169      ((c) == '=') ||                                            \
170      ((c) == '?'))
171
172 /* RFC 2253 says we must escape ",+\"\\<>;=" EXCEPT inside a quoted string.
173  * Inside a quoted string, we only need to escape " and \
174  * We choose to quote strings containing any of those special characters,
175  * so we only need to escape " and \
176  */
177 #define NEEDS_ESCAPE(c) \
178     (c == C_DOUBLE_QUOTE || c == C_BACKSLASH)
179
180 #define NEEDS_HEX_ESCAPE(c) \
181     ((PRUint8)c < 0x20 || c == 0x7f)
182
183 int
184 cert_AVAOidTagToMaxLen(SECOidTag tag)
185 {
186     const NameToKind *n2k = name2kinds;
187
188     while (n2k->kind != tag && n2k->kind != SEC_OID_UNKNOWN) {
189         ++n2k;
190     }
191     return (n2k->kind != SEC_OID_UNKNOWN) ? n2k->maxLen : -1;
192 }
193
194 static PRBool
195 IsPrintable(unsigned char *data, unsigned len)
196 {
197     unsigned char ch, *end;
198
199     end = data + len;
200     while (data < end) {
201         ch = *data++;
202         if (!IS_PRINTABLE(ch)) {
203             return PR_FALSE;
204         }
205     }
206     return PR_TRUE;
207 }
208
209 static void
210 skipSpace(char **pbp, char *endptr)
211 {
212     char *bp = *pbp;
213     while (bp < endptr && OPTIONAL_SPACE(*bp)) {
214         bp++;
215     }
216     *pbp = bp;
217 }
218
219 static SECStatus
220 scanTag(char **pbp, char *endptr, char *tagBuf, int tagBufSize)
221 {
222     char *bp, *tagBufp;
223     int taglen;
224
225     PORT_Assert(tagBufSize > 0);
226     
227     /* skip optional leading space */
228     skipSpace(pbp, endptr);
229     if (*pbp == endptr) {
230         /* nothing left */
231         return SECFailure;
232     }
233     
234     /* fill tagBuf */
235     taglen = 0;
236     bp = *pbp;
237     tagBufp = tagBuf;
238     while (bp < endptr && !OPTIONAL_SPACE(*bp) && (*bp != C_EQUAL)) {
239         if (++taglen >= tagBufSize) {
240             *pbp = bp;
241             return SECFailure;
242         }
243         *tagBufp++ = *bp++;
244     }
245     /* null-terminate tagBuf -- guaranteed at least one space left */
246     *tagBufp++ = 0;
247     *pbp = bp;
248     
249     /* skip trailing spaces till we hit something - should be an equal sign */
250     skipSpace(pbp, endptr);
251     if (*pbp == endptr) {
252         /* nothing left */
253         return SECFailure;
254     }
255     if (**pbp != C_EQUAL) {
256         /* should be an equal sign */
257         return SECFailure;
258     }
259     /* skip over the equal sign */
260     (*pbp)++;
261     
262     return SECSuccess;
263 }
264
265 /* Returns the number of bytes in the value. 0 means failure. */
266 static int
267 scanVal(char **pbp, char *endptr, char *valBuf, int valBufSize)  
268 {
269     char *bp, *valBufp;
270     int vallen = 0;
271     PRBool isQuoted;
272     
273     PORT_Assert(valBufSize > 0);
274     
275     /* skip optional leading space */
276     skipSpace(pbp, endptr);
277     if(*pbp == endptr) {
278         /* nothing left */
279         return 0;
280     }
281     
282     bp = *pbp;
283     
284     /* quoted? */
285     if (*bp == C_DOUBLE_QUOTE) {
286         isQuoted = PR_TRUE;
287         /* skip over it */
288         bp++;
289     } else {
290         isQuoted = PR_FALSE;
291     }
292     
293     valBufp = valBuf;
294     while (bp < endptr) {
295         char c = *bp;
296         if (c == C_BACKSLASH) {
297             /* escape character */
298             bp++;
299             if (bp >= endptr) {
300                 /* escape charater must appear with paired char */
301                 *pbp = bp;
302                 return 0;
303             }
304             c = *bp;
305             if (IS_HEX(c) && (endptr - bp) >= 2 && IS_HEX(bp[1])) {
306                 bp++;
307                 c = (char)((x2b[(PRUint8)c] << 4) | x2b[(PRUint8)*bp]); 
308             }
309         } else if (c == '#' && bp == *pbp) {
310             /* ignore leading #, quotation not required for it. */
311         } else if (!isQuoted && SPECIAL_CHAR(c)) {
312             /* unescaped special and not within quoted value */
313             break;
314         } else if (c == C_DOUBLE_QUOTE) {
315             /* reached unescaped double quote */
316             break;
317         }
318         /* append character */
319         vallen++;
320         if (vallen >= valBufSize) {
321             *pbp = bp;
322             return 0;
323         }
324         *valBufp++ = c;
325         bp++;
326     }
327     
328     /* strip trailing spaces from unquoted values */
329     if (!isQuoted) {
330         while (valBufp > valBuf) {
331             char c = valBufp[-1];
332             if (! OPTIONAL_SPACE(c))
333                 break;
334             --valBufp;
335         }
336         vallen = valBufp - valBuf;
337     }
338     
339     if (isQuoted) {
340         /* insist that we stopped on a double quote */
341         if (*bp != C_DOUBLE_QUOTE) {
342             *pbp = bp;
343             return 0;
344         }
345         /* skip over the quote and skip optional space */
346         bp++;
347         skipSpace(&bp, endptr);
348     }
349     
350     *pbp = bp;
351     
352     /* null-terminate valBuf -- guaranteed at least one space left */
353     *valBufp = 0;
354     
355     return vallen;
356 }
357
358 /* Caller must set error code upon failure */
359 static SECStatus
360 hexToBin(PLArenaPool *pool, SECItem * destItem, const char * src, int len)
361 {
362     PRUint8 * dest;
363
364     destItem->data = NULL; 
365     if (len <= 0 || (len & 1)) {
366         goto loser;
367     }
368     len >>= 1;
369     if (!SECITEM_AllocItem(pool, destItem, len))
370         goto loser;
371     dest = destItem->data;
372     for (; len > 0; len--, src += 2) {
373         PRInt16 bin = (x2b[(PRUint8)src[0]] << 4) | x2b[(PRUint8)src[1]]; 
374         if (bin < 0)
375             goto loser;
376         *dest++ = (PRUint8)bin;
377     }
378     return SECSuccess;
379 loser:
380     if (!pool)
381         SECITEM_FreeItem(destItem, PR_FALSE);
382     return SECFailure;
383 }
384
385 /* Parses one AVA, starting at *pbp.  Stops at endptr.
386  * Advances *pbp past parsed AVA and trailing separator (if present).
387  * On any error, returns NULL and *pbp is undefined.
388  * On success, returns CERTAVA allocated from arena, and (*pbp)[-1] was 
389  * the last character parsed.  *pbp is either equal to endptr or 
390  * points to first character after separator.
391  */
392 static CERTAVA *
393 ParseRFC1485AVA(PRArenaPool *arena, char **pbp, char *endptr)
394 {
395     CERTAVA *a;
396     const NameToKind *n2k;
397     char *bp;
398     int       vt = -1;
399     int       valLen;
400     SECOidTag kind  = SEC_OID_UNKNOWN;
401     SECStatus rv    = SECFailure;
402     SECItem   derOid = { 0, NULL, 0 };
403     SECItem   derVal = { 0, NULL, 0};
404     char      sep   = 0;
405
406     char tagBuf[32];
407     char valBuf[384];
408
409     PORT_Assert(arena);
410     if (SECSuccess != scanTag(pbp, endptr, tagBuf, sizeof tagBuf) ||
411         !(valLen    = scanVal(pbp, endptr, valBuf, sizeof valBuf))) {
412         goto loser;
413     }
414
415     bp = *pbp;
416     if (bp < endptr) {
417         sep = *bp++; /* skip over separator */
418     }
419     *pbp = bp;
420     /* if we haven't finished, insist that we've stopped on a separator */
421     if (sep && sep != ',' && sep != ';' && sep != '+') {
422         goto loser;
423     }
424
425     /* is this a dotted decimal OID attribute type ? */
426     if (!PL_strncasecmp("oid.", tagBuf, 4)) {
427         rv = SEC_StringToOID(arena, &derOid, tagBuf, strlen(tagBuf));
428     } else {
429         for (n2k = name2kinds; n2k->name; n2k++) {
430             SECOidData *oidrec;
431             if (PORT_Strcasecmp(n2k->name, tagBuf) == 0) {
432                 kind = n2k->kind;
433                 vt   = n2k->valueType;
434                 oidrec = SECOID_FindOIDByTag(kind);
435                 if (oidrec == NULL)
436                     goto loser;
437                 derOid = oidrec->oid;
438                 break;
439             }
440         }
441     }
442     if (kind == SEC_OID_UNKNOWN && rv != SECSuccess) 
443         goto loser;
444
445     /* Is this a hex encoding of a DER attribute value ? */
446     if ('#' == valBuf[0]) {
447         /* convert attribute value from hex to binary */
448         rv = hexToBin(arena, &derVal, valBuf + 1, valLen - 1);
449         if (rv)
450             goto loser;
451         a = CERT_CreateAVAFromRaw(arena, &derOid, &derVal);
452     } else {
453         if (kind == SEC_OID_UNKNOWN)
454             goto loser;
455         if (kind == SEC_OID_AVA_COUNTRY_NAME && valLen != 2)
456             goto loser;
457         if (vt == SEC_ASN1_PRINTABLE_STRING &&
458             !IsPrintable((unsigned char*) valBuf, valLen)) 
459             goto loser;
460         if (vt == SEC_ASN1_DS) {
461             /* RFC 4630: choose PrintableString or UTF8String */
462             if (IsPrintable((unsigned char*) valBuf, valLen))
463                 vt = SEC_ASN1_PRINTABLE_STRING;
464             else 
465                 vt = SEC_ASN1_UTF8_STRING;
466         }
467
468         derVal.data = (unsigned char*) valBuf;
469         derVal.len  = valLen;
470         a = CERT_CreateAVAFromSECItem(arena, kind, vt, &derVal);
471     }
472     return a;
473
474 loser:
475     /* matched no kind -- invalid tag */
476     PORT_SetError(SEC_ERROR_INVALID_AVA);
477     return 0;
478 }
479
480 static CERTName *
481 ParseRFC1485Name(char *buf, int len)
482 {
483     SECStatus rv;
484     CERTName *name;
485     char *bp, *e;
486     CERTAVA *ava;
487     CERTRDN *rdn = NULL;
488
489     name = CERT_CreateName(NULL);
490     if (name == NULL) {
491         return NULL;
492     }
493     
494     e = buf + len;
495     bp = buf;
496     while (bp < e) {
497         ava = ParseRFC1485AVA(name->arena, &bp, e);
498         if (ava == 0) 
499             goto loser;
500         if (!rdn) {
501             rdn = CERT_CreateRDN(name->arena, ava, (CERTAVA *)0);
502             if (rdn == 0) 
503                 goto loser;
504             rv = CERT_AddRDN(name, rdn);
505         } else {
506             rv = CERT_AddAVA(name->arena, rdn, ava);
507         }
508         if (rv) 
509             goto loser;
510         if (bp[-1] != '+')
511             rdn = NULL; /* done with this RDN */
512         skipSpace(&bp, e);
513     }
514
515     if (name->rdns[0] == 0) {
516         /* empty name -- illegal */
517         goto loser;
518     }
519
520     /* Reverse order of RDNS to comply with RFC */
521     {
522         CERTRDN **firstRdn;
523         CERTRDN **lastRdn;
524         CERTRDN *tmp;
525         
526         /* get first one */
527         firstRdn = name->rdns;
528         
529         /* find last one */
530         lastRdn = name->rdns;
531         while (*lastRdn) lastRdn++;
532         lastRdn--;
533         
534         /* reverse list */
535         for ( ; firstRdn < lastRdn; firstRdn++, lastRdn--) {
536             tmp = *firstRdn;
537             *firstRdn = *lastRdn;
538             *lastRdn = tmp;
539         }
540     }
541     
542     /* return result */
543     return name;
544     
545   loser:
546     CERT_DestroyName(name);
547     return NULL;
548 }
549
550 CERTName *
551 CERT_AsciiToName(char *string)
552 {
553     CERTName *name;
554     name = ParseRFC1485Name(string, PORT_Strlen(string));
555     return name;
556 }
557
558 /************************************************************************/
559
560 typedef struct stringBufStr {
561     char *buffer;
562     unsigned offset;
563     unsigned size;
564 } stringBuf;
565
566 #define DEFAULT_BUFFER_SIZE 200
567
568 static SECStatus
569 AppendStr(stringBuf *bufp, char *str)
570 {
571     char *buf;
572     unsigned bufLen, bufSize, len;
573     int size = 0;
574
575     /* Figure out how much to grow buf by (add in the '\0') */
576     buf = bufp->buffer;
577     bufLen = bufp->offset;
578     len = PORT_Strlen(str);
579     bufSize = bufLen + len;
580     if (!buf) {
581         bufSize++;
582         size = PR_MAX(DEFAULT_BUFFER_SIZE,bufSize*2);
583         buf = (char *) PORT_Alloc(size);
584         bufp->size = size;
585     } else if (bufp->size < bufSize) {
586         size = bufSize*2;
587         buf =(char *) PORT_Realloc(buf,size);
588         bufp->size = size;
589     }
590     if (!buf) {
591         PORT_SetError(SEC_ERROR_NO_MEMORY);
592         return SECFailure;
593     }
594     bufp->buffer = buf;
595     bufp->offset = bufSize;
596
597     /* Concatenate str onto buf */
598     buf = buf + bufLen;
599     if (bufLen) buf--;                  /* stomp on old '\0' */
600     PORT_Memcpy(buf, str, len+1);               /* put in new null */
601     return SECSuccess;
602 }
603
604 typedef enum {
605     minimalEscape = 0,          /* only hex escapes, and " and \ */
606     minimalEscapeAndQuote,      /* as above, plus quoting        */
607     fullEscape                  /* no quoting, full escaping     */
608 } EQMode;
609
610 /* Some characters must be escaped as a hex string, e.g. c -> \nn .
611  * Others must be escaped by preceding with a '\', e.g. c -> \c , but
612  * there are certain "special characters" that may be handled by either
613  * escaping them, or by enclosing the entire attribute value in quotes.
614  * A NULL value for pEQMode implies selecting minimalEscape mode.
615  * Some callers will do quoting when needed, others will not.
616  * If a caller selects minimalEscapeAndQuote, and the string does not
617  * need quoting, then this function changes it to minimalEscape.
618  */
619 static int
620 cert_RFC1485_GetRequiredLen(const char *src, int srclen, EQMode *pEQMode)
621 {
622     int i, reqLen=0;
623     EQMode mode = pEQMode ? *pEQMode : minimalEscape;
624     PRBool needsQuoting = PR_FALSE;
625     char lastC = 0;
626
627     /* need to make an initial pass to determine if quoting is needed */
628     for (i = 0; i < srclen; i++) {
629         char c = src[i];
630         reqLen++;
631         if (NEEDS_HEX_ESCAPE(c)) {      /* c -> \xx  */
632             reqLen += 2;
633         } else if (NEEDS_ESCAPE(c)) {   /* c -> \c   */
634             reqLen++;
635         } else if (SPECIAL_CHAR(c)) {
636             if (mode == minimalEscapeAndQuote) /* quoting is allowed */
637                 needsQuoting = PR_TRUE; /* entirety will need quoting */
638             else if (mode == fullEscape)
639                 reqLen++;               /* MAY escape this character */
640         } else if (OPTIONAL_SPACE(c) && OPTIONAL_SPACE(lastC)) {
641             if (mode == minimalEscapeAndQuote) /* quoting is allowed */
642                 needsQuoting = PR_TRUE; /* entirety will need quoting */
643         }
644         lastC = c;
645     }
646     /* if it begins or ends in optional space it needs quoting */
647     if (!needsQuoting && srclen > 0 && mode == minimalEscapeAndQuote && 
648         (OPTIONAL_SPACE(src[srclen-1]) || OPTIONAL_SPACE(src[0]))) {
649         needsQuoting = PR_TRUE;
650     }
651
652     if (needsQuoting) 
653         reqLen += 2;
654     if (pEQMode && mode == minimalEscapeAndQuote && !needsQuoting)
655         *pEQMode = minimalEscape;
656     return reqLen;
657 }
658
659 static const char hexChars[16] = { "0123456789abcdef" };
660
661 static SECStatus
662 escapeAndQuote(char *dst, int dstlen, char *src, int srclen, EQMode *pEQMode)
663 {
664     int i, reqLen=0;
665     EQMode mode = pEQMode ? *pEQMode : minimalEscape;
666
667     /* space for terminal null */
668     reqLen = cert_RFC1485_GetRequiredLen(src, srclen, &mode) + 1;
669     if (reqLen > dstlen) {
670         PORT_SetError(SEC_ERROR_OUTPUT_LEN);
671         return SECFailure;
672     }
673
674     if (mode == minimalEscapeAndQuote)
675         *dst++ = C_DOUBLE_QUOTE;
676     for (i = 0; i < srclen; i++) {
677         char c = src[i];
678         if (NEEDS_HEX_ESCAPE(c)) {
679             *dst++ = C_BACKSLASH;
680             *dst++ = hexChars[ (c >> 4) & 0x0f ];
681             *dst++ = hexChars[  c       & 0x0f ];
682         } else {
683             if (NEEDS_ESCAPE(c) || (SPECIAL_CHAR(c) && mode == fullEscape)) {
684                 *dst++ = C_BACKSLASH;
685             }
686             *dst++ = c;
687         }
688     }
689     if (mode == minimalEscapeAndQuote)
690         *dst++ = C_DOUBLE_QUOTE;
691     *dst++ = 0;
692     if (pEQMode)
693         *pEQMode = mode;
694     return SECSuccess;
695 }
696
697 SECStatus
698 CERT_RFC1485_EscapeAndQuote(char *dst, int dstlen, char *src, int srclen)
699 {
700     EQMode mode = minimalEscapeAndQuote;
701     return escapeAndQuote(dst, dstlen, src, srclen, &mode);
702 }
703
704
705 /* convert an OID to dotted-decimal representation */
706 /* Returns a string that must be freed with PR_smprintf_free(), */
707 char *
708 CERT_GetOidString(const SECItem *oid)
709 {
710     PRUint8 *stop;   /* points to first byte after OID string */
711     PRUint8 *first;  /* byte of an OID component integer      */
712     PRUint8 *last;   /* byte of an OID component integer      */
713     char *rvString   = NULL;
714     char *prefix     = NULL;
715
716 #define MAX_OID_LEN 1024 /* bytes */
717
718     if (oid->len > MAX_OID_LEN) {
719         PORT_SetError(SEC_ERROR_INPUT_LEN);
720         return NULL;
721     }
722
723     /* first will point to the next sequence of bytes to decode */
724     first = (PRUint8 *)oid->data;
725     /* stop points to one past the legitimate data */
726     stop = &first[ oid->len ];
727
728     /*
729      * Check for our pseudo-encoded single-digit OIDs
730      */
731     if ((*first == 0x80) && (2 == oid->len)) {
732         /* Funky encoding.  The second byte is the number */
733         rvString = PR_smprintf("%lu", (PRUint32)first[1]);
734         if (!rvString) {
735             PORT_SetError(SEC_ERROR_NO_MEMORY);
736         }
737         return rvString;
738     }
739
740     for (; first < stop; first = last + 1) {
741         unsigned int bytesBeforeLast;
742     
743         for (last = first; last < stop; last++) {
744             if (0 == (*last & 0x80)) {
745                 break;
746             }
747         }
748         bytesBeforeLast = (unsigned int)(last - first);
749         if (bytesBeforeLast <= 3U) {        /* 0-28 bit number */
750             PRUint32 n = 0;
751             PRUint32 c;
752
753 #define CGET(i, m) \
754                 c  = last[-i] & m; \
755                 n |= c << (7 * i)
756
757 #define CASE(i, m) \
758             case i:                      \
759                 CGET(i, m);              \
760                 if (!n) goto unsupported \
761                 /* fall-through */
762
763             switch (bytesBeforeLast) {
764             CASE(3, 0x7f);
765             CASE(2, 0x7f);
766             CASE(1, 0x7f);
767             case 0: n |= last[0] & 0x7f;
768                 break;
769             }
770             if (last[0] & 0x80)
771                 goto unsupported;
772       
773             if (!rvString) {
774                 /* This is the first number.. decompose it */
775                 PRUint32 one = PR_MIN(n/40, 2); /* never > 2 */
776                 PRUint32 two = n - (one * 40);
777         
778                 rvString = PR_smprintf("OID.%lu.%lu", one, two);
779             } else {
780                 prefix = rvString;
781                 rvString = PR_smprintf("%s.%lu", prefix, n);
782             }
783         } else if (bytesBeforeLast <= 9U) { /* 29-64 bit number */
784             PRUint64 n = 0;
785             PRUint64 c;
786
787             switch (bytesBeforeLast) {
788             CASE(9, 0x01);
789             CASE(8, 0x7f);
790             CASE(7, 0x7f);
791             CASE(6, 0x7f);
792             CASE(5, 0x7f);
793             CASE(4, 0x7f);
794             CGET(3, 0x7f);
795             CGET(2, 0x7f);
796             CGET(1, 0x7f);
797             CGET(0, 0x7f);
798                 break;
799             }
800             if (last[0] & 0x80)
801                 goto unsupported;
802       
803             if (!rvString) {
804                 /* This is the first number.. decompose it */
805                 PRUint64 one = PR_MIN(n/40, 2); /* never > 2 */
806                 PRUint64 two = n - (one * 40);
807         
808                 rvString = PR_smprintf("OID.%llu.%llu", one, two);
809             } else {
810                 prefix = rvString;
811                 rvString = PR_smprintf("%s.%llu", prefix, n);
812             }
813         } else {
814             /* More than a 64-bit number, or not minimal encoding. */
815 unsupported:
816             if (!rvString)
817                 rvString = PR_smprintf("OID.UNSUPPORTED");
818             else {
819                 prefix = rvString;
820                 rvString = PR_smprintf("%s.UNSUPPORTED", prefix);
821             }
822         }
823
824         if (prefix) {
825             PR_smprintf_free(prefix);
826             prefix = NULL;
827         }
828         if (!rvString) {
829             PORT_SetError(SEC_ERROR_NO_MEMORY);
830             break;
831         }
832     }
833     return rvString;
834 }
835
836 /* convert DER-encoded hex to a string */
837 static SECItem *
838 get_hex_string(SECItem *data)
839 {
840     SECItem *rv;
841     unsigned int i, j;
842     static const char hex[] = { "0123456789ABCDEF" };
843
844     /* '#' + 2 chars per octet + terminator */
845     rv = SECITEM_AllocItem(NULL, NULL, data->len*2 + 2);
846     if (!rv) {
847         return NULL;
848     }
849     rv->data[0] = '#';
850     rv->len = 1 + 2 * data->len;
851     for (i=0; i<data->len; i++) {
852         j = data->data[i];
853         rv->data[2*i+1] = hex[j >> 4];
854         rv->data[2*i+2] = hex[j & 15];
855     }
856     rv->data[rv->len] = 0;
857     return rv;
858 }
859
860 /* For compliance with RFC 2253, RFC 3280 and RFC 4630, we choose to 
861  * use the NAME=STRING form, rather than the OID.N.N=#hexXXXX form, 
862  * when both of these conditions are met:
863  *  1) The attribute name OID (kind) has a known name string that is 
864  *     defined in one of those RFCs, or in RFCs that they cite, AND
865  *  2) The attribute's value encoding is RFC compliant for the kind
866  *     (e.g., the value's encoding tag is correct for the kind, and
867  *     the value's length is in the range allowed for the kind, and
868  *     the value's contents are appropriate for the encoding tag).
869  *  Otherwise, we use the OID.N.N=#hexXXXX form.
870  *
871  *  If the caller prefers maximum human readability to RFC compliance,
872  *  then 
873  *  - We print the kind in NAME= string form if we know the name
874  *    string for the attribute type OID, regardless of whether the 
875  *    value is correctly encoded or not. else we use the OID.N.N= form.
876  *  - We use the non-hex STRING form for the attribute value if the
877  *    value can be represented in such a form.  Otherwise, we use 
878  *    the hex string form.
879  *  This implies that, for maximum human readability, in addition to 
880  *  the two forms allowed by the RFC, we allow two other forms of output:
881  *  - the OID.N.N=STRING form, and 
882  *  - the NAME=#hexXXXX form
883  *  When the caller prefers maximum human readability, we do not allow
884  *  the value of any attribute to exceed the length allowed by the RFC.
885  *  If the attribute value exceeds the allowed length, we truncate it to 
886  *  the allowed length and append "...".
887  *  Also in this case, we arbitrarily impose a limit on the length of the 
888  *  entire AVA encoding, regardless of the form, of 384 bytes per AVA.
889  *  This limit includes the trailing NULL character.  If the encoded 
890  *  AVA length exceeds that limit, this function reports failure to encode
891  *  the AVA.
892  *
893  *  An ASCII representation of an AVA is said to be "invertible" if 
894  *  conversion back to DER reproduces the original DER encoding exactly.
895  *  The RFC 2253 rules do not ensure that all ASCII AVAs derived according
896  *  to its rules are invertible. That is because the RFCs allow some 
897  *  attribute values to be encoded in any of a number of encodings,
898  *  and the encoding type information is lost in the non-hex STRING form.
899  *  This is particularly true of attributes of type DirectoryString.
900  *  The encoding type information is always preserved in the hex string 
901  *  form, because the hex includes the entire DER encoding of the value.
902  *
903  *  So, when the caller perfers maximum invertibility, we apply the 
904  *  RFC compliance rules stated above, and add a third required 
905  *  condition on the use of the NAME=STRING form.  
906  *   3) The attribute's kind is not is allowed to be encoded in any of 
907  *      several different encodings, such as DirectoryStrings.
908  *
909  * The chief difference between CERT_N2A_STRICT and CERT_N2A_INVERTIBLE
910  * is that the latter forces DirectoryStrings to be hex encoded.
911  *
912  * As a simplification, we assume the value is correctly encoded for 
913  * its encoding type.  That is, we do not test that all the characters
914  * in a string encoded type are allowed by that type.  We assume it.
915  */
916 static SECStatus
917 AppendAVA(stringBuf *bufp, CERTAVA *ava, CertStrictnessLevel strict)
918 {
919 #define TMPBUF_LEN 384
920     const NameToKind *pn2k   = name2kinds;
921     SECItem     *avaValue    = NULL;
922     char        *unknownTag  = NULL;
923     char        *encodedAVA  = NULL;
924     PRBool       useHex      = PR_FALSE;  /* use =#hexXXXX form */
925     PRBool       truncateName  = PR_FALSE;
926     PRBool       truncateValue = PR_FALSE;
927     SECOidTag    endKind;
928     SECStatus    rv;
929     unsigned int len;
930     unsigned int nameLen, valueLen;
931     unsigned int maxName, maxValue;
932     EQMode       mode        = minimalEscapeAndQuote;
933     NameToKind   n2k         = { NULL, 32767, SEC_OID_UNKNOWN, SEC_ASN1_DS };
934     char         tmpBuf[TMPBUF_LEN];
935
936 #define tagName  n2k.name    /* non-NULL means use NAME= form */
937 #define maxBytes n2k.maxLen
938 #define tag      n2k.kind
939 #define vt       n2k.valueType
940
941     /* READABLE mode recognizes more names from the name2kinds table
942      * than do STRICT or INVERTIBLE modes.  This assignment chooses the
943      * point in the table where the attribute type name scanning stops.
944      */
945     endKind = (strict == CERT_N2A_READABLE) ? SEC_OID_UNKNOWN
946                                             : SEC_OID_AVA_POSTAL_ADDRESS;
947     tag = CERT_GetAVATag(ava);
948     while (pn2k->kind != tag && pn2k->kind != endKind) {
949         ++pn2k;
950     }
951
952     if (pn2k->kind != endKind ) {
953         n2k = *pn2k;
954     } else if (strict != CERT_N2A_READABLE) {
955         useHex = PR_TRUE;
956     }
957     /* For invertable form, force Directory Strings to use hex form. */
958     if (strict == CERT_N2A_INVERTIBLE && vt == SEC_ASN1_DS) {
959         tagName = NULL;      /* must use OID.N form */
960         useHex = PR_TRUE;    /* must use hex string */
961     }
962     if (!useHex) {
963         avaValue = CERT_DecodeAVAValue(&ava->value);
964         if (!avaValue) {
965             useHex = PR_TRUE;
966             if (strict != CERT_N2A_READABLE) {
967                 tagName = NULL;  /* must use OID.N form */
968             }
969         }
970     }
971     if (!tagName) {
972         /* handle unknown attribute types per RFC 2253 */
973         tagName = unknownTag = CERT_GetOidString(&ava->type);
974         if (!tagName) {
975             if (avaValue)
976                 SECITEM_FreeItem(avaValue, PR_TRUE);
977             return SECFailure;
978         }
979     }
980     if (useHex) {
981         avaValue = get_hex_string(&ava->value);
982         if (!avaValue) {
983             if (unknownTag) 
984                 PR_smprintf_free(unknownTag);
985             return SECFailure;
986         }
987     }
988
989     nameLen  = strlen(tagName);
990     valueLen = (useHex ? avaValue->len : 
991                 cert_RFC1485_GetRequiredLen((char *)avaValue->data, avaValue->len, 
992                                             &mode));
993     len = nameLen + valueLen + 2; /* Add 2 for '=' and trailing NUL */
994
995     maxName  = nameLen;
996     maxValue = valueLen;
997     if (len <= sizeof(tmpBuf)) {
998         encodedAVA = tmpBuf;
999     } else if (strict != CERT_N2A_READABLE) {
1000         encodedAVA = PORT_Alloc(len);
1001         if (!encodedAVA) {
1002             SECITEM_FreeItem(avaValue, PR_TRUE);
1003             if (unknownTag) 
1004                 PR_smprintf_free(unknownTag);
1005             return SECFailure;
1006         }
1007     } else {
1008         /* Must make output fit in tmpbuf */
1009         unsigned int fair = (sizeof tmpBuf)/2 - 1; /* for = and \0 */
1010
1011         if (nameLen < fair) {
1012             /* just truncate the value */
1013             maxValue = (sizeof tmpBuf) - (nameLen + 6); /* for "=...\0",
1014                                                            and possibly '"' */
1015         } else if (valueLen < fair) {
1016             /* just truncate the name */
1017             maxName  = (sizeof tmpBuf) - (valueLen + 5); /* for "=...\0" */
1018         } else {
1019             /* truncate both */
1020             maxName = maxValue = fair - 3;  /* for "..." */
1021         }
1022         if (nameLen > maxName) {
1023             PORT_Assert(unknownTag && unknownTag == tagName);
1024             truncateName = PR_TRUE;
1025             nameLen = maxName;
1026         }
1027         encodedAVA = tmpBuf;
1028     }
1029
1030     memcpy(encodedAVA, tagName, nameLen);
1031     if (truncateName) {
1032         /* If tag name is too long, we know it is an OID form that was 
1033          * allocated from the heap, so we can modify it in place 
1034          */
1035         encodedAVA[nameLen-1] = '.';
1036         encodedAVA[nameLen-2] = '.';
1037         encodedAVA[nameLen-3] = '.';
1038     }
1039     encodedAVA[nameLen++] = '=';
1040     if (unknownTag) 
1041         PR_smprintf_free(unknownTag);
1042
1043     if (strict == CERT_N2A_READABLE && maxValue > maxBytes)
1044         maxValue = maxBytes;
1045     if (valueLen > maxValue) {
1046         valueLen = maxValue;
1047         truncateValue = PR_TRUE;
1048     }
1049     /* escape and quote as necessary - don't quote hex strings */
1050     if (useHex) {
1051         char * end = encodedAVA + nameLen + valueLen;
1052         memcpy(encodedAVA + nameLen, (char *)avaValue->data, valueLen);
1053         end[0] = '\0';
1054         if (truncateValue) {
1055             end[-1] = '.';
1056             end[-2] = '.';
1057             end[-3] = '.';
1058         }
1059         rv = SECSuccess;
1060     } else if (!truncateValue) {
1061         rv = escapeAndQuote(encodedAVA + nameLen, len - nameLen, 
1062                             (char *)avaValue->data, avaValue->len, &mode);
1063     } else {
1064         /* must truncate the escaped and quoted value */
1065         char bigTmpBuf[TMPBUF_LEN * 3 + 3];
1066         rv = escapeAndQuote(bigTmpBuf, sizeof bigTmpBuf,
1067                             (char *)avaValue->data, valueLen, &mode);
1068
1069         bigTmpBuf[valueLen--] = '\0'; /* hard stop here */
1070         /* See if we're in the middle of a multi-byte UTF8 character */
1071         while (((bigTmpBuf[valueLen] & 0xc0) == 0x80) && valueLen > 0) {
1072             bigTmpBuf[valueLen--] = '\0';
1073         }
1074         /* add ellipsis to signify truncation. */
1075         bigTmpBuf[++valueLen] = '.';
1076         bigTmpBuf[++valueLen] = '.';
1077         bigTmpBuf[++valueLen] = '.';
1078         if (bigTmpBuf[0] == '"')
1079             bigTmpBuf[++valueLen] = '"';
1080         bigTmpBuf[++valueLen] = '\0';
1081         PORT_Assert(nameLen + valueLen <= (sizeof tmpBuf) - 1);
1082         memcpy(encodedAVA + nameLen, bigTmpBuf, valueLen+1);
1083     }
1084
1085     SECITEM_FreeItem(avaValue, PR_TRUE);
1086     if (rv == SECSuccess)
1087         rv = AppendStr(bufp, encodedAVA);
1088     if (encodedAVA != tmpBuf)
1089         PORT_Free(encodedAVA);
1090     return rv;
1091 }
1092
1093 #undef tagName
1094 #undef maxBytes
1095 #undef tag
1096 #undef vt
1097
1098 char *
1099 CERT_NameToAsciiInvertible(CERTName *name, CertStrictnessLevel strict)
1100 {
1101     CERTRDN** rdns;
1102     CERTRDN** lastRdn;
1103     CERTRDN** rdn;
1104     PRBool first = PR_TRUE;
1105     stringBuf strBuf = { NULL, 0, 0 };
1106     
1107     rdns = name->rdns;
1108     if (rdns == NULL) {
1109         return NULL;
1110     }
1111     
1112     /* find last RDN */
1113     lastRdn = rdns;
1114     while (*lastRdn) lastRdn++;
1115     lastRdn--;
1116     
1117     /*
1118      * Loop over name contents in _reverse_ RDN order appending to string
1119      */
1120     for (rdn = lastRdn; rdn >= rdns; rdn--) {
1121         CERTAVA** avas = (*rdn)->avas;
1122         CERTAVA* ava;
1123         PRBool newRDN = PR_TRUE;
1124
1125         /* 
1126          * XXX Do we need to traverse the AVAs in reverse order, too?
1127          */
1128         while (avas && (ava = *avas++) != NULL) {
1129             SECStatus rv;
1130             /* Put in comma or plus separator */
1131             if (!first) {
1132                 /* Use of spaces is deprecated in RFC 2253. */
1133                 rv = AppendStr(&strBuf, newRDN ? "," : "+");
1134                 if (rv) goto loser;
1135             } else {
1136                 first = PR_FALSE;
1137             }
1138             
1139             /* Add in tag type plus value into strBuf */
1140             rv = AppendAVA(&strBuf, ava, strict);
1141             if (rv) goto loser;
1142             newRDN = PR_FALSE;
1143         }
1144     }
1145     return strBuf.buffer;
1146 loser:
1147     if (strBuf.buffer) {
1148         PORT_Free(strBuf.buffer);
1149     }
1150     return NULL;
1151 }
1152
1153 char *
1154 CERT_NameToAscii(CERTName *name)
1155 {
1156     return CERT_NameToAsciiInvertible(name, CERT_N2A_READABLE);
1157 }
1158
1159 /*
1160  * Return the string representation of a DER encoded distinguished name
1161  * "dername" - The DER encoded name to convert
1162  */
1163 char *
1164 CERT_DerNameToAscii(SECItem *dername)
1165 {
1166     int rv;
1167     PRArenaPool *arena = NULL;
1168     CERTName name;
1169     char *retstr = NULL;
1170     
1171     arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
1172     
1173     if ( arena == NULL) {
1174         goto loser;
1175     }
1176     
1177     rv = SEC_QuickDERDecodeItem(arena, &name, CERT_NameTemplate, dername);
1178     
1179     if ( rv != SECSuccess ) {
1180         goto loser;
1181     }
1182
1183     retstr = CERT_NameToAscii(&name);
1184
1185 loser:
1186     if ( arena != NULL ) {
1187         PORT_FreeArena(arena, PR_FALSE);
1188     }
1189     
1190     return(retstr);
1191 }
1192
1193 static char *
1194 avaToString(PRArenaPool *arena, CERTAVA *ava)
1195 {
1196     char *    buf       = NULL;
1197     SECItem*  avaValue;
1198     int       valueLen;
1199
1200     avaValue = CERT_DecodeAVAValue(&ava->value);
1201     if(!avaValue) {
1202         return buf;
1203     }
1204     valueLen = cert_RFC1485_GetRequiredLen((char *)avaValue->data,
1205                                            avaValue->len, NULL) + 1;
1206     if (arena) {
1207         buf = (char *)PORT_ArenaZAlloc(arena, valueLen);
1208     } else {
1209         buf = (char *)PORT_ZAlloc(valueLen);
1210     }
1211     if (buf) {
1212         SECStatus rv = escapeAndQuote(buf, valueLen, (char *)avaValue->data, 
1213                                       avaValue->len, NULL);
1214         if (rv != SECSuccess) {
1215             if (!arena)
1216                 PORT_Free(buf);
1217             buf = NULL;
1218         }
1219     }
1220     SECITEM_FreeItem(avaValue, PR_TRUE);
1221     return buf;
1222 }
1223
1224 /* RDNs are sorted from most general to most specific.
1225  * This code returns the FIRST one found, the most general one found.
1226  */
1227 static char *
1228 CERT_GetNameElement(PRArenaPool *arena, CERTName *name, int wantedTag)
1229 {
1230     CERTRDN** rdns = name->rdns;
1231     CERTRDN*  rdn;
1232     CERTAVA*  ava  = NULL;
1233
1234     while (rdns && (rdn = *rdns++) != 0) {
1235         CERTAVA** avas = rdn->avas;
1236         while (avas && (ava = *avas++) != 0) {
1237             int tag = CERT_GetAVATag(ava);
1238             if ( tag == wantedTag ) {
1239                 avas = NULL;
1240                 rdns = NULL; /* break out of all loops */
1241             }
1242         }
1243     }
1244     return ava ? avaToString(arena, ava) : NULL;
1245 }
1246
1247 /* RDNs are sorted from most general to most specific.
1248  * This code returns the LAST one found, the most specific one found.
1249  * This is particularly appropriate for Common Name.  See RFC 2818.
1250  */
1251 static char *
1252 CERT_GetLastNameElement(PRArenaPool *arena, CERTName *name, int wantedTag)
1253 {
1254     CERTRDN** rdns    = name->rdns;
1255     CERTRDN*  rdn;
1256     CERTAVA*  lastAva = NULL;
1257     
1258     while (rdns && (rdn = *rdns++) != 0) {
1259         CERTAVA** avas = rdn->avas;
1260         CERTAVA*  ava;
1261         while (avas && (ava = *avas++) != 0) {
1262             int tag = CERT_GetAVATag(ava);
1263             if ( tag == wantedTag ) {
1264                 lastAva = ava;
1265             }
1266         }
1267     }
1268     return lastAva ? avaToString(arena, lastAva) : NULL;
1269 }
1270
1271 char *
1272 CERT_GetCertificateEmailAddress(CERTCertificate *cert)
1273 {
1274     char *rawEmailAddr = NULL;
1275     SECItem subAltName;
1276     SECStatus rv;
1277     CERTGeneralName *nameList = NULL;
1278     CERTGeneralName *current;
1279     PRArenaPool *arena = NULL;
1280     int i;
1281     
1282     subAltName.data = NULL;
1283
1284     rawEmailAddr = CERT_GetNameElement(cert->arena, &(cert->subject),
1285                                                  SEC_OID_PKCS9_EMAIL_ADDRESS);
1286     if ( rawEmailAddr == NULL ) {
1287         rawEmailAddr = CERT_GetNameElement(cert->arena, &(cert->subject), 
1288                                                         SEC_OID_RFC1274_MAIL);
1289     }
1290     if ( rawEmailAddr == NULL) {
1291
1292         rv = CERT_FindCertExtension(cert,  SEC_OID_X509_SUBJECT_ALT_NAME, 
1293                                                                 &subAltName);
1294         if (rv != SECSuccess) {
1295             goto finish;
1296         }
1297         arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
1298         if (!arena) {
1299             goto finish;
1300         }
1301         nameList = current = CERT_DecodeAltNameExtension(arena, &subAltName);
1302         if (!nameList ) {
1303             goto finish;
1304         }
1305         if (nameList != NULL) {
1306             do {
1307                 if (current->type == certDirectoryName) {
1308                     rawEmailAddr = CERT_GetNameElement(cert->arena,
1309                         &(current->name.directoryName), 
1310                                                SEC_OID_PKCS9_EMAIL_ADDRESS);
1311                     if ( rawEmailAddr == NULL ) {
1312                         rawEmailAddr = CERT_GetNameElement(cert->arena,
1313                           &(current->name.directoryName), SEC_OID_RFC1274_MAIL);
1314                     }
1315                 } else if (current->type == certRFC822Name) {
1316                     rawEmailAddr = (char*)PORT_ArenaZAlloc(cert->arena,
1317                                                 current->name.other.len + 1);
1318                     if (!rawEmailAddr) {
1319                         goto finish;
1320                     }
1321                     PORT_Memcpy(rawEmailAddr, current->name.other.data, 
1322                                 current->name.other.len);
1323                     rawEmailAddr[current->name.other.len] = '\0';
1324                 }
1325                 if (rawEmailAddr) {
1326                     break;
1327                 }
1328                 current = CERT_GetNextGeneralName(current);
1329             } while (current != nameList);
1330         }
1331     }
1332     if (rawEmailAddr) {
1333         for (i = 0; i <= (int) PORT_Strlen(rawEmailAddr); i++) {
1334             rawEmailAddr[i] = tolower(rawEmailAddr[i]);
1335         }
1336     } 
1337
1338 finish:
1339
1340     /* Don't free nameList, it's part of the arena. */
1341
1342     if (arena) {
1343         PORT_FreeArena(arena, PR_FALSE);
1344     }
1345
1346     if ( subAltName.data ) {
1347         SECITEM_FreeItem(&subAltName, PR_FALSE);
1348     }
1349
1350     return(rawEmailAddr);
1351 }
1352
1353 static char *
1354 appendStringToBuf(char *dest, char *src, PRUint32 *pRemaining)
1355 {
1356     PRUint32 len;
1357     if (dest && src && src[0] && *pRemaining > (len = PL_strlen(src))) {
1358         PRUint32 i;
1359         for (i = 0; i < len; ++i)
1360             dest[i] = tolower(src[i]);
1361         dest[len] = 0;
1362         dest        += len + 1;
1363         *pRemaining -= len + 1;
1364     }
1365     return dest;
1366 }
1367
1368 #undef NEEDS_HEX_ESCAPE
1369 #define NEEDS_HEX_ESCAPE(c) (c < 0x20)
1370
1371 static char *
1372 appendItemToBuf(char *dest, SECItem *src, PRUint32 *pRemaining)
1373 {
1374     if (dest && src && src->data && src->len && src->data[0]) {
1375         PRUint32 len = src->len;
1376         PRUint32 i;
1377         PRUint32 reqLen = len + 1;
1378         /* are there any embedded control characters ? */
1379         for (i = 0; i < len; i++) {
1380             if (NEEDS_HEX_ESCAPE(src->data[i]))
1381                 reqLen += 2;   
1382         }
1383         if (*pRemaining > reqLen) {
1384             for (i = 0; i < len; ++i) {
1385                 PRUint8 c = src->data[i];
1386                 if (NEEDS_HEX_ESCAPE(c)) {
1387                     *dest++ = C_BACKSLASH;
1388                     *dest++ = hexChars[ (c >> 4) & 0x0f ];
1389                     *dest++ = hexChars[  c       & 0x0f ];
1390                 } else {
1391                     *dest++ = tolower(c);
1392                 }
1393             }
1394             *dest++ = '\0';
1395             *pRemaining -= reqLen;
1396         }
1397     }
1398     return dest;
1399 }
1400
1401 /* Returns a pointer to an environment-like string, a series of 
1402 ** null-terminated strings, terminated by a zero-length string.
1403 ** This function is intended to be internal to NSS.
1404 */
1405 char *
1406 cert_GetCertificateEmailAddresses(CERTCertificate *cert)
1407 {
1408     char *           rawEmailAddr = NULL;
1409     char *           addrBuf      = NULL;
1410     char *           pBuf         = NULL;
1411     PRArenaPool *    tmpArena     = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
1412     PRUint32         maxLen       = 0;
1413     PRInt32          finalLen     = 0;
1414     SECStatus        rv;
1415     SECItem          subAltName;
1416     
1417     if (!tmpArena) 
1418         return addrBuf;
1419
1420     subAltName.data = NULL;
1421     maxLen = cert->derCert.len;
1422     PORT_Assert(maxLen);
1423     if (!maxLen) 
1424         maxLen = 2000;  /* a guess, should never happen */
1425
1426     pBuf = addrBuf = (char *)PORT_ArenaZAlloc(tmpArena, maxLen + 1);
1427     if (!addrBuf) 
1428         goto loser;
1429
1430     rawEmailAddr = CERT_GetNameElement(tmpArena, &cert->subject,
1431                                        SEC_OID_PKCS9_EMAIL_ADDRESS);
1432     pBuf = appendStringToBuf(pBuf, rawEmailAddr, &maxLen);
1433
1434     rawEmailAddr = CERT_GetNameElement(tmpArena, &cert->subject, 
1435                                        SEC_OID_RFC1274_MAIL);
1436     pBuf = appendStringToBuf(pBuf, rawEmailAddr, &maxLen);
1437
1438     rv = CERT_FindCertExtension(cert,  SEC_OID_X509_SUBJECT_ALT_NAME, 
1439                                 &subAltName);
1440     if (rv == SECSuccess && subAltName.data) {
1441         CERTGeneralName *nameList     = NULL;
1442
1443         if (!!(nameList = CERT_DecodeAltNameExtension(tmpArena, &subAltName))) {
1444             CERTGeneralName *current = nameList;
1445             do {
1446                 if (current->type == certDirectoryName) {
1447                     rawEmailAddr = CERT_GetNameElement(tmpArena,
1448                                                &current->name.directoryName, 
1449                                                SEC_OID_PKCS9_EMAIL_ADDRESS);
1450                     pBuf = appendStringToBuf(pBuf, rawEmailAddr, &maxLen);
1451
1452                     rawEmailAddr = CERT_GetNameElement(tmpArena,
1453                                               &current->name.directoryName, 
1454                                               SEC_OID_RFC1274_MAIL);
1455                     pBuf = appendStringToBuf(pBuf, rawEmailAddr, &maxLen);
1456                 } else if (current->type == certRFC822Name) {
1457                     pBuf = appendItemToBuf(pBuf, &current->name.other, &maxLen);
1458                 }
1459                 current = CERT_GetNextGeneralName(current);
1460             } while (current != nameList);
1461         }
1462         SECITEM_FreeItem(&subAltName, PR_FALSE);
1463         /* Don't free nameList, it's part of the tmpArena. */
1464     }
1465     /* now copy superstring to cert's arena */
1466     finalLen = (pBuf - addrBuf) + 1;
1467     pBuf = NULL;
1468     if (finalLen > 1) {
1469         pBuf = PORT_ArenaAlloc(cert->arena, finalLen);
1470         if (pBuf) {
1471             PORT_Memcpy(pBuf, addrBuf, finalLen);
1472         }
1473     }
1474 loser:
1475     if (tmpArena)
1476         PORT_FreeArena(tmpArena, PR_FALSE);
1477
1478     return pBuf;
1479 }
1480
1481 /* returns pointer to storage in cert's arena.  Storage remains valid
1482 ** as long as cert's reference count doesn't go to zero.
1483 ** Caller should strdup or otherwise copy.
1484 */
1485 const char *    /* const so caller won't muck with it. */
1486 CERT_GetFirstEmailAddress(CERTCertificate * cert)
1487 {
1488     if (cert && cert->emailAddr && cert->emailAddr[0])
1489         return (const char *)cert->emailAddr;
1490     return NULL;
1491 }
1492
1493 /* returns pointer to storage in cert's arena.  Storage remains valid
1494 ** as long as cert's reference count doesn't go to zero.
1495 ** Caller should strdup or otherwise copy.
1496 */
1497 const char *    /* const so caller won't muck with it. */
1498 CERT_GetNextEmailAddress(CERTCertificate * cert, const char * prev)
1499 {
1500     if (cert && prev && prev[0]) {
1501         PRUint32 len = PL_strlen(prev);
1502         prev += len + 1;
1503         if (prev && prev[0])
1504             return prev;
1505     }
1506     return NULL;
1507 }
1508
1509 /* This is seriously bogus, now that certs store their email addresses in
1510 ** subject Alternative Name extensions. 
1511 ** Returns a string allocated by PORT_StrDup, which the caller must free.
1512 */
1513 char *
1514 CERT_GetCertEmailAddress(CERTName *name)
1515 {
1516     char *rawEmailAddr;
1517     char *emailAddr;
1518
1519     
1520     rawEmailAddr = CERT_GetNameElement(NULL, name, SEC_OID_PKCS9_EMAIL_ADDRESS);
1521     if ( rawEmailAddr == NULL ) {
1522         rawEmailAddr = CERT_GetNameElement(NULL, name, SEC_OID_RFC1274_MAIL);
1523     }
1524     emailAddr = CERT_FixupEmailAddr(rawEmailAddr);
1525     if ( rawEmailAddr ) {
1526         PORT_Free(rawEmailAddr);
1527     }
1528     return(emailAddr);
1529 }
1530
1531 /* The return value must be freed with PORT_Free. */
1532 char *
1533 CERT_GetCommonName(CERTName *name)
1534 {
1535     return(CERT_GetLastNameElement(NULL, name, SEC_OID_AVA_COMMON_NAME));
1536 }
1537
1538 char *
1539 CERT_GetCountryName(CERTName *name)
1540 {
1541     return(CERT_GetNameElement(NULL, name, SEC_OID_AVA_COUNTRY_NAME));
1542 }
1543
1544 char *
1545 CERT_GetLocalityName(CERTName *name)
1546 {
1547     return(CERT_GetNameElement(NULL, name, SEC_OID_AVA_LOCALITY));
1548 }
1549
1550 char *
1551 CERT_GetStateName(CERTName *name)
1552 {
1553     return(CERT_GetNameElement(NULL, name, SEC_OID_AVA_STATE_OR_PROVINCE));
1554 }
1555
1556 char *
1557 CERT_GetOrgName(CERTName *name)
1558 {
1559     return(CERT_GetNameElement(NULL, name, SEC_OID_AVA_ORGANIZATION_NAME));
1560 }
1561
1562 char *
1563 CERT_GetDomainComponentName(CERTName *name)
1564 {
1565     return(CERT_GetNameElement(NULL, name, SEC_OID_AVA_DC));
1566 }
1567
1568 char *
1569 CERT_GetOrgUnitName(CERTName *name)
1570 {
1571     return(CERT_GetNameElement(NULL, name, SEC_OID_AVA_ORGANIZATIONAL_UNIT_NAME));
1572 }
1573
1574 char *
1575 CERT_GetDnQualifier(CERTName *name)
1576 {
1577     return(CERT_GetNameElement(NULL, name, SEC_OID_AVA_DN_QUALIFIER));
1578 }
1579
1580 char *
1581 CERT_GetCertUid(CERTName *name)
1582 {
1583     return(CERT_GetNameElement(NULL, name, SEC_OID_RFC1274_UID));
1584 }
1585