r9680: Update Heimdal to current lorikeet-heimdal (which was itself updated
[metze/samba/wip.git] / source / heimdal / lib / asn1 / gen_encode.c
1 /*
2  * Copyright (c) 1997 - 2005 Kungliga Tekniska Högskolan
3  * (Royal Institute of Technology, Stockholm, Sweden). 
4  * All rights reserved. 
5  *
6  * Redistribution and use in source and binary forms, with or without 
7  * modification, are permitted provided that the following conditions 
8  * are met: 
9  *
10  * 1. Redistributions of source code must retain the above copyright 
11  *    notice, this list of conditions and the following disclaimer. 
12  *
13  * 2. Redistributions in binary form must reproduce the above copyright 
14  *    notice, this list of conditions and the following disclaimer in the 
15  *    documentation and/or other materials provided with the distribution. 
16  *
17  * 3. Neither the name of the Institute nor the names of its contributors 
18  *    may be used to endorse or promote products derived from this software 
19  *    without specific prior written permission. 
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND 
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE 
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 
31  * SUCH DAMAGE. 
32  */
33
34 #include "gen_locl.h"
35
36 RCSID("$Id: gen_encode.c,v 1.19 2005/08/23 11:52:16 lha Exp $");
37
38 static void
39 encode_primitive (const char *typename, const char *name)
40 {
41     fprintf (codefile,
42              "e = der_put_%s(p, len, %s, &l);\n"
43              "if (e) return e;\np -= l; len -= l; ret += l;\n\n",
44              typename,
45              name);
46 }
47
48 const char *
49 classname(Der_class class)
50 {
51     const char *cn[] = { "ASN1_C_UNIV", "ASN1_C_APPL",
52                          "ASN1_C_CONTEXT", "ASN1_C_PRIV" };
53     if(class < ASN1_C_UNIV || class > ASN1_C_PRIVATE)
54         return "???";
55     return cn[class];
56 }
57
58
59 const char *
60 valuename(Der_class class, int value)
61 {
62     static char s[32];
63     struct { 
64         int value;
65         const char *s;
66     } *p, values[] = {
67 #define X(Y) { Y, #Y }
68         X(UT_BMPString),
69         X(UT_BitString),
70         X(UT_Boolean),
71         X(UT_EmbeddedPDV),
72         X(UT_Enumerated),
73         X(UT_External),
74         X(UT_GeneralString),
75         X(UT_GeneralizedTime),
76         X(UT_GraphicString),
77         X(UT_IA5String),
78         X(UT_Integer),
79         X(UT_Null),
80         X(UT_NumericString),
81         X(UT_OID),
82         X(UT_ObjectDescriptor),
83         X(UT_OctetString),
84         X(UT_PrintableString),
85         X(UT_Real),
86         X(UT_RelativeOID),
87         X(UT_Sequence),
88         X(UT_Set),
89         X(UT_TeletexString),
90         X(UT_UTCTime),
91         X(UT_UTF8String),
92         X(UT_UniversalString),
93         X(UT_VideotexString),
94         X(UT_VisibleString),
95 #undef X
96         { -1, NULL }
97     };
98     if(class == ASN1_C_UNIV) {
99         for(p = values; p->value != -1; p++)
100             if(p->value == value)
101                 return p->s;
102     }
103     snprintf(s, sizeof(s), "%d", value);
104     return s;
105 }
106
107 static int
108 encode_type (const char *name, const Type *t, const char *tmpstr)
109 {
110     int constructed = 1;
111
112     switch (t->type) {
113     case TType:
114 #if 0
115         encode_type (name, t->symbol->type);
116 #endif
117         fprintf (codefile,
118                  "e = encode_%s(p, len, %s, &l);\n"
119                  "if (e) return e;\np -= l; len -= l; ret += l;\n\n",
120                  t->symbol->gen_name, name);
121         break;
122     case TInteger:
123         if(t->members) {
124             char *s;
125             asprintf(&s, "(const int*)%s", name);
126             if(s == NULL)
127                 errx(1, "out of memory");
128             encode_primitive ("integer", s);
129             free(s);
130         } else if (t->range == NULL) {
131             encode_primitive ("heim_integer", name);
132         } else if (t->range->min == INT_MIN && t->range->max == INT_MAX) {
133             encode_primitive ("integer", name);
134         } else if (t->range->min == 0 && t->range->max == UINT_MAX) {
135             encode_primitive ("unsigned", name);
136         } else if (t->range->min == 0 && t->range->max == INT_MAX) {
137             encode_primitive ("unsigned", name);
138         } else
139             errx(1, "%s: unsupported range %d -> %d", 
140                  name, t->range->min, t->range->max);
141         constructed = 0;
142         break;
143     case TBoolean:
144         encode_primitive ("boolean", name);
145         constructed = 0;
146         break;
147     case TOctetString:
148         encode_primitive ("octet_string", name);
149         constructed = 0;
150         break;
151     case TBitString: {
152         Member *m;
153         int pos;
154         int rest;
155
156         if (ASN1_TAILQ_EMPTY(t->members)) {
157             encode_primitive("bit_string", name);
158             constructed = 0;
159             break;
160         }
161
162         fprintf (codefile, "{\n"
163                  "unsigned char c = 0;\n");
164         if (!rfc1510_bitstring)
165             fprintf (codefile,
166                      "int bit_set = 0;\n");
167 #if 0
168         pos = t->members->prev->val;
169         /* fix for buggy MIT (and OSF?) code */
170         if (pos > 31)
171             abort ();
172 #endif
173         /*
174          * It seems that if we do not always set pos to 31 here, the MIT
175          * code will do the wrong thing.
176          *
177          * I hate ASN.1 (and DER), but I hate it even more when everybody
178          * has to screw it up differently.
179          */
180         pos = ASN1_TAILQ_LAST(t->members, memhead)->val;
181         if (rfc1510_bitstring) {
182             if (pos < 31)
183                 pos = 31;
184             rest = 7 - (pos % 8);
185         } else
186             rest = 0;
187
188         ASN1_TAILQ_FOREACH_REVERSE(m, t->members, memhead, members) {
189             while (m->val / 8 < pos / 8) {
190                 if (!rfc1510_bitstring)
191                     fprintf (codefile,
192                              "if (c != 0 || bit_set) {\n");
193                 fprintf (codefile,
194                          "if (len < 1) return ASN1_OVERFLOW;\n"
195                          "*p-- = c; len--; ret++;\n"
196                          "c = 0;\n");
197                 if (!rfc1510_bitstring)
198                     fprintf (codefile,
199                              "bit_set = 1;\n"
200                              "}\n");
201                 pos -= 8;
202             }
203             fprintf (codefile,
204                      "if((%s)->%s) {\n"
205                      "c |= 1<<%d;\n", 
206                      name, m->gen_name, 7 - m->val % 8);
207             if (!rfc1510_bitstring)
208                 rest = 7 - m->val % 8;
209             fprintf (codefile,
210                      "}\n");
211         }
212
213         if (!rfc1510_bitstring)
214             fprintf (codefile,
215                      "if (c != 0 || bit_set) {\n");
216         fprintf (codefile, 
217                  "if (len < 1) return ASN1_OVERFLOW;\n"
218                  "*p-- = c; len--; ret++;\n");
219         if (!rfc1510_bitstring)
220             fprintf (codefile,
221                      "}\n");
222         
223         fprintf (codefile, 
224                  "if (len < 1) return ASN1_OVERFLOW;\n"
225                  "*p-- = %d;\n"
226                  "len -= 1;\n"
227                  "ret += 1;\n"
228                  "}\n\n",
229                  rest);
230         constructed = 0;
231         break;
232     }
233     case TEnumerated : {
234         encode_primitive ("enumerated", name);
235         constructed = 0;
236         break;
237     }
238
239     case TSet:
240     case TSequence: {
241         Member *m;
242
243         if (t->members == NULL)
244             break;
245         
246         ASN1_TAILQ_FOREACH_REVERSE(m, t->members, memhead, members) {
247             char *s;
248
249             if (m->ellipsis)
250                 continue;
251
252             asprintf (&s, "%s(%s)->%s", m->optional ? "" : "&", name, m->gen_name);
253             if (s == NULL)
254                 errx(1, "malloc");
255             fprintf(codefile, "/* %s */\n", m->name);
256             if (m->optional)
257                 fprintf (codefile,
258                          "if(%s) ",
259                          s);
260             else if(m->defval)
261                 gen_compare_defval(s + 1, m->defval);
262             fprintf (codefile, "{\n");
263             fprintf (codefile, "size_t %s_oldret = ret;\n", tmpstr);
264             fprintf (codefile, "ret = 0;\n");
265             encode_type (s, m->type, m->gen_name);
266             fprintf (codefile, "ret += %s_oldret;\n", tmpstr);
267             fprintf (codefile, "}\n");
268             free (s);
269         }
270         break;
271     }
272     case TSetOf: {
273
274         fprintf(codefile,
275                 "{\n"
276                 "struct heim_octet_string *val;\n"
277                 "size_t elen, totallen = 0;\n"
278                 "int eret;\n");
279
280         fprintf(codefile,
281                 "val = malloc(sizeof(val[0]) * (%s)->len);\n"
282                 "if (val == NULL && (%s)->len != 0) return ENOMEM;\n",
283                 name, name);
284
285         fprintf(codefile,
286                 "for(i = 0; i < (%s)->len; i++) {\n",
287                 name);
288
289         fprintf(codefile,
290                 "ASN1_MALLOC_ENCODE(%s, val[i].data, "
291                 "val[i].length, &(%s)->val[i], &elen, eret);\n",
292                 t->subtype->symbol->gen_name,
293                 name);
294
295         fprintf(codefile,
296                 "if(eret) {\n"
297                 "i--;\n"
298                 "while (i >= 0) {\n"
299                 "free(val[i].data);\n"
300                 "i--;\n"
301                 "}\n"
302                 "free(val);\n"
303                 "return eret;\n"
304                 "}\n"
305                 "totallen += elen;\n"
306                 "}\n");
307
308         fprintf(codefile,
309                 "if (totallen > len) {\n"
310                 "for (i = 0; i < (%s)->len; i++) {\n"
311                 "free(val[i].data);\n"
312                 "}\n"
313                 "free(val);\n"
314                 "return ASN1_OVERFLOW;\n"
315                 "}\n",
316                 name);
317
318         fprintf(codefile,
319                 "qsort(val, (%s)->len, sizeof(val[0]), _heim_der_set_sort);\n",
320                 name);
321
322         fprintf (codefile,
323                  "for(i = (%s)->len - 1; i >= 0; --i) {\n"
324                  "p -= val[i].length;\n"
325                  "ret += val[i].length;\n"
326                  "memcpy(p + 1, val[i].data, val[i].length);\n"
327                  "free(val[i].data);\n"
328                  "}\n"
329                  "free(val);\n"
330                  "}\n",
331                  name);
332         break;
333     }
334     case TSequenceOf: {
335         char *n;
336         char *sname;
337
338         fprintf (codefile,
339                  "for(i = (%s)->len - 1; i >= 0; --i) {\n"
340                  "size_t %s_for_oldret = ret;\n"
341                  "ret = 0;\n",
342                  name, tmpstr);
343         asprintf (&n, "&(%s)->val[i]", name);
344         if (n == NULL)
345             errx(1, "malloc");
346         asprintf (&sname, "%s_S_Of", tmpstr);
347         if (sname == NULL)
348             errx(1, "malloc");
349         encode_type (n, t->subtype, sname);
350         fprintf (codefile,
351                  "ret += %s_for_oldret;\n"
352                  "}\n",
353                  tmpstr);
354         free (n);
355         free (sname);
356         break;
357     }
358     case TGeneralizedTime:
359         encode_primitive ("generalized_time", name);
360         constructed = 0;
361         break;
362     case TGeneralString:
363         encode_primitive ("general_string", name);
364         constructed = 0;
365         break;
366     case TTag: {
367         char *tname;
368         int c;
369         asprintf (&tname, "%s_tag", tmpstr);
370         if (tname == NULL)
371             errx(1, "malloc");  
372         c = encode_type (name, t->subtype, tname);
373         fprintf (codefile,
374                  "e = der_put_length_and_tag (p, len, ret, %s, %s, %s, &l);\n"
375                  "if (e) return e;\np -= l; len -= l; ret += l;\n\n",
376                  classname(t->tag.tagclass),
377                  c ? "CONS" : "PRIM", 
378                  valuename(t->tag.tagclass, t->tag.tagvalue));
379         free (tname);
380         break;
381     }
382     case TChoice:{
383         Member *m, *have_ellipsis = NULL;
384         char *s;
385
386         if (t->members == NULL)
387             break;
388
389         fprintf(codefile, "\n");
390
391         asprintf (&s, "(%s)", name);
392         if (s == NULL)
393             errx(1, "malloc");
394         fprintf(codefile, "switch(%s->element) {\n", s);
395
396         ASN1_TAILQ_FOREACH_REVERSE(m, t->members, memhead, members) {
397             char *s2;
398
399             if (m->ellipsis) {
400                 have_ellipsis = m;
401                 continue;
402             }
403
404             fprintf (codefile, "case %s: {", m->label); 
405             asprintf(&s2, "%s(%s)->u.%s", m->optional ? "" : "&", 
406                      s, m->gen_name);
407             if (s2 == NULL)
408                 errx(1, "malloc");
409             if (m->optional)
410                 fprintf (codefile, "if(%s) {\n", s2);
411             fprintf (codefile, "size_t %s_oldret = ret;\n", tmpstr);
412             fprintf (codefile, "ret = 0;\n");
413             constructed = encode_type (s2, m->type, m->gen_name);
414             fprintf (codefile, "ret += %s_oldret;\n", tmpstr);
415             if(m->optional)
416                 fprintf (codefile, "}\n");
417             fprintf(codefile, "break;\n");
418             fprintf(codefile, "}\n");
419             free (s2);
420         }
421         free (s);
422         if (have_ellipsis) {
423             fprintf(codefile,
424                     "case %s: {\n"
425                     "if (len < (%s)->u.%s.length)\n"
426                     "return ASN1_OVERFLOW;\n"
427                     "p -= (%s)->u.%s.length;\n"
428                     "ret += (%s)->u.%s.length;\n"
429                     "memcpy(p + 1, (%s)->u.%s.data, (%s)->u.%s.length);\n"
430                     "break;\n"
431                     "}\n",
432                     have_ellipsis->label,
433                     name, have_ellipsis->gen_name,
434                     name, have_ellipsis->gen_name,
435                     name, have_ellipsis->gen_name,
436                     name, have_ellipsis->gen_name,
437                     name, have_ellipsis->gen_name);
438         }
439         fprintf(codefile, "};\n");
440         break;
441     }
442     case TOID:
443         encode_primitive ("oid", name);
444         constructed = 0;
445         break;
446     case TUTCTime:
447         encode_primitive ("utctime", name);
448         constructed = 0;
449         break;
450     case TUTF8String:
451         encode_primitive ("utf8string", name);
452         constructed = 0;
453         break;
454     case TPrintableString:
455         encode_primitive ("printable_string", name);
456         constructed = 0;
457         break;
458     case TIA5String:
459         encode_primitive ("ia5_string", name);
460         constructed = 0;
461         break;
462     case TBMPString:
463         encode_primitive ("bmp_string", name);
464         constructed = 0;
465         break;
466     case TUniversalString:
467         encode_primitive ("universal_string", name);
468         constructed = 0;
469         break;
470     case TNull:
471         fprintf (codefile, "/* NULL */\n");
472         constructed = 0;
473         break;
474     default:
475         abort ();
476     }
477     return constructed;
478 }
479
480 void
481 generate_type_encode (const Symbol *s)
482 {
483     fprintf (headerfile,
484              "int    "
485              "encode_%s(unsigned char *, size_t, const %s *, size_t *);\n",
486              s->gen_name, s->gen_name);
487
488     fprintf (codefile, "int\n"
489              "encode_%s(unsigned char *p, size_t len,"
490              " const %s *data, size_t *size)\n"
491              "{\n",
492              s->gen_name, s->gen_name);
493
494     switch (s->type->type) {
495     case TInteger:
496     case TBoolean:
497     case TOctetString:
498     case TGeneralizedTime:
499     case TGeneralString:
500     case TUTCTime:
501     case TUTF8String:
502     case TPrintableString:
503     case TIA5String:
504     case TBMPString:
505     case TUniversalString:
506     case TNull:
507     case TBitString:
508     case TEnumerated:
509     case TOID:
510     case TSequence:
511     case TSequenceOf:
512     case TSet:
513     case TSetOf:
514     case TTag:
515     case TType:
516     case TChoice:
517         fprintf (codefile,
518                  "size_t ret = 0;\n"
519                  "size_t l;\n"
520                  "int i, e;\n\n");
521         fprintf(codefile, "i = 0;\n"); /* hack to avoid `unused variable' */
522     
523         encode_type("data", s->type, "Top");
524
525         fprintf (codefile, "*size = ret;\n"
526                  "return 0;\n");
527         break;
528     default:
529         abort ();
530     }
531     fprintf (codefile, "}\n\n");
532 }