af77b0919493f13d84689b3b9ec51dae475dae06
[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 <openssl/crypto.h>
61 #include <openssl/x509.h>
62 #include <openssl/asn1.h>
63
64 #include "charmap.h"
65
66 /* ASN1_STRING_print_ex() and X509_NAME_print_ex().
67  * Enhanced string and name printing routines handling
68  * multibyte characters, RFC2253 and a host of other
69  * options.
70  */
71
72
73 #define CHARTYPE_BS_ESC         (ASN1_STRFLGS_ESC_2253 | CHARTYPE_FIRST_ESC_2253 | CHARTYPE_LAST_ESC_2253)
74
75
76 /* Three IO functions for sending data to memory, a BIO and
77  * and a FILE pointer.
78  */
79
80 int send_mem_chars(void *arg, const void *buf, int len)
81 {
82         unsigned char **out = arg;
83         if(!out) return 1;
84         memcpy(*out, buf, len);
85         *out += len;
86         return 1;
87 }
88
89 int send_bio_chars(void *arg, const void *buf, int len)
90 {
91         if(!arg) return 1;
92         if(BIO_write(arg, buf, len) != len) return 0;
93         return 1;
94 }
95
96 int send_fp_chars(void *arg, const void *buf, int len)
97 {
98         if(!arg) return 1;
99         if(fwrite(buf, 1, len, arg) != (unsigned int)len) return 0;
100         return 1;
101 }
102
103 typedef int char_io(void *arg, const void *buf, int len);
104
105 /* This function handles display of
106  * strings, one character at a time.
107  * It is passed an unsigned long for each
108  * character because it could come from 2 or even
109  * 4 byte forms.
110  */
111
112 static int do_esc_char(unsigned long c, unsigned char flags, char *do_quotes, char_io *io_ch, void *arg)
113 {
114         unsigned char chflgs, chtmp;
115         char tmphex[11];
116         if(c > 0xffff) {
117                 BIO_snprintf(tmphex, 11, "\\W%08lX", c);
118                 if(!io_ch(arg, tmphex, 10)) return -1;
119                 return 10;
120         }
121         if(c > 0xff) {
122                 BIO_snprintf(tmphex, 11, "\\U%04lX", c);
123                 if(!io_ch(arg, tmphex, 6)) return -1;
124                 return 6;
125         }
126         chtmp = (unsigned char)c;
127         if(chtmp > 0x7f) chflgs = flags & ASN1_STRFLGS_ESC_MSB;
128         else chflgs = char_type[chtmp] & flags;
129         if(chflgs & CHARTYPE_BS_ESC) {
130                 /* If we don't escape with quotes, signal we need quotes */
131                 if(chflgs & ASN1_STRFLGS_ESC_QUOTE) {
132                         if(do_quotes) *do_quotes = 1;
133                         if(!io_ch(arg, &chtmp, 1)) return -1;
134                         return 1;
135                 }
136                 if(!io_ch(arg, "\\", 1)) return -1;
137                 if(!io_ch(arg, &chtmp, 1)) return -1;
138                 return 2;
139         }
140         if(chflgs & (ASN1_STRFLGS_ESC_CTRL|ASN1_STRFLGS_ESC_MSB)) {
141                 BIO_snprintf(tmphex, 11, "\\%02X", chtmp);
142                 if(!io_ch(arg, tmphex, 3)) return -1;
143                 return 3;
144         }
145         if(!io_ch(arg, &chtmp, 1)) return -1;
146         return 1;
147 }
148
149 #define BUF_TYPE_WIDTH_MASK     0x7
150 #define BUF_TYPE_CONVUTF8       0x8
151
152 /* This function sends each character in a buffer to
153  * do_esc_char(). It interprets the content formats
154  * and converts to or from UTF8 as appropriate.
155  */
156
157 static int do_buf(unsigned char *buf, int buflen,
158                         int type, unsigned char flags, char *quotes, char_io *io_ch, void *arg)
159 {
160         int i, outlen, len;
161         unsigned char orflags, *p, *q;
162         unsigned long c;
163         p = buf;
164         q = buf + buflen;
165         outlen = 0;
166         while(p != q) {
167                 if(p == buf) orflags = CHARTYPE_FIRST_ESC_2253;
168                 else orflags = 0;
169                 switch(type & BUF_TYPE_WIDTH_MASK) {
170                         case 4:
171                         c = ((unsigned long)*p++) << 24;
172                         c |= ((unsigned long)*p++) << 16;
173                         c |= ((unsigned long)*p++) << 8;
174                         c |= *p++;
175                         break;
176
177                         case 2:
178                         c = ((unsigned long)*p++) << 8;
179                         c |= *p++;
180                         break;
181
182                         case 1:
183                         c = *p++;
184                         break;
185                         
186                         case 0:
187                         i = UTF8_getc(p, buflen, &c);
188                         if(i < 0) return -1;    /* Invalid UTF8String */
189                         p += i;
190                         break;
191                 }
192                 if (p == q) orflags = CHARTYPE_LAST_ESC_2253;
193                 if(type & BUF_TYPE_CONVUTF8) {
194                         unsigned char utfbuf[6];
195                         int utflen;
196                         utflen = UTF8_putc(utfbuf, 6, c);
197                         for(i = 0; i < utflen; i++) {
198                                 /* We don't need to worry about setting orflags correctly
199                                  * because if utflen==1 its value will be correct anyway 
200                                  * otherwise each character will be > 0x7f and so the 
201                                  * character will never be escaped on first and last.
202                                  */
203                                 len = do_esc_char(utfbuf[i], (unsigned char)(flags | orflags), quotes, io_ch, arg);
204                                 if(len < 0) return -1;
205                                 outlen += len;
206                         }
207                 } else {
208                         len = do_esc_char(c, (unsigned char)(flags | orflags), quotes, io_ch, arg);
209                         if(len < 0) return -1;
210                         outlen += len;
211                 }
212         }
213         return outlen;
214 }
215
216 /* This function hex dumps a buffer of characters */
217
218 static int do_hex_dump(char_io *io_ch, void *arg, unsigned char *buf, int buflen)
219 {
220         const static char hexdig[] = "0123456789ABCDEF";
221         unsigned char *p, *q;
222         char hextmp[2];
223         if(arg) {
224                 p = buf;
225                 q = buf + buflen;
226                 while(p != q) {
227                         hextmp[0] = hexdig[*p >> 4];
228                         hextmp[1] = hexdig[*p & 0xf];
229                         if(!io_ch(arg, hextmp, 2)) return -1;
230                         p++;
231                 }
232         }
233         return buflen << 1;
234 }
235
236 /* "dump" a string. This is done when the type is unknown,
237  * or the flags request it. We can either dump the content
238  * octets or the entire DER encoding. This uses the RFC2253
239  * #01234 format.
240  */
241
242 int do_dump(unsigned long lflags, char_io *io_ch, void *arg, ASN1_STRING *str)
243 {
244         /* Placing the ASN1_STRING in a temp ASN1_TYPE allows
245          * the DER encoding to readily obtained
246          */
247         ASN1_TYPE t;
248         unsigned char *der_buf, *p;
249         int outlen, der_len;
250
251         if(!io_ch(arg, "#", 1)) return -1;
252         /* If we don't dump DER encoding just dump content octets */
253         if(!(lflags & ASN1_STRFLGS_DUMP_DER)) {
254                 outlen = do_hex_dump(io_ch, arg, str->data, str->length);
255                 if(outlen < 0) return -1;
256                 return outlen + 1;
257         }
258         t.type = str->type;
259         t.value.ptr = (char *)str;
260         der_len = i2d_ASN1_TYPE(&t, NULL);
261         der_buf = OPENSSL_malloc(der_len);
262         if(!der_buf) return -1;
263         p = der_buf;
264         i2d_ASN1_TYPE(&t, &p);
265         outlen = do_hex_dump(io_ch, arg, der_buf, der_len);
266         OPENSSL_free(der_buf);
267         if(outlen < 0) return -1;
268         return outlen + 1;
269 }
270
271 /* Lookup table to convert tags to character widths,
272  * 0 = UTF8 encoded, -1 is used for non string types
273  * otherwise it is the number of bytes per character
274  */
275
276 const static char tag2nbyte[] = {
277         -1, -1, -1, -1, -1,     /* 0-4 */
278         -1, -1, -1, -1, -1,     /* 5-9 */
279         -1, -1, 0, -1,          /* 10-13 */
280         -1, -1, -1, -1,         /* 15-17 */
281         -1, 1, 1,               /* 18-20 */
282         -1, 1, -1,-1,           /* 21-24 */
283         -1, 1, -1,              /* 25-27 */
284         4, -1, 2                /* 28-30 */
285 };
286
287 #define ESC_FLAGS (ASN1_STRFLGS_ESC_2253 | \
288                   ASN1_STRFLGS_ESC_QUOTE | \
289                   ASN1_STRFLGS_ESC_CTRL | \
290                   ASN1_STRFLGS_ESC_MSB)
291
292 /* This is the main function, print out an
293  * ASN1_STRING taking note of various escape
294  * and display options. Returns number of
295  * characters written or -1 if an error
296  * occurred.
297  */
298
299 static int do_print_ex(char_io *io_ch, void *arg, unsigned long lflags, ASN1_STRING *str)
300 {
301         int outlen, len;
302         int type;
303         char quotes;
304         unsigned char flags;
305         quotes = 0;
306         /* Keep a copy of escape flags */
307         flags = (unsigned char)(lflags & ESC_FLAGS);
308
309         type = str->type;
310
311         outlen = 0;
312
313
314         if(lflags & ASN1_STRFLGS_SHOW_TYPE) {
315                 const char *tagname;
316                 tagname = ASN1_tag2str(type);
317                 outlen += strlen(tagname);
318                 if(!io_ch(arg, tagname, outlen) || !io_ch(arg, ":", 1)) return -1; 
319                 outlen++;
320         }
321
322         /* Decide what to do with type, either dump content or display it */
323
324         /* Dump everything */
325         if(lflags & ASN1_STRFLGS_DUMP_ALL) type = -1;
326         /* Ignore the string type */
327         else if(lflags & ASN1_STRFLGS_IGNORE_TYPE) type = 1;
328         else {
329                 /* Else determine width based on type */
330                 if((type > 0) && (type < 31)) type = tag2nbyte[type];
331                 else type = -1;
332                 if((type == -1) && !(lflags & ASN1_STRFLGS_DUMP_UNKNOWN)) type = 1;
333         }
334
335         if(type == -1) {
336                 len = do_dump(lflags, io_ch, arg, str);
337                 if(len < 0) return -1;
338                 outlen += len;
339                 return outlen;
340         }
341
342         if(lflags & ASN1_STRFLGS_UTF8_CONVERT) {
343                 /* Note: if string is UTF8 and we want
344                  * to convert to UTF8 then we just interpret
345                  * it as 1 byte per character to avoid converting
346                  * twice.
347                  */
348                 if(!type) type = 1;
349                 else type |= BUF_TYPE_CONVUTF8;
350         }
351
352         len = do_buf(str->data, str->length, type, flags, &quotes, io_ch, NULL);
353         if(outlen < 0) return -1;
354         outlen += len;
355         if(quotes) outlen += 2;
356         if(!arg) return outlen;
357         if(quotes && !io_ch(arg, "\"", 1)) return -1;
358         do_buf(str->data, str->length, type, flags, NULL, io_ch, arg);
359         if(quotes && !io_ch(arg, "\"", 1)) return -1;
360         return outlen;
361 }
362
363 /* Used for line indenting: print 'indent' spaces */
364
365 static int do_indent(char_io *io_ch, void *arg, int indent)
366 {
367         int i;
368         for(i = 0; i < indent; i++)
369                         if(!io_ch(arg, " ", 1)) return 0;
370         return 1;
371 }
372
373
374 static int do_name_ex(char_io *io_ch, void *arg, X509_NAME *n,
375                                 int indent, unsigned long flags)
376 {
377         int i, prev = -1, orflags, cnt;
378         int fn_opt, fn_nid;
379         ASN1_OBJECT *fn;
380         ASN1_STRING *val;
381         X509_NAME_ENTRY *ent;
382         char objtmp[80];
383         const char *objbuf;
384         int outlen, len;
385         char *sep_dn, *sep_mv, *sep_eq;
386         int sep_dn_len, sep_mv_len, sep_eq_len;
387         if(indent < 0) indent = 0;
388         outlen = indent;
389         if(!do_indent(io_ch, arg, indent)) return -1;
390         switch (flags & XN_FLAG_SEP_MASK)
391         {
392                 case XN_FLAG_SEP_MULTILINE:
393                 sep_dn = "\n";
394                 sep_dn_len = 1;
395                 sep_mv = " + ";
396                 sep_mv_len = 3;
397                 break;
398
399                 case XN_FLAG_SEP_COMMA_PLUS:
400                 sep_dn = ",";
401                 sep_dn_len = 1;
402                 sep_mv = "+";
403                 sep_mv_len = 1;
404                 indent = 0;
405                 break;
406
407                 case XN_FLAG_SEP_CPLUS_SPC:
408                 sep_dn = ", ";
409                 sep_dn_len = 2;
410                 sep_mv = " + ";
411                 sep_mv_len = 3;
412                 indent = 0;
413                 break;
414
415                 case XN_FLAG_SEP_SPLUS_SPC:
416                 sep_dn = "; ";
417                 sep_dn_len = 2;
418                 sep_mv = " + ";
419                 sep_mv_len = 3;
420                 indent = 0;
421                 break;
422
423                 default:
424                 return -1;
425         }
426
427         if(flags & XN_FLAG_SPC_EQ) {
428                 sep_eq = " = ";
429                 sep_eq_len = 3;
430         } else {
431                 sep_eq = "=";
432                 sep_eq_len = 1;
433         }
434
435         fn_opt = flags & XN_FLAG_FN_MASK;
436
437         cnt = X509_NAME_entry_count(n); 
438         for(i = 0; i < cnt; i++) {
439                 if(flags & XN_FLAG_DN_REV)
440                                 ent = X509_NAME_get_entry(n, cnt - i - 1);
441                 else ent = X509_NAME_get_entry(n, i);
442                 if(prev != -1) {
443                         if(prev == ent->set) {
444                                 if(!io_ch(arg, sep_mv, sep_mv_len)) return -1;
445                                 outlen += sep_mv_len;
446                         } else {
447                                 if(!io_ch(arg, sep_dn, sep_dn_len)) return -1;
448                                 outlen += sep_dn_len;
449                                 if(!do_indent(io_ch, arg, indent)) return -1;
450                                 outlen += indent;
451                         }
452                 }
453                 prev = ent->set;
454                 fn = X509_NAME_ENTRY_get_object(ent);
455                 val = X509_NAME_ENTRY_get_data(ent);
456                 fn_nid = OBJ_obj2nid(fn);
457                 if(fn_opt != XN_FLAG_FN_NONE) {
458                         int objlen;
459                         if((fn_opt == XN_FLAG_FN_OID) || (fn_nid==NID_undef) ) {
460                                 OBJ_obj2txt(objtmp, 80, fn, 1);
461                                 objbuf = objtmp;
462                         } else {
463                                 if(fn_opt == XN_FLAG_FN_SN) 
464                                         objbuf = OBJ_nid2sn(fn_nid);
465                                 else if(fn_opt == XN_FLAG_FN_LN)
466                                         objbuf = OBJ_nid2ln(fn_nid);
467                                 else objbuf = "";
468                         }
469                         objlen = strlen(objbuf);
470                         if(!io_ch(arg, objbuf, objlen)) return -1;
471                         if(!io_ch(arg, sep_eq, sep_eq_len)) return -1;
472                         outlen += objlen + sep_eq_len;
473                 }
474                 /* If the field name is unknown then fix up the DER dump
475                  * flag. We might want to limit this further so it will
476                  * DER dump on anything other than a few 'standard' fields.
477                  */
478                 if((fn_nid == NID_undef) && (flags & XN_FLAG_DUMP_UNKNOWN_FIELDS)) 
479                                         orflags = ASN1_STRFLGS_DUMP_ALL;
480                 else orflags = 0;
481      
482                 len = do_print_ex(io_ch, arg, flags | orflags, val);
483                 if(len < 0) return -1;
484                 outlen += len;
485         }
486         return outlen;
487 }
488
489 /* Wrappers round the main functions */
490
491 int X509_NAME_print_ex(BIO *out, X509_NAME *nm, int indent, unsigned long flags)
492 {
493         return do_name_ex(send_bio_chars, out, nm, indent, flags);
494 }
495
496
497 int X509_NAME_print_ex_fp(FILE *fp, X509_NAME *nm, int indent, unsigned long flags)
498 {
499         return do_name_ex(send_fp_chars, fp, nm, indent, flags);
500 }
501
502 int ASN1_STRING_print_ex(BIO *out, ASN1_STRING *str, unsigned long flags)
503 {
504         return do_print_ex(send_bio_chars, out, flags, str);
505 }
506
507
508 int ASN1_STRING_print_ex_fp(FILE *fp, ASN1_STRING *str, unsigned long flags)
509 {
510         return do_print_ex(send_fp_chars, fp, flags, str);
511 }
512
513 /* Utility function: convert any string type to UTF8, returns number of bytes
514  * in output string or a negative error code
515  */
516
517 int ASN1_STRING_to_UTF8(unsigned char **out, ASN1_STRING *in)
518 {
519         ASN1_STRING stmp, *str = &stmp;
520         int mbflag, type, ret;
521         if(!*out || !in) return -1;
522         type = in->type;
523         if((type < 0) || (type > 30)) return -1;
524         mbflag = tag2nbyte[type];
525         if(mbflag == -1) return -1;
526         mbflag |= MBSTRING_FLAG;
527         stmp.data = NULL;
528         ret = ASN1_mbstring_copy(&str, in->data, in->length, mbflag, B_ASN1_UTF8STRING);
529         if(ret < 0) return ret;
530         if(out) *out = stmp.data;
531         return stmp.length;
532 }