7ddb7662f1e54f703781c03bae69b019f6dc6d5d
[openssl.git] / crypto / asn1 / a_strex.c
1 /* a_strex.c */
2 /* Written by Dr Stephen N Henson (shenson@bigfoot.com) for the OpenSSL
3  * project 2000.
4  */
5 /* ====================================================================
6  * Copyright (c) 2000 The OpenSSL Project.  All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  *
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer. 
14  *
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in
17  *    the documentation and/or other materials provided with the
18  *    distribution.
19  *
20  * 3. All advertising materials mentioning features or use of this
21  *    software must display the following acknowledgment:
22  *    "This product includes software developed by the OpenSSL Project
23  *    for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
24  *
25  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
26  *    endorse or promote products derived from this software without
27  *    prior written permission. For written permission, please contact
28  *    licensing@OpenSSL.org.
29  *
30  * 5. Products derived from this software may not be called "OpenSSL"
31  *    nor may "OpenSSL" appear in their names without prior written
32  *    permission of the OpenSSL Project.
33  *
34  * 6. Redistributions of any form whatsoever must retain the following
35  *    acknowledgment:
36  *    "This product includes software developed by the OpenSSL Project
37  *    for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
38  *
39  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
40  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
41  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
42  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
43  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
44  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
45  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
46  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
48  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
49  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
50  * OF THE POSSIBILITY OF SUCH DAMAGE.
51  * ====================================================================
52  *
53  * This product includes cryptographic software written by Eric Young
54  * (eay@cryptsoft.com).  This product includes software written by Tim
55  * Hudson (tjh@cryptsoft.com).
56  *
57  */
58
59 #include <stdio.h>
60 #include <string.h>
61 #include <openssl/crypto.h>
62 #include <openssl/x509.h>
63 #include <openssl/asn1.h>
64
65 #include "charmap.h"
66
67 /* ASN1_STRING_print_ex() and X509_NAME_print_ex().
68  * Enhanced string and name printing routines handling
69  * multibyte characters, RFC2253 and a host of other
70  * options.
71  */
72
73
74 #define CHARTYPE_BS_ESC         (ASN1_STRFLGS_ESC_2253 | CHARTYPE_FIRST_ESC_2253 | CHARTYPE_LAST_ESC_2253)
75
76
77 /* Three IO functions for sending data to memory, a BIO and
78  * and a FILE pointer.
79  */
80 #if 0                           /* never used */
81 static int send_mem_chars(void *arg, const void *buf, int len)
82 {
83         unsigned char **out = arg;
84         if(!out) return 1;
85         memcpy(*out, buf, len);
86         *out += len;
87         return 1;
88 }
89 #endif
90
91 static int send_bio_chars(void *arg, const void *buf, int len)
92 {
93         if(!arg) return 1;
94         if(BIO_write(arg, buf, len) != len) return 0;
95         return 1;
96 }
97
98 static int send_fp_chars(void *arg, const void *buf, int len)
99 {
100         if(!arg) return 1;
101         if(fwrite(buf, 1, len, arg) != (unsigned int)len) return 0;
102         return 1;
103 }
104
105 typedef int char_io(void *arg, const void *buf, int len);
106
107 /* This function handles display of
108  * strings, one character at a time.
109  * It is passed an unsigned long for each
110  * character because it could come from 2 or even
111  * 4 byte forms.
112  */
113
114 static int do_esc_char(unsigned long c, unsigned char flags, char *do_quotes, char_io *io_ch, void *arg)
115 {
116         unsigned char chflgs, chtmp;
117         char tmphex[11];
118         if(c > 0xffff) {
119                 BIO_snprintf(tmphex, 11, "\\W%08lX", c);
120                 if(!io_ch(arg, tmphex, 10)) return -1;
121                 return 10;
122         }
123         if(c > 0xff) {
124                 BIO_snprintf(tmphex, 11, "\\U%04lX", c);
125                 if(!io_ch(arg, tmphex, 6)) return -1;
126                 return 6;
127         }
128         chtmp = (unsigned char)c;
129         if(chtmp > 0x7f) chflgs = flags & ASN1_STRFLGS_ESC_MSB;
130         else chflgs = char_type[chtmp] & flags;
131         if(chflgs & CHARTYPE_BS_ESC) {
132                 /* If we don't escape with quotes, signal we need quotes */
133                 if(chflgs & ASN1_STRFLGS_ESC_QUOTE) {
134                         if(do_quotes) *do_quotes = 1;
135                         if(!io_ch(arg, &chtmp, 1)) return -1;
136                         return 1;
137                 }
138                 if(!io_ch(arg, "\\", 1)) return -1;
139                 if(!io_ch(arg, &chtmp, 1)) return -1;
140                 return 2;
141         }
142         if(chflgs & (ASN1_STRFLGS_ESC_CTRL|ASN1_STRFLGS_ESC_MSB)) {
143                 BIO_snprintf(tmphex, 11, "\\%02X", chtmp);
144                 if(!io_ch(arg, tmphex, 3)) return -1;
145                 return 3;
146         }
147         if(!io_ch(arg, &chtmp, 1)) return -1;
148         return 1;
149 }
150
151 #define BUF_TYPE_WIDTH_MASK     0x7
152 #define BUF_TYPE_CONVUTF8       0x8
153
154 /* This function sends each character in a buffer to
155  * do_esc_char(). It interprets the content formats
156  * and converts to or from UTF8 as appropriate.
157  */
158
159 static int do_buf(unsigned char *buf, int buflen,
160                         int type, unsigned char flags, char *quotes, char_io *io_ch, void *arg)
161 {
162         int i, outlen, len;
163         unsigned char orflags, *p, *q;
164         unsigned long c;
165         p = buf;
166         q = buf + buflen;
167         outlen = 0;
168         while(p != q) {
169                 if(p == buf) orflags = CHARTYPE_FIRST_ESC_2253;
170                 else orflags = 0;
171                 switch(type & BUF_TYPE_WIDTH_MASK) {
172                         case 4:
173                         c = ((unsigned long)*p++) << 24;
174                         c |= ((unsigned long)*p++) << 16;
175                         c |= ((unsigned long)*p++) << 8;
176                         c |= *p++;
177                         break;
178
179                         case 2:
180                         c = ((unsigned long)*p++) << 8;
181                         c |= *p++;
182                         break;
183
184                         case 1:
185                         c = *p++;
186                         break;
187                         
188                         case 0:
189                         i = UTF8_getc(p, buflen, &c);
190                         if(i < 0) return -1;    /* Invalid UTF8String */
191                         p += i;
192                         break;
193                 }
194                 if (p == q) orflags = CHARTYPE_LAST_ESC_2253;
195                 if(type & BUF_TYPE_CONVUTF8) {
196                         unsigned char utfbuf[6];
197                         int utflen;
198                         utflen = UTF8_putc(utfbuf, 6, c);
199                         for(i = 0; i < utflen; i++) {
200                                 /* We don't need to worry about setting orflags correctly
201                                  * because if utflen==1 its value will be correct anyway 
202                                  * otherwise each character will be > 0x7f and so the 
203                                  * character will never be escaped on first and last.
204                                  */
205                                 len = do_esc_char(utfbuf[i], (unsigned char)(flags | orflags), quotes, io_ch, arg);
206                                 if(len < 0) return -1;
207                                 outlen += len;
208                         }
209                 } else {
210                         len = do_esc_char(c, (unsigned char)(flags | orflags), quotes, io_ch, arg);
211                         if(len < 0) return -1;
212                         outlen += len;
213                 }
214         }
215         return outlen;
216 }
217
218 /* This function hex dumps a buffer of characters */
219
220 static int do_hex_dump(char_io *io_ch, void *arg, unsigned char *buf, int buflen)
221 {
222         const static char hexdig[] = "0123456789ABCDEF";
223         unsigned char *p, *q;
224         char hextmp[2];
225         if(arg) {
226                 p = buf;
227                 q = buf + buflen;
228                 while(p != q) {
229                         hextmp[0] = hexdig[*p >> 4];
230                         hextmp[1] = hexdig[*p & 0xf];
231                         if(!io_ch(arg, hextmp, 2)) return -1;
232                         p++;
233                 }
234         }
235         return buflen << 1;
236 }
237
238 /* "dump" a string. This is done when the type is unknown,
239  * or the flags request it. We can either dump the content
240  * octets or the entire DER encoding. This uses the RFC2253
241  * #01234 format.
242  */
243
244 static int do_dump(unsigned long lflags, char_io *io_ch, void *arg, ASN1_STRING *str)
245 {
246         /* Placing the ASN1_STRING in a temp ASN1_TYPE allows
247          * the DER encoding to readily obtained
248          */
249         ASN1_TYPE t;
250         unsigned char *der_buf, *p;
251         int outlen, der_len;
252
253         if(!io_ch(arg, "#", 1)) return -1;
254         /* If we don't dump DER encoding just dump content octets */
255         if(!(lflags & ASN1_STRFLGS_DUMP_DER)) {
256                 outlen = do_hex_dump(io_ch, arg, str->data, str->length);
257                 if(outlen < 0) return -1;
258                 return outlen + 1;
259         }
260         t.type = str->type;
261         t.value.ptr = (char *)str;
262         der_len = i2d_ASN1_TYPE(&t, NULL);
263         der_buf = OPENSSL_malloc(der_len);
264         if(!der_buf) return -1;
265         p = der_buf;
266         i2d_ASN1_TYPE(&t, &p);
267         outlen = do_hex_dump(io_ch, arg, der_buf, der_len);
268         OPENSSL_free(der_buf);
269         if(outlen < 0) return -1;
270         return outlen + 1;
271 }
272
273 /* Lookup table to convert tags to character widths,
274  * 0 = UTF8 encoded, -1 is used for non string types
275  * otherwise it is the number of bytes per character
276  */
277
278 const static char tag2nbyte[] = {
279         -1, -1, -1, -1, -1,     /* 0-4 */
280         -1, -1, -1, -1, -1,     /* 5-9 */
281         -1, -1, 0, -1,          /* 10-13 */
282         -1, -1, -1, -1,         /* 15-17 */
283         -1, 1, 1,               /* 18-20 */
284         -1, 1, -1,-1,           /* 21-24 */
285         -1, 1, -1,              /* 25-27 */
286         4, -1, 2                /* 28-30 */
287 };
288
289 #define ESC_FLAGS (ASN1_STRFLGS_ESC_2253 | \
290                   ASN1_STRFLGS_ESC_QUOTE | \
291                   ASN1_STRFLGS_ESC_CTRL | \
292                   ASN1_STRFLGS_ESC_MSB)
293
294 /* This is the main function, print out an
295  * ASN1_STRING taking note of various escape
296  * and display options. Returns number of
297  * characters written or -1 if an error
298  * occurred.
299  */
300
301 static int do_print_ex(char_io *io_ch, void *arg, unsigned long lflags, ASN1_STRING *str)
302 {
303         int outlen, len;
304         int type;
305         char quotes;
306         unsigned char flags;
307         quotes = 0;
308         /* Keep a copy of escape flags */
309         flags = (unsigned char)(lflags & ESC_FLAGS);
310
311         type = str->type;
312
313         outlen = 0;
314
315
316         if(lflags & ASN1_STRFLGS_SHOW_TYPE) {
317                 const char *tagname;
318                 tagname = ASN1_tag2str(type);
319                 outlen += strlen(tagname);
320                 if(!io_ch(arg, tagname, outlen) || !io_ch(arg, ":", 1)) return -1; 
321                 outlen++;
322         }
323
324         /* Decide what to do with type, either dump content or display it */
325
326         /* Dump everything */
327         if(lflags & ASN1_STRFLGS_DUMP_ALL) type = -1;
328         /* Ignore the string type */
329         else if(lflags & ASN1_STRFLGS_IGNORE_TYPE) type = 1;
330         else {
331                 /* Else determine width based on type */
332                 if((type > 0) && (type < 31)) type = tag2nbyte[type];
333                 else type = -1;
334                 if((type == -1) && !(lflags & ASN1_STRFLGS_DUMP_UNKNOWN)) type = 1;
335         }
336
337         if(type == -1) {
338                 len = do_dump(lflags, io_ch, arg, str);
339                 if(len < 0) return -1;
340                 outlen += len;
341                 return outlen;
342         }
343
344         if(lflags & ASN1_STRFLGS_UTF8_CONVERT) {
345                 /* Note: if string is UTF8 and we want
346                  * to convert to UTF8 then we just interpret
347                  * it as 1 byte per character to avoid converting
348                  * twice.
349                  */
350                 if(!type) type = 1;
351                 else type |= BUF_TYPE_CONVUTF8;
352         }
353
354         len = do_buf(str->data, str->length, type, flags, &quotes, io_ch, NULL);
355         if(outlen < 0) return -1;
356         outlen += len;
357         if(quotes) outlen += 2;
358         if(!arg) return outlen;
359         if(quotes && !io_ch(arg, "\"", 1)) return -1;
360         do_buf(str->data, str->length, type, flags, NULL, io_ch, arg);
361         if(quotes && !io_ch(arg, "\"", 1)) return -1;
362         return outlen;
363 }
364
365 /* Used for line indenting: print 'indent' spaces */
366
367 static int do_indent(char_io *io_ch, void *arg, int indent)
368 {
369         int i;
370         for(i = 0; i < indent; i++)
371                         if(!io_ch(arg, " ", 1)) return 0;
372         return 1;
373 }
374
375 #define FN_WIDTH_LN     25
376 #define FN_WIDTH_SN     10
377
378 static int do_name_ex(char_io *io_ch, void *arg, X509_NAME *n,
379                                 int indent, unsigned long flags)
380 {
381         int i, prev = -1, orflags, cnt;
382         int fn_opt, fn_nid;
383         ASN1_OBJECT *fn;
384         ASN1_STRING *val;
385         X509_NAME_ENTRY *ent;
386         char objtmp[80];
387         const char *objbuf;
388         int outlen, len;
389         char *sep_dn, *sep_mv, *sep_eq;
390         int sep_dn_len, sep_mv_len, sep_eq_len;
391         if(indent < 0) indent = 0;
392         outlen = indent;
393         if(!do_indent(io_ch, arg, indent)) return -1;
394         switch (flags & XN_FLAG_SEP_MASK)
395         {
396                 case XN_FLAG_SEP_MULTILINE:
397                 sep_dn = "\n";
398                 sep_dn_len = 1;
399                 sep_mv = " + ";
400                 sep_mv_len = 3;
401                 break;
402
403                 case XN_FLAG_SEP_COMMA_PLUS:
404                 sep_dn = ",";
405                 sep_dn_len = 1;
406                 sep_mv = "+";
407                 sep_mv_len = 1;
408                 indent = 0;
409                 break;
410
411                 case XN_FLAG_SEP_CPLUS_SPC:
412                 sep_dn = ", ";
413                 sep_dn_len = 2;
414                 sep_mv = " + ";
415                 sep_mv_len = 3;
416                 indent = 0;
417                 break;
418
419                 case XN_FLAG_SEP_SPLUS_SPC:
420                 sep_dn = "; ";
421                 sep_dn_len = 2;
422                 sep_mv = " + ";
423                 sep_mv_len = 3;
424                 indent = 0;
425                 break;
426
427                 default:
428                 return -1;
429         }
430
431         if(flags & XN_FLAG_SPC_EQ) {
432                 sep_eq = " = ";
433                 sep_eq_len = 3;
434         } else {
435                 sep_eq = "=";
436                 sep_eq_len = 1;
437         }
438
439         fn_opt = flags & XN_FLAG_FN_MASK;
440
441         cnt = X509_NAME_entry_count(n); 
442         for(i = 0; i < cnt; i++) {
443                 if(flags & XN_FLAG_DN_REV)
444                                 ent = X509_NAME_get_entry(n, cnt - i - 1);
445                 else ent = X509_NAME_get_entry(n, i);
446                 if(prev != -1) {
447                         if(prev == ent->set) {
448                                 if(!io_ch(arg, sep_mv, sep_mv_len)) return -1;
449                                 outlen += sep_mv_len;
450                         } else {
451                                 if(!io_ch(arg, sep_dn, sep_dn_len)) return -1;
452                                 outlen += sep_dn_len;
453                                 if(!do_indent(io_ch, arg, indent)) return -1;
454                                 outlen += indent;
455                         }
456                 }
457                 prev = ent->set;
458                 fn = X509_NAME_ENTRY_get_object(ent);
459                 val = X509_NAME_ENTRY_get_data(ent);
460                 fn_nid = OBJ_obj2nid(fn);
461                 if(fn_opt != XN_FLAG_FN_NONE) {
462                         int objlen, fld_len;
463                         if((fn_opt == XN_FLAG_FN_OID) || (fn_nid==NID_undef) ) {
464                                 OBJ_obj2txt(objtmp, 80, fn, 1);
465                                 fld_len = 0; /* XXX: what should this be? */
466                                 objbuf = objtmp;
467                         } else {
468                                 if(fn_opt == XN_FLAG_FN_SN) {
469                                         fld_len = FN_WIDTH_SN;
470                                         objbuf = OBJ_nid2sn(fn_nid);
471                                 } else if(fn_opt == XN_FLAG_FN_LN) {
472                                         fld_len = FN_WIDTH_LN;
473                                         objbuf = OBJ_nid2ln(fn_nid);
474                                 } else {
475                                         fld_len = 0; /* XXX: what should this be? */
476                                         objbuf = "";
477                                 }
478                         }
479                         objlen = strlen(objbuf);
480                         if(!io_ch(arg, objbuf, objlen)) return -1;
481                         if ((objlen < fld_len) && (flags & XN_FLAG_FN_ALIGN)) {
482                                 if (!do_indent(io_ch, arg, fld_len - objlen)) return -1;
483                                 outlen += fld_len - objlen;
484                         }
485                         if(!io_ch(arg, sep_eq, sep_eq_len)) return -1;
486                         outlen += objlen + sep_eq_len;
487                 }
488                 /* If the field name is unknown then fix up the DER dump
489                  * flag. We might want to limit this further so it will
490                  * DER dump on anything other than a few 'standard' fields.
491                  */
492                 if((fn_nid == NID_undef) && (flags & XN_FLAG_DUMP_UNKNOWN_FIELDS)) 
493                                         orflags = ASN1_STRFLGS_DUMP_ALL;
494                 else orflags = 0;
495      
496                 len = do_print_ex(io_ch, arg, flags | orflags, val);
497                 if(len < 0) return -1;
498                 outlen += len;
499         }
500         return outlen;
501 }
502
503 /* Wrappers round the main functions */
504
505 int X509_NAME_print_ex(BIO *out, X509_NAME *nm, int indent, unsigned long flags)
506 {
507         if(flags == XN_FLAG_COMPAT)
508                 return X509_NAME_print(out, nm, indent);
509         return do_name_ex(send_bio_chars, out, nm, indent, flags);
510 }
511
512
513 int X509_NAME_print_ex_fp(FILE *fp, X509_NAME *nm, int indent, unsigned long flags)
514 {
515         if(flags == XN_FLAG_COMPAT)
516                 {
517                 BIO *btmp;
518                 int ret;
519                 btmp = BIO_new_fp(fp, BIO_NOCLOSE);
520                 if(!btmp) return -1;
521                 ret = X509_NAME_print(btmp, nm, indent);
522                 BIO_free(btmp);
523                 return ret;
524                 }
525         return do_name_ex(send_fp_chars, fp, nm, indent, flags);
526 }
527
528 int ASN1_STRING_print_ex(BIO *out, ASN1_STRING *str, unsigned long flags)
529 {
530         return do_print_ex(send_bio_chars, out, flags, str);
531 }
532
533
534 int ASN1_STRING_print_ex_fp(FILE *fp, ASN1_STRING *str, unsigned long flags)
535 {
536         return do_print_ex(send_fp_chars, fp, flags, str);
537 }
538
539 /* Utility function: convert any string type to UTF8, returns number of bytes
540  * in output string or a negative error code
541  */
542
543 int ASN1_STRING_to_UTF8(unsigned char **out, ASN1_STRING *in)
544 {
545         ASN1_STRING stmp, *str = &stmp;
546         int mbflag, type, ret;
547         if(!in) return -1;
548         type = in->type;
549         if((type < 0) || (type > 30)) return -1;
550         mbflag = tag2nbyte[type];
551         if(mbflag == -1) return -1;
552         mbflag |= MBSTRING_FLAG;
553         stmp.data = NULL;
554         ret = ASN1_mbstring_copy(&str, in->data, in->length, mbflag, B_ASN1_UTF8STRING);
555         if(ret < 0) return ret;
556         *out = stmp.data;
557         return stmp.length;
558 }