]> git.saurik.com Git - apple/security.git/blob - OSX/libsecurity_asn1/lib/secasn1e.c
Security-59306.61.1.tar.gz
[apple/security.git] / OSX / libsecurity_asn1 / lib / secasn1e.c
1 /*
2 * The contents of this file are subject to the Mozilla Public
3 * License Version 1.1 (the "License"); you may not use this file
4 * except in compliance with the License. You may obtain a copy of
5 * the License at http://www.mozilla.org/MPL/
6 *
7 * Software distributed under the License is distributed on an "AS
8 * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
9 * implied. See the License for the specific language governing
10 * rights and limitations under the License.
11 *
12 * The Original Code is the Netscape security libraries.
13 *
14 * The Initial Developer of the Original Code is Netscape
15 * Communications Corporation. Portions created by Netscape are
16 * Copyright (C) 1994-2000 Netscape Communications Corporation. All
17 * Rights Reserved.
18 *
19 * Contributor(s):
20 *
21 * Alternatively, the contents of this file may be used under the
22 * terms of the GNU General Public License Version 2 or later (the
23 * "GPL"), in which case the provisions of the GPL are applicable
24 * instead of those above. If you wish to allow use of your
25 * version of this file only under the terms of the GPL and not to
26 * allow others to use your version of this file under the MPL,
27 * indicate your decision by deleting the provisions above and
28 * replace them with the notice and other provisions required by
29 * the GPL. If you do not delete the provisions above, a recipient
30 * may use your version of this file under either the MPL or the
31 * GPL.
32 */
33
34 /*
35 * Support for ENcoding ASN.1 data based on BER/DER (Basic/Distinguished
36 * Encoding Rules).
37 *
38 * $Id: secasn1e.c,v 1.7 2004/05/13 15:29:13 dmitch Exp $
39 */
40
41 #include "secasn1.h"
42
43 typedef enum {
44 beforeHeader,
45 duringContents,
46 duringGroup,
47 duringSequence,
48 afterContents,
49 afterImplicit,
50 afterInline,
51 afterPointer,
52 afterChoice,
53 notInUse
54 } sec_asn1e_parse_place;
55
56 typedef enum {
57 allDone,
58 encodeError,
59 keepGoing,
60 needBytes
61 } sec_asn1e_parse_status;
62
63 typedef enum {
64 hdr_normal = 0, /* encode header normally */
65 hdr_any = 1, /* header already encoded in content */
66 hdr_decoder = 2, /* template only used by decoder. skip it. */
67 hdr_optional = 3, /* optional component, to be omitted */
68 hdr_placeholder = 4 /* place holder for from_buf content */
69 } sec_asn1e_hdr_encoding;
70
71 typedef struct sec_asn1e_state_struct {
72 SEC_ASN1EncoderContext *top;
73 const SecAsn1Template *theTemplate;
74 void *src;
75
76 struct sec_asn1e_state_struct *parent; /* aka prev */
77 struct sec_asn1e_state_struct *child; /* aka next */
78
79 sec_asn1e_parse_place place; /* where we are in encoding process */
80
81 /*
82 * XXX explain the next fields as clearly as possible...
83 */
84 unsigned char tag_modifiers;
85 unsigned char tag_number;
86 unsigned long underlying_kind;
87
88 int depth;
89
90 PRBool explicit, /* we are handling an explicit header */
91 indefinite, /* need end-of-contents */
92 is_string, /* encoding a simple string or an ANY */
93 may_stream, /* when streaming, do indefinite encoding */
94 optional, /* omit field if it has no contents */
95 ignore_stream /* ignore streaming value of sub-template */
96 #ifdef __APPLE__
97 ,
98 signedInt /* signed alternate to SEC_ASN1_INTEGER */
99 #endif
100 ;
101 } sec_asn1e_state;
102
103 /*
104 * An "outsider" will have an opaque pointer to this, created by calling
105 * SEC_ASN1EncoderStart(). It will be passed back in to all subsequent
106 * calls to SEC_ASN1EncoderUpdate() and related routines, and when done
107 * it is passed to SEC_ASN1EncoderFinish().
108 */
109 struct sec_EncoderContext_struct {
110 PRArenaPool *our_pool; /* for our internal allocs */
111
112 sec_asn1e_state *current;
113 sec_asn1e_parse_status status;
114
115 PRBool streaming;
116 PRBool from_buf;
117
118 SEC_ASN1NotifyProc notify_proc; /* call before/after handling field */
119 void *notify_arg; /* argument to notify_proc */
120 PRBool during_notify; /* true during call to notify_proc */
121
122 SEC_ASN1WriteProc output_proc; /* pass encoded bytes to this */
123 void *output_arg; /* argument to that function */
124 };
125
126
127 static sec_asn1e_state *
128 sec_asn1e_push_state(SEC_ASN1EncoderContext *cx,
129 const SecAsn1Template *theTemplate,
130 const void *src, PRBool new_depth)
131 {
132 sec_asn1e_state *state, *new_state;
133
134 state = cx->current;
135
136 new_state = (sec_asn1e_state*)PORT_ArenaZAlloc(cx->our_pool, sizeof(*new_state));
137 if (new_state == NULL) {
138 cx->status = encodeError;
139 return NULL;
140 }
141
142 new_state->top = cx;
143 new_state->parent = state;
144 new_state->theTemplate = theTemplate;
145 new_state->place = notInUse;
146 if (src != NULL) {
147 new_state->src = (char *)src + theTemplate->offset;
148 }
149
150 if (state != NULL) {
151 new_state->depth = state->depth;
152 if (new_depth) {
153 new_state->depth++;
154 }
155 state->child = new_state;
156 }
157
158 cx->current = new_state;
159 return new_state;
160 }
161
162
163 static void
164 sec_asn1e_scrub_state(sec_asn1e_state *state)
165 {
166 /*
167 * Some default "scrubbing".
168 * XXX right set of initializations?
169 */
170 state->place = beforeHeader;
171 state->indefinite = PR_FALSE;
172 }
173
174
175 static void
176 sec_asn1e_notify_before(SEC_ASN1EncoderContext *cx, void *src, int depth)
177 {
178 if (cx->notify_proc == NULL) {
179 return;
180 }
181
182 cx->during_notify = PR_TRUE;
183 (* cx->notify_proc)(cx->notify_arg, PR_TRUE, src, depth);
184 cx->during_notify = PR_FALSE;
185 }
186
187
188 static void
189 sec_asn1e_notify_after(SEC_ASN1EncoderContext *cx, void *src, int depth)
190 {
191 if (cx->notify_proc == NULL) {
192 return;
193 }
194
195 cx->during_notify = PR_TRUE;
196 (* cx->notify_proc)(cx->notify_arg, PR_FALSE, src, depth);
197 cx->during_notify = PR_FALSE;
198 }
199
200
201 static sec_asn1e_state *
202 sec_asn1e_init_state_based_on_template(sec_asn1e_state *state)
203 {
204 PRBool explicit, is_string, may_stream, optional, universal, ignore_stream;
205 unsigned char tag_modifiers;
206 unsigned long encode_kind, under_kind;
207 unsigned long tag_number;
208 #ifdef __APPLE__
209 PRBool signedInt, dynamic;
210 #endif
211
212 encode_kind = state->theTemplate->kind;
213
214 universal = ((encode_kind & SEC_ASN1_CLASS_MASK) == SEC_ASN1_UNIVERSAL) ? PR_TRUE : PR_FALSE;
215
216 explicit = (encode_kind & SEC_ASN1_EXPLICIT) ? PR_TRUE : PR_FALSE;
217 encode_kind &= ~SEC_ASN1_EXPLICIT;
218
219 optional = (encode_kind & SEC_ASN1_OPTIONAL) ? PR_TRUE : PR_FALSE;
220 encode_kind &= ~SEC_ASN1_OPTIONAL;
221
222 PORT_Assert(!(explicit && universal)); /* bad templates */
223
224 may_stream = (encode_kind & SEC_ASN1_MAY_STREAM) ? PR_TRUE : PR_FALSE;
225 encode_kind &= ~SEC_ASN1_MAY_STREAM;
226
227 ignore_stream = (encode_kind & SEC_ASN1_NO_STREAM) ? PR_TRUE : PR_FALSE;
228 encode_kind &= ~SEC_ASN1_NO_STREAM;
229
230 #ifdef __APPLE__
231 signedInt = (encode_kind & SEC_ASN1_SIGNED_INT) ? PR_TRUE : PR_FALSE;
232 encode_kind &= ~SEC_ASN1_SIGNED_INT;
233 #endif
234
235 #ifdef __APPLE__
236 dynamic = (encode_kind & SEC_ASN1_DYNAMIC) ? PR_TRUE : PR_FALSE;
237 #endif
238 encode_kind &= ~SEC_ASN1_DYNAMIC;
239
240 if( encode_kind & SEC_ASN1_CHOICE ) {
241 under_kind = SEC_ASN1_CHOICE;
242 } else if ((encode_kind & (SEC_ASN1_POINTER | SEC_ASN1_INLINE)) ||
243 (!universal && !explicit)) {
244 const SecAsn1Template *subt;
245 void *src = NULL;
246
247 PORT_Assert((encode_kind & (SEC_ASN1_ANY | SEC_ASN1_SKIP)) == 0);
248
249 sec_asn1e_scrub_state(state);
250
251 if (encode_kind & SEC_ASN1_POINTER) {
252 /*
253 * XXX This used to PORT_Assert (encode_kind == SEC_ASN1_POINTER);
254 * but that was too restrictive. This needs to be fixed,
255 * probably copying what the decoder now checks for, and
256 * adding a big comment here to explain what the checks mean.
257 */
258 src = *(void **)state->src;
259 state->place = afterPointer;
260 if (src == NULL) {
261 /*
262 * If this is optional, but NULL, then the field does
263 * not need to be encoded. In this case we are done;
264 * we do not want to push a subtemplate.
265 */
266 if (optional) {
267 return state;
268 }
269
270 /*
271 * XXX this is an error; need to figure out
272 * how to handle this
273 */
274 }
275 } else {
276 src = state->src;
277 if (encode_kind & SEC_ASN1_INLINE) {
278 /* check that there are no extraneous bits */
279 PORT_Assert(encode_kind == SEC_ASN1_INLINE && !optional);
280 state->place = afterInline;
281 } else {
282 /*
283 * Save the tag modifiers and tag number here before moving
284 * on to the next state in case this is a member of a
285 * SEQUENCE OF
286 */
287 state->tag_modifiers = (unsigned char)encode_kind & SEC_ASN1_TAG_MASK & ~SEC_ASN1_TAGNUM_MASK;
288 state->tag_number = (unsigned char)encode_kind & SEC_ASN1_TAGNUM_MASK;
289
290 state->place = afterImplicit;
291 state->optional = optional;
292 }
293 }
294
295 subt = SEC_ASN1GetSubtemplate(state->theTemplate, state->src, PR_TRUE,
296 NULL /* __APPLE__ */, 0 /* __APPLE__ */);
297 state = sec_asn1e_push_state(state->top, subt, src, PR_FALSE);
298 if (state == NULL) {
299 return NULL;
300 }
301
302 if (universal) {
303 /*
304 * This is a POINTER or INLINE; just init based on that
305 * and we are done.
306 */
307 return sec_asn1e_init_state_based_on_template(state);
308 }
309
310 /*
311 * This is an implicit, non-universal (meaning, application-private
312 * or context-specific) field. This results in a "magic" tag but
313 * encoding based on the underlying type. We pushed a new state
314 * that is based on the subtemplate (the underlying type), but
315 * now we will sort of alias it to give it some of our properties
316 * (tag, optional status, etc.).
317 */
318
319 under_kind = state->theTemplate->kind;
320 if (under_kind & SEC_ASN1_MAY_STREAM) {
321 if (!ignore_stream) {
322 may_stream = PR_TRUE;
323 }
324 under_kind &= ~SEC_ASN1_MAY_STREAM;
325 }
326 } else {
327 under_kind = encode_kind;
328 }
329
330 /*
331 * Sanity check that there are no unwanted bits marked in under_kind.
332 * These bits were either removed above (after we recorded them) or
333 * they simply should not be found (signalling a bad/broken template).
334 * XXX is this the right set of bits to test here? (i.e. need to add
335 * or remove any?)
336 */
337 PORT_Assert((under_kind & (/*SEC_ASN1_EXPLICIT | */SEC_ASN1_OPTIONAL
338 | SEC_ASN1_SKIP | SEC_ASN1_INNER
339 | SEC_ASN1_DYNAMIC | SEC_ASN1_MAY_STREAM
340 | SEC_ASN1_INLINE | SEC_ASN1_POINTER)) == 0);
341
342 if (encode_kind & SEC_ASN1_ANY) {
343 PORT_Assert(encode_kind == under_kind);
344 tag_modifiers = 0;
345 tag_number = 0;
346 is_string = PR_TRUE;
347 } else {
348 tag_modifiers = (unsigned char)encode_kind & SEC_ASN1_TAG_MASK & ~SEC_ASN1_TAGNUM_MASK;
349 /*
350 * XXX This assumes only single-octet identifiers. To handle
351 * the HIGH TAG form we would need to do some more work, especially
352 * in how to specify them in the template, because right now we
353 * do not provide a way to specify more *tag* bits in encode_kind.
354 */
355
356 #ifdef __APPLE__
357 /*
358 * Apple change: if this is a DYNAMIC template, use the tag number
359 * from the subtemplate's kind
360 */
361 if (dynamic) {
362 tag_number = state->theTemplate->kind & SEC_ASN1_TAGNUM_MASK;
363 explicit = (state->theTemplate->kind & SEC_ASN1_EXPLICIT) ? PR_TRUE : PR_FALSE;
364 tag_modifiers |= (state->theTemplate->kind & SEC_ASN1_CONSTRUCTED);
365 }
366 else
367 #endif /* __APPLE__ */
368 tag_number = encode_kind & SEC_ASN1_TAGNUM_MASK;
369
370 is_string = PR_FALSE;
371 switch (under_kind & SEC_ASN1_TAGNUM_MASK) {
372 case SEC_ASN1_SET:
373 /*
374 * XXX A plain old SET (as opposed to a SET OF) is not implemented.
375 * If it ever is, remove this assert...
376 */
377 PORT_Assert((under_kind & SEC_ASN1_GROUP) != 0);
378 /* fallthru */
379 case SEC_ASN1_SEQUENCE:
380 tag_modifiers |= SEC_ASN1_CONSTRUCTED;
381 break;
382 case SEC_ASN1_BIT_STRING:
383 case SEC_ASN1_BMP_STRING:
384 case SEC_ASN1_GENERALIZED_TIME:
385 case SEC_ASN1_IA5_STRING:
386 case SEC_ASN1_OCTET_STRING:
387 case SEC_ASN1_PRINTABLE_STRING:
388 case SEC_ASN1_T61_STRING:
389 case SEC_ASN1_UNIVERSAL_STRING:
390 case SEC_ASN1_UTC_TIME:
391 case SEC_ASN1_UTF8_STRING:
392 case SEC_ASN1_VISIBLE_STRING:
393 /*
394 * We do not yet know if we will be constructing the string,
395 * so we have to wait to do this final tag modification.
396 */
397 is_string = PR_TRUE;
398 break;
399 }
400 }
401
402 state->tag_modifiers = tag_modifiers;
403 state->tag_number = (unsigned char)tag_number;
404 state->underlying_kind = under_kind;
405 state->explicit = explicit;
406 state->may_stream = may_stream;
407 state->is_string = is_string;
408 state->optional = optional;
409 state->ignore_stream = ignore_stream;
410 #ifdef __APPLE__
411 state->signedInt = signedInt;
412 #endif
413
414 sec_asn1e_scrub_state(state);
415
416 return state;
417 }
418
419
420 static void
421 sec_asn1e_write_part(sec_asn1e_state *state,
422 const char *buf, size_t len,
423 SEC_ASN1EncodingPart part)
424 {
425 SEC_ASN1EncoderContext *cx;
426
427 cx = state->top;
428 (* cx->output_proc)(cx->output_arg, buf, len, state->depth, part);
429 }
430
431
432 /*
433 * XXX This assumes only single-octet identifiers. To handle
434 * the HIGH TAG form we would need to modify this interface and
435 * teach it to properly encode the special form.
436 */
437 static void
438 sec_asn1e_write_identifier_bytes(sec_asn1e_state *state, unsigned char value)
439 {
440 char byte;
441
442 byte = (char) value;
443 sec_asn1e_write_part(state, &byte, 1, SEC_ASN1_Identifier);
444 }
445
446 int
447 SEC_ASN1EncodeLength(unsigned char *buf,unsigned long value) {
448 int lenlen;
449
450 lenlen = SEC_ASN1LengthLength(value);
451 if (lenlen == 1) {
452 buf[0] = value;
453 } else {
454 int i;
455
456 i = lenlen - 1;
457 buf[0] = 0x80 | i;
458 while (i) {
459 buf[i--] = value;
460 value >>= 8;
461 }
462 PORT_Assert(value == 0);
463 }
464 return lenlen;
465 }
466
467 static void
468 sec_asn1e_write_length_bytes(sec_asn1e_state *state, unsigned long value,
469 PRBool indefinite)
470 {
471 int lenlen;
472 unsigned char buf[sizeof(unsigned long) + 1];
473
474 if (indefinite) {
475 PORT_Assert(value == 0);
476 buf[0] = 0x80;
477 lenlen = 1;
478 } else {
479 lenlen = SEC_ASN1EncodeLength(buf,value);
480 }
481
482 sec_asn1e_write_part(state, (char *) buf, lenlen, SEC_ASN1_Length);
483 }
484
485
486 static void
487 sec_asn1e_write_contents_bytes(sec_asn1e_state *state,
488 const char *buf, unsigned long len)
489 {
490 sec_asn1e_write_part(state, buf, len, SEC_ASN1_Contents);
491 }
492
493
494 static void
495 sec_asn1e_write_end_of_contents_bytes(sec_asn1e_state *state)
496 {
497 const char eoc[2] = {0, 0};
498
499 sec_asn1e_write_part(state, eoc, 2, SEC_ASN1_EndOfContents);
500 }
501
502 static int
503 sec_asn1e_which_choice(void *src, const SecAsn1Template *theTemplate)
504 {
505 int rv;
506 unsigned int which = *(unsigned int *)src;
507
508 for( rv = 1, theTemplate++; theTemplate->kind != 0; rv++, theTemplate++ ) {
509 if( which == theTemplate->size ) {
510 return rv;
511 }
512 }
513
514 return 0;
515 }
516
517 static unsigned long
518 sec_asn1e_contents_length(const SecAsn1Template *theTemplate, void *src,
519 PRBool ignoresubstream, PRBool insideIndefinite,
520 sec_asn1e_hdr_encoding *pHdrException)
521 {
522 unsigned long encode_kind, underlying_kind;
523 PRBool explicit, optional, universal, may_stream;
524 unsigned long len;
525 #ifdef __APPLE__
526 PRBool signedInt;
527 #endif
528
529 /*
530 * This function currently calculates the length in all cases
531 * except the following: when writing out the contents of a
532 * template that belongs to a state where it was a sub-template
533 * with the SEC_ASN1_MAY_STREAM bit set and it's parent had the
534 * optional bit set. The information that the parent is optional
535 * and that we should return the length of 0 when that length is
536 * present since that means the optional field is no longer present.
537 * So we add the ignoresubstream flag which is passed in when
538 * writing the contents, but for all recursive calls to
539 * sec_asn1e_contents_length, we pass PR_FALSE, because this
540 * function correctly calculates the length for children templates
541 * from that point on. Confused yet? At least you didn't have
542 * to figure it out. ;) -javi
543 */
544 encode_kind = theTemplate->kind;
545
546 universal = ((encode_kind & SEC_ASN1_CLASS_MASK) == SEC_ASN1_UNIVERSAL) ? PR_TRUE : PR_FALSE;
547
548 explicit = (encode_kind & SEC_ASN1_EXPLICIT) ? PR_TRUE : PR_FALSE;
549 encode_kind &= ~SEC_ASN1_EXPLICIT;
550
551 optional = (encode_kind & SEC_ASN1_OPTIONAL) ? PR_TRUE : PR_FALSE;
552 encode_kind &= ~SEC_ASN1_OPTIONAL;
553
554 PORT_Assert(!(explicit && universal)); /* bad templates */
555
556 may_stream = (encode_kind & SEC_ASN1_MAY_STREAM) ? PR_TRUE : PR_FALSE;
557 encode_kind &= ~SEC_ASN1_MAY_STREAM;
558
559 /* Just clear this to get it out of the way; we do not need it here */
560 encode_kind &= ~SEC_ASN1_DYNAMIC;
561
562 if (encode_kind & SEC_ASN1_NO_STREAM) {
563 ignoresubstream = PR_TRUE;
564 }
565 encode_kind &= ~SEC_ASN1_NO_STREAM;
566
567 if (encode_kind & SEC_ASN1_CHOICE) {
568 void *src2;
569 int indx = sec_asn1e_which_choice(src, theTemplate);
570 if( 0 == indx ) {
571 /* XXX set an error? "choice not found" */
572 /* state->top->status = encodeError; */
573 return 0;
574 }
575
576 src2 = (void *)((char *)src - theTemplate->offset + theTemplate[indx].offset);
577
578 return sec_asn1e_contents_length(&theTemplate[indx], src2,
579 ignoresubstream, insideIndefinite,
580 pHdrException);
581 }
582
583 if ((encode_kind & (SEC_ASN1_POINTER | SEC_ASN1_INLINE)) || !universal) {
584
585 /* XXX any bits we want to disallow (PORT_Assert against) here? */
586
587 theTemplate = SEC_ASN1GetSubtemplate(theTemplate, src, PR_TRUE,
588 NULL /* __APPLE__ */, 0 /* __APPLE__ */);
589
590 if (encode_kind & SEC_ASN1_POINTER) {
591 /*
592 * XXX This used to PORT_Assert (encode_kind == SEC_ASN1_POINTER);
593 * but that was too restrictive. This needs to be fixed,
594 * probably copying what the decoder now checks for, and
595 * adding a big comment here to explain what the checks mean.
596 * Alternatively, the check here could be omitted altogether
597 * just letting sec_asn1e_init_state_based_on_template
598 * do it, since that routine can do better error handling, too.
599 */
600 src = *(void **)src;
601 if (src == NULL) {
602 *pHdrException = optional ? hdr_optional : hdr_normal;
603 return 0;
604 }
605 } else if (encode_kind & SEC_ASN1_INLINE) {
606 /* check that there are no extraneous bits */
607 PORT_Assert (encode_kind == SEC_ASN1_INLINE && !optional);
608 }
609
610 src = (char *)src + theTemplate->offset;
611
612 len = sec_asn1e_contents_length(theTemplate, src,
613 ignoresubstream, insideIndefinite,
614 pHdrException);
615 if (len == 0 && optional) {
616 *pHdrException = hdr_optional;
617 } else if (explicit) {
618 if (*pHdrException == hdr_any) {
619 /* *we* do not want to add in a header,
620 ** but our caller still does.
621 */
622 *pHdrException = hdr_normal;
623 } else if (*pHdrException == hdr_normal) {
624 /* if the inner content exists, our length is
625 * len(identifier) + len(length) + len(innercontent)
626 * XXX we currently assume len(identifier) == 1;
627 * to support a high-tag-number this would need to be smarter.
628 */
629 len += 1 + SEC_ASN1LengthLength(len);
630 }
631 }
632 return len;
633 }
634
635 underlying_kind = encode_kind;
636
637 #ifdef __APPLE__
638 signedInt = (underlying_kind & SEC_ASN1_SIGNED_INT) ?
639 PR_TRUE : PR_FALSE;
640 #endif
641
642 /* This is only used in decoding; it plays no part in encoding. */
643 if (underlying_kind & SEC_ASN1_SAVE) {
644 /* check that there are no extraneous bits */
645 PORT_Assert (underlying_kind == SEC_ASN1_SAVE);
646 *pHdrException = hdr_decoder;
647 return 0;
648 }
649
650 /* Having any of these bits is not expected here... */
651 PORT_Assert ((underlying_kind & (SEC_ASN1_EXPLICIT | SEC_ASN1_OPTIONAL
652 | SEC_ASN1_INLINE | SEC_ASN1_POINTER
653 | SEC_ASN1_DYNAMIC | SEC_ASN1_MAY_STREAM
654 | SEC_ASN1_SAVE | SEC_ASN1_SKIP)) == 0);
655
656 if (underlying_kind & SEC_ASN1_CHOICE) {
657 void *src2;
658 int indx = sec_asn1e_which_choice(src, theTemplate);
659 if( 0 == indx ) {
660 /* XXX set an error? "choice not found" */
661 /* state->top->status = encodeError; */
662 return 0;
663 }
664
665 src2 = (void *)((char *)src - theTemplate->offset + theTemplate[indx].offset);
666 len = sec_asn1e_contents_length(&theTemplate[indx], src2, ignoresubstream,
667 insideIndefinite, pHdrException);
668 } else {
669 switch (underlying_kind) {
670 case SEC_ASN1_SEQUENCE_OF:
671 case SEC_ASN1_SET_OF: {
672 const SecAsn1Template *tmpt;
673 void *sub_src;
674 unsigned long sub_len;
675 void **group;
676
677 len = 0;
678
679 group = *(void ***)src;
680 if (group == NULL) {
681 break;
682 }
683
684 tmpt = SEC_ASN1GetSubtemplate(theTemplate, src, PR_TRUE,
685 NULL /* __APPLE__ */, 0 /* __APPLE__ */);
686
687 for (; *group != NULL; group++) {
688 sub_src = (char *)(*group) + tmpt->offset;
689 sub_len = sec_asn1e_contents_length(tmpt, sub_src, ignoresubstream,
690 insideIndefinite, pHdrException);
691 len += sub_len;
692 /*
693 * XXX The 1 below is the presumed length of the identifier;
694 * to support a high-tag-number this would need to be smarter.
695 */
696 if (*pHdrException == hdr_normal) {
697 len += 1 + SEC_ASN1LengthLength(sub_len);
698 }
699 }
700 }
701 break;
702
703 case SEC_ASN1_SEQUENCE:
704 case SEC_ASN1_SET: {
705 const SecAsn1Template *tmpt;
706 void *sub_src;
707 unsigned long sub_len;
708
709 len = 0;
710 for (tmpt = theTemplate + 1; tmpt->kind; tmpt++) {
711 sub_src = (char *)src + tmpt->offset;
712 sub_len = sec_asn1e_contents_length(tmpt, sub_src, ignoresubstream,
713 insideIndefinite, pHdrException);
714 len += sub_len;
715 /*
716 * XXX The 1 below is the presumed length of the identifier;
717 * to support a high-tag-number this would need to be smarter.
718 */
719 if (*pHdrException == hdr_normal) {
720 len += 1 + SEC_ASN1LengthLength (sub_len);
721 }
722 }
723 }
724 break;
725
726 case SEC_ASN1_BIT_STRING:
727 /* convert bit length to byte */
728 len = (((SecAsn1Item *)src)->Length + 7) >> 3;
729 /* bit string contents involve an extra octet */
730 if (len) {
731 len++;
732 }
733 break;
734
735 case SEC_ASN1_INTEGER: {
736 /* ASN.1 INTEGERs are signed.
737 * If the source is an unsigned integer, the encoder will need
738 * to handle the conversion here.
739 */
740 unsigned char *buf = ((SecAsn1Item *)src)->Data;
741 #ifndef __APPLE__
742 SecAsn1ItemType integerType = ((SecAsn1Item *)src)->type;
743 #endif
744 len = ((SecAsn1Item *)src)->Length;
745 while (len > 0) {
746 if (*buf != 0) {
747 #ifdef __APPLE__
748 if (*buf & 0x80 && !signedInt)
749 #else
750 if (*buf & 0x80 && integerType == siUnsignedInteger)
751 #endif // __APPLE__
752 {
753 len++; /* leading zero needed to make number signed */
754 }
755 break; /* reached beginning of number */
756 }
757 if (len == 1) {
758 break; /* the number 0 */
759 }
760 if (buf[1] & 0x80) {
761 break; /* leading zero already present */
762 }
763 /* extraneous leading zero, keep going */
764 buf++;
765 len--;
766 }
767 }
768 break;
769
770 default:
771 len = ((SecAsn1Item *)src)->Length;
772 break;
773 } /* end switch */
774
775 #ifndef WHAT_PROBLEM_DOES_THIS_SOLVE
776 /* if we're streaming, we may have a secitem w/len 0 as placeholder */
777 if (!len && insideIndefinite && may_stream && !ignoresubstream) {
778 len = 1;
779 }
780 #endif
781 } /* end else */
782
783 if (len == 0 && optional)
784 *pHdrException = hdr_optional;
785 else if (underlying_kind == SEC_ASN1_ANY)
786 *pHdrException = hdr_any;
787 else
788 *pHdrException = hdr_normal;
789
790 return len;
791 }
792
793
794 static void
795 sec_asn1e_write_header(sec_asn1e_state *state)
796 {
797 unsigned long contents_length;
798 unsigned char tag_number, tag_modifiers;
799 sec_asn1e_hdr_encoding hdrException = hdr_normal;
800 PRBool indefinite = PR_FALSE;
801
802 PORT_Assert (state->place == beforeHeader);
803
804 tag_number = state->tag_number;
805 tag_modifiers = state->tag_modifiers;
806
807 if (state->underlying_kind == SEC_ASN1_ANY) {
808 state->place = duringContents;
809 return;
810 }
811
812 if (state->underlying_kind & SEC_ASN1_CHOICE) {
813 int indx = sec_asn1e_which_choice(state->src, state->theTemplate);
814 if( 0 == indx ) {
815 /* XXX set an error? "choice not found" */
816 state->top->status = encodeError;
817 return;
818 }
819
820 state->place = afterChoice;
821 state = sec_asn1e_push_state(state->top, &state->theTemplate[indx],
822 (char *)state->src - state->theTemplate->offset,
823 PR_TRUE);
824
825 if (state) {
826 /*
827 * Do the "before" field notification.
828 */
829 sec_asn1e_notify_before (state->top, state->src, state->depth);
830 (void)sec_asn1e_init_state_based_on_template (state);
831 }
832 return;
833 }
834
835 /* The !isString test below is apparently intended to ensure that all
836 ** constructed types receive indefinite length encoding.
837 */
838 indefinite = (PRBool)(state->top->streaming && state->may_stream &&
839 (state->top->from_buf || !state->is_string));
840
841 /*
842 * If we are doing a definite-length encoding, first we have to
843 * walk the data structure to calculate the entire contents length.
844 * If we are doing an indefinite-length encoding, we still need to
845 * know if the contents is:
846 * optional and to be omitted, or
847 * an ANY (header is pre-encoded), or
848 * a SAVE or some other kind of template used only by the decoder.
849 * So, we call this function either way.
850 */
851 contents_length = sec_asn1e_contents_length(state->theTemplate,
852 state->src,
853 state->ignore_stream,
854 indefinite,
855 &hdrException);
856 /*
857 * We might be told explicitly not to put out a header.
858 * But it can also be the case, via a pushed subtemplate, that
859 * sec_asn1e_contents_length could not know that this field is
860 * really optional. So check for that explicitly, too.
861 */
862 if (hdrException != hdr_normal ||
863 (contents_length == 0 && state->optional)) {
864 state->place = afterContents;
865 if (state->top->streaming &&
866 state->may_stream &&
867 state->top->from_buf) {
868 /* we did not find an optional indefinite string, so we
869 * don't encode it. However, if TakeFromBuf is on, we stop
870 * here anyway to give our caller a chance to intercept at the
871 * same point where we would stop if the field were present.
872 */
873 state->top->status = needBytes;
874 }
875 return;
876 }
877
878 if (indefinite) {
879 /*
880 * We need to put out an indefinite-length encoding.
881 * The only universal types that can be constructed are SETs,
882 * SEQUENCEs, and strings; so check that it is one of those,
883 * or that it is not universal (e.g. context-specific).
884 */
885 state->indefinite = PR_TRUE;
886 PORT_Assert ((tag_number == SEC_ASN1_SET)
887 || (tag_number == SEC_ASN1_SEQUENCE)
888 || ((tag_modifiers & SEC_ASN1_CLASS_MASK) != 0)
889 || state->is_string);
890 tag_modifiers |= SEC_ASN1_CONSTRUCTED;
891 contents_length = 0;
892 }
893
894 sec_asn1e_write_identifier_bytes(state, (unsigned char)(tag_number | tag_modifiers));
895 sec_asn1e_write_length_bytes(state, contents_length, state->indefinite);
896
897 if (contents_length == 0 && !state->indefinite) {
898 /*
899 * If no real contents to encode, then we are done with this field.
900 */
901 state->place = afterContents;
902 return;
903 }
904
905 /*
906 * An EXPLICIT is nothing but an outer header, which we have already
907 * written. Now we need to do the inner header and contents.
908 */
909 if (state->explicit) {
910 state->place = afterContents;
911 const SecAsn1Template *subt = SEC_ASN1GetSubtemplate(state->theTemplate, state->src, PR_TRUE,
912 NULL /* __APPLE__ */, 0 /* __APPLE__ */);
913 state = sec_asn1e_push_state(state->top, subt, state->src, PR_TRUE);
914 if (state != NULL) {
915 (void)sec_asn1e_init_state_based_on_template(state);
916 }
917 return;
918 }
919
920 switch (state->underlying_kind) {
921 case SEC_ASN1_SET_OF:
922 case SEC_ASN1_SEQUENCE_OF: {
923 /*
924 * We need to push a child to handle each member.
925 */
926 void **group;
927 const SecAsn1Template *subt;
928
929 group = *(void ***)state->src;
930 if (group == NULL || *group == NULL) {
931 /*
932 * Group is empty; we are done.
933 */
934 state->place = afterContents;
935 return;
936 }
937 state->place = duringGroup;
938 subt = SEC_ASN1GetSubtemplate(state->theTemplate, state->src,
939 PR_TRUE, NULL /* __APPLE__ */, 0 /* __APPLE__ */);
940 state = sec_asn1e_push_state(state->top, subt, *group, PR_TRUE);
941 if (state != NULL) {
942 (void)sec_asn1e_init_state_based_on_template(state);
943 }
944 }
945 break;
946
947 case SEC_ASN1_SEQUENCE:
948 case SEC_ASN1_SET:
949 /*
950 * We need to push a child to handle the individual fields.
951 */
952 state->place = duringSequence;
953 state = sec_asn1e_push_state(state->top, state->theTemplate + 1,
954 state->src, PR_TRUE);
955 if (state != NULL) {
956 /*
957 * Do the "before" field notification.
958 */
959 sec_asn1e_notify_before(state->top, state->src, state->depth);
960 (void)sec_asn1e_init_state_based_on_template(state);
961 }
962 break;
963
964 default:
965 /*
966 * I think we do not need to do anything else.
967 * XXX Correct?
968 */
969 state->place = duringContents;
970 break;
971 }
972 }
973
974
975 static void
976 sec_asn1e_write_contents_from_buf(sec_asn1e_state *state,
977 const char *buf, unsigned long len)
978 {
979 PORT_Assert(state->place == duringContents);
980 PORT_Assert(state->top->from_buf);
981 PORT_Assert(state->may_stream && !state->ignore_stream);
982
983 /*
984 * Probably they just turned on "take from buf", but have not
985 * yet given us any bytes. If there is nothing in the buffer
986 * then we have nothing to do but return and wait.
987 */
988 if (buf == NULL || len == 0) {
989 state->top->status = needBytes;
990 return;
991 }
992 /*
993 * We are streaming, reading from a passed-in buffer.
994 * This means we are encoding a simple string or an ANY.
995 * For the former, we need to put out a substring, with its
996 * own identifier and length. For an ANY, we just write it
997 * out as is (our caller is required to ensure that it
998 * is a properly encoded entity).
999 */
1000 PORT_Assert(state->is_string); /* includes ANY */
1001 if (state->underlying_kind != SEC_ASN1_ANY) {
1002 unsigned char identifier;
1003
1004 /*
1005 * Create the identifier based on underlying_kind. We cannot
1006 * use tag_number and tag_modifiers because this can be an
1007 * implicitly encoded field. In that case, the underlying
1008 * substrings *are* encoded with their real tag.
1009 */
1010 identifier = (unsigned char)(state->underlying_kind & SEC_ASN1_TAG_MASK);
1011 /*
1012 * The underlying kind should just be a simple string; there
1013 * should be no bits like CONTEXT_SPECIFIC or CONSTRUCTED set.
1014 */
1015 PORT_Assert((identifier & SEC_ASN1_TAGNUM_MASK) == identifier);
1016 /*
1017 * Write out the tag and length for the substring.
1018 */
1019 sec_asn1e_write_identifier_bytes(state, identifier);
1020 if (state->underlying_kind == SEC_ASN1_BIT_STRING) {
1021 char byte;
1022 /*
1023 * Assume we have a length in bytes but we need to output
1024 * a proper bit string. This interface only works for bit
1025 * strings that are full multiples of 8. If support for
1026 * real, variable length bit strings is needed then the
1027 * caller will have to know to pass in a bit length instead
1028 * of a byte length and then this code will have to
1029 * perform the encoding necessary (length written is length
1030 * in bytes plus 1, and the first octet of string is the
1031 * number of bits remaining between the end of the bit
1032 * string and the next byte boundary).
1033 */
1034 sec_asn1e_write_length_bytes(state, len + 1, PR_FALSE);
1035 byte = 0;
1036 sec_asn1e_write_contents_bytes(state, &byte, 1);
1037 } else {
1038 sec_asn1e_write_length_bytes(state, len, PR_FALSE);
1039 }
1040 }
1041 sec_asn1e_write_contents_bytes(state, buf, len);
1042 state->top->status = needBytes;
1043 }
1044
1045 static void
1046 sec_asn1e_write_contents(sec_asn1e_state *state)
1047 {
1048 unsigned long len = 0;
1049
1050 PORT_Assert(state->place == duringContents);
1051 switch (state->underlying_kind) {
1052 case SEC_ASN1_SET:
1053 case SEC_ASN1_SEQUENCE:
1054 PORT_Assert (0);
1055 break;
1056
1057 case SEC_ASN1_BIT_STRING: {
1058 SecAsn1Item *item;
1059 char rem;
1060
1061 item = (SecAsn1Item *)state->src;
1062 len = (item->Length + 7) >> 3;
1063 rem = (unsigned char)((len << 3) - item->Length); /* remaining bits */
1064 sec_asn1e_write_contents_bytes(state, &rem, 1);
1065 sec_asn1e_write_contents_bytes(state, (char *) item->Data, len);
1066 }
1067 break;
1068
1069 case SEC_ASN1_BMP_STRING:
1070 /* The number of bytes must be divisable by 2 */
1071 if ((((SecAsn1Item *)state->src)->Length) % 2) {
1072 SEC_ASN1EncoderContext *cx;
1073
1074 cx = state->top;
1075 cx->status = encodeError;
1076 break;
1077 }
1078 /* otherwise, fall through to write the content */
1079 goto process_string;
1080
1081 case SEC_ASN1_UNIVERSAL_STRING:
1082 /* The number of bytes must be divisable by 4 */
1083 if ((((SecAsn1Item *)state->src)->Length) % 4) {
1084 SEC_ASN1EncoderContext *cx;
1085
1086 cx = state->top;
1087 cx->status = encodeError;
1088 break;
1089 }
1090 /* otherwise, fall through to write the content */
1091 goto process_string;
1092
1093 case SEC_ASN1_INTEGER: {
1094 /* ASN.1 INTEGERs are signed. If the source is an unsigned
1095 * integer, the encoder will need to handle the conversion here.
1096 */
1097 size_t blen;
1098 unsigned char *intbuf;
1099 #ifdef __APPLE__
1100 PRBool signedInt = state->signedInt;
1101 #else
1102 SECItemType integerType = ((SecAsn1Item *)state->src)->type;
1103 #endif
1104 blen = ((SecAsn1Item *)state->src)->Length;
1105 intbuf = ((SecAsn1Item *)state->src)->Data;
1106 while (blen > 0) {
1107 #ifdef __APPLE__
1108 if (*intbuf & 0x80 && !signedInt)
1109 #else
1110 if (*intbuf & 0x80 && integerType == siUnsignedInteger)
1111 #endif
1112 {
1113 char zero = 0; /* write a leading 0 */
1114 sec_asn1e_write_contents_bytes(state, &zero, 1);
1115 /* and then the remaining buffer */
1116 sec_asn1e_write_contents_bytes(state, (char *)intbuf, blen);
1117 break;
1118 }
1119 /* Check three possibilities:
1120 * 1. No leading zeros, msb of MSB is not 1;
1121 * 2. The number is zero itself;
1122 * 3. Encoding a signed integer with a leading zero,
1123 * keep the zero so that the number is positive.
1124 */
1125 if (*intbuf != 0 ||
1126 blen == 1 ||
1127 #ifdef __APPLE__
1128 (intbuf[1] & 0x80 && signedInt) )
1129 #else
1130 (intbuf[1] & 0x80 && integerType != siUnsignedInteger) )
1131 #endif
1132 {
1133 sec_asn1e_write_contents_bytes(state, (char *)intbuf, blen);
1134 break;
1135 }
1136 /* byte is 0, continue */
1137 intbuf++;
1138 blen--;
1139 }
1140 }
1141 /* done with this content */
1142 break;
1143
1144 process_string:
1145 default:
1146 {
1147 SecAsn1Item *item;
1148
1149 item = (SecAsn1Item *)state->src;
1150 sec_asn1e_write_contents_bytes(state, (char *) item->Data, item->Length);
1151 }
1152 break;
1153 }
1154 state->place = afterContents;
1155 }
1156
1157
1158 /*
1159 * We are doing a SET OF or SEQUENCE OF, and have just finished an item.
1160 */
1161 static void
1162 sec_asn1e_next_in_group(sec_asn1e_state *state)
1163 {
1164 sec_asn1e_state *child;
1165 void **group;
1166 void *member;
1167
1168 PORT_Assert(state->place == duringGroup);
1169 PORT_Assert(state->child != NULL);
1170
1171 child = state->child;
1172
1173 group = *(void ***)state->src;
1174
1175 /*
1176 * Find placement of current item.
1177 */
1178 member = (char *)(state->child->src) - child->theTemplate->offset;
1179 while (*group != member) {
1180 group++;
1181 }
1182
1183 /*
1184 * Move forward to next item.
1185 */
1186 group++;
1187 if (*group == NULL) {
1188 /*
1189 * That was our last one; we are done now.
1190 */
1191 child->place = notInUse;
1192 state->place = afterContents;
1193 return;
1194 }
1195 child->src = (char *)(*group) + child->theTemplate->offset;
1196
1197 /*
1198 * Re-"push" child.
1199 */
1200 sec_asn1e_scrub_state(child);
1201 state->top->current = child;
1202 }
1203
1204
1205 /*
1206 * We are moving along through a sequence; move forward by one,
1207 * (detecting end-of-sequence when it happens).
1208 */
1209 static void
1210 sec_asn1e_next_in_sequence(sec_asn1e_state *state)
1211 {
1212 sec_asn1e_state *child;
1213
1214 PORT_Assert(state->place == duringSequence);
1215 PORT_Assert(state->child != NULL);
1216
1217 child = state->child;
1218
1219 /*
1220 * Do the "after" field notification.
1221 */
1222 sec_asn1e_notify_after(state->top, child->src, child->depth);
1223
1224 /*
1225 * Move forward.
1226 */
1227 child->theTemplate++;
1228 if (child->theTemplate->kind == 0) {
1229 /*
1230 * We are done with this sequence.
1231 */
1232 child->place = notInUse;
1233 state->place = afterContents;
1234 return;
1235 }
1236
1237 /*
1238 * Reset state and push.
1239 */
1240
1241 child->src = (char *)state->src + child->theTemplate->offset;
1242
1243 /*
1244 * Do the "before" field notification.
1245 */
1246 sec_asn1e_notify_before(state->top, child->src, child->depth);
1247
1248 state->top->current = child;
1249 (void)sec_asn1e_init_state_based_on_template(child);
1250 }
1251
1252
1253 static void
1254 sec_asn1e_after_contents (sec_asn1e_state *state)
1255 {
1256 PORT_Assert(state->place == afterContents);
1257
1258 if (state->indefinite) {
1259 sec_asn1e_write_end_of_contents_bytes(state);
1260 }
1261
1262 /*
1263 * Just make my parent be the current state. It will then clean
1264 * up after me and free me (or reuse me).
1265 */
1266 state->top->current = state->parent;
1267 }
1268
1269
1270 /*
1271 * This function is called whether or not we are streaming; if we
1272 * *are* streaming, our caller can also instruct us to take bytes
1273 * from the passed-in buffer (at buf, for length len, which is likely
1274 * bytes but could even mean bits if the current field is a bit string).
1275 * If we have been so instructed, we will gobble up bytes from there
1276 * (rather than from our src structure) and output them, and then
1277 * we will just return, expecting to be called again -- either with
1278 * more bytes or after our caller has instructed us that we are done
1279 * (for now) with the buffer.
1280 */
1281 SECStatus
1282 SEC_ASN1EncoderUpdate(SEC_ASN1EncoderContext *cx,
1283 const char *buf, unsigned long len)
1284 {
1285 sec_asn1e_state *state;
1286
1287 if (cx->status == needBytes) {
1288 PORT_Assert(buf != NULL && len != 0);
1289 cx->status = keepGoing;
1290 }
1291
1292 while (cx->status == keepGoing) {
1293 state = cx->current;
1294 switch (state->place) {
1295 case beforeHeader:
1296 sec_asn1e_write_header(state);
1297 break;
1298 case duringContents:
1299 if (cx->from_buf)
1300 sec_asn1e_write_contents_from_buf(state, buf, len);
1301 else
1302 sec_asn1e_write_contents(state);
1303 break;
1304 case duringGroup:
1305 sec_asn1e_next_in_group(state);
1306 break;
1307 case duringSequence:
1308 sec_asn1e_next_in_sequence(state);
1309 break;
1310 case afterContents:
1311 sec_asn1e_after_contents(state);
1312 break;
1313 case afterImplicit:
1314 case afterInline:
1315 case afterPointer:
1316 case afterChoice:
1317 /*
1318 * These states are more documentation than anything.
1319 * They just need to force a pop.
1320 */
1321 PORT_Assert(!state->indefinite);
1322 state->place = afterContents;
1323 break;
1324 case notInUse:
1325 default:
1326 /* This is not an error, but rather a plain old BUG! */
1327 PORT_Assert(0);
1328 cx->status = encodeError;
1329 break;
1330 }
1331
1332 if (cx->status == encodeError) {
1333 break;
1334 }
1335
1336 /* It might have changed, so we have to update our local copy. */
1337 state = cx->current;
1338
1339 /* If it is NULL, we have popped all the way to the top. */
1340 if (state == NULL) {
1341 cx->status = allDone;
1342 break;
1343 }
1344 }
1345
1346 if (cx->status == encodeError) {
1347 return SECFailure;
1348 }
1349
1350 return SECSuccess;
1351 }
1352
1353
1354 void
1355 SEC_ASN1EncoderFinish(SEC_ASN1EncoderContext *cx)
1356 {
1357 /*
1358 * XXX anything else that needs to be finished?
1359 */
1360
1361 PORT_FreeArena(cx->our_pool, PR_FALSE);
1362 }
1363
1364
1365 SEC_ASN1EncoderContext *
1366 SEC_ASN1EncoderStart(const void *src, const SecAsn1Template *theTemplate,
1367 SEC_ASN1WriteProc output_proc, void *output_arg)
1368 {
1369 PRArenaPool *our_pool;
1370 SEC_ASN1EncoderContext *cx;
1371
1372 our_pool = PORT_NewArena(SEC_ASN1_DEFAULT_ARENA_SIZE);
1373 if (our_pool == NULL) {
1374 return NULL;
1375 }
1376
1377 cx = (SEC_ASN1EncoderContext*)PORT_ArenaZAlloc(our_pool, sizeof(*cx));
1378 if (cx == NULL) {
1379 PORT_FreeArena(our_pool, PR_FALSE);
1380 return NULL;
1381 }
1382
1383 cx->our_pool = our_pool;
1384 cx->output_proc = output_proc;
1385 cx->output_arg = output_arg;
1386
1387 cx->status = keepGoing;
1388
1389 if (sec_asn1e_push_state(cx, theTemplate, src, PR_FALSE) == NULL
1390 || sec_asn1e_init_state_based_on_template(cx->current) == NULL) {
1391 /*
1392 * Trouble initializing (probably due to failed allocations)
1393 * requires that we just give up.
1394 */
1395 PORT_FreeArena (our_pool,PR_FALSE);
1396 return NULL;
1397 }
1398
1399 return cx;
1400 }
1401
1402
1403 /*
1404 * XXX Do we need a FilterProc, too?
1405 */
1406
1407
1408 void
1409 SEC_ASN1EncoderSetNotifyProc(SEC_ASN1EncoderContext *cx,
1410 SEC_ASN1NotifyProc fn, void *arg)
1411 {
1412 cx->notify_proc = fn;
1413 cx->notify_arg = arg;
1414 }
1415
1416
1417 void
1418 SEC_ASN1EncoderClearNotifyProc(SEC_ASN1EncoderContext *cx)
1419 {
1420 cx->notify_proc = NULL;
1421 cx->notify_arg = NULL; /* not necessary; just being clean */
1422 }
1423
1424
1425 void
1426 SEC_ASN1EncoderAbort(SEC_ASN1EncoderContext *cx, int error)
1427 {
1428 PORT_Assert(cx);
1429 PORT_SetError(error);
1430 cx->status = encodeError;
1431 }
1432
1433
1434 void
1435 SEC_ASN1EncoderSetStreaming(SEC_ASN1EncoderContext *cx)
1436 {
1437 /* XXX is there a way to check that we are "between" fields here? */
1438
1439 cx->streaming = PR_TRUE;
1440 }
1441
1442
1443 void
1444 SEC_ASN1EncoderClearStreaming(SEC_ASN1EncoderContext *cx)
1445 {
1446 /* XXX is there a way to check that we are "between" fields here? */
1447
1448 cx->streaming = PR_FALSE;
1449 }
1450
1451
1452 void
1453 SEC_ASN1EncoderSetTakeFromBuf(SEC_ASN1EncoderContext *cx)
1454 {
1455 /*
1456 * XXX is there a way to check that we are "between" fields here? this
1457 * needs to include a check for being in between groups of items in
1458 * a SET_OF or SEQUENCE_OF.
1459 */
1460 PORT_Assert(cx->streaming);
1461 cx->from_buf = PR_TRUE;
1462 }
1463
1464
1465 void
1466 SEC_ASN1EncoderClearTakeFromBuf(SEC_ASN1EncoderContext *cx)
1467 {
1468 /* we should actually be taking from buf *now* */
1469 PORT_Assert (cx->from_buf);
1470 if (! cx->from_buf) { /* if not, just do nothing */
1471 return;
1472 }
1473
1474 cx->from_buf = PR_FALSE;
1475
1476 if (cx->status == needBytes) {
1477 cx->status = keepGoing;
1478 cx->current->place = afterContents;
1479 }
1480 }
1481
1482
1483 SECStatus
1484 SEC_ASN1Encode(const void *src, const SecAsn1Template *theTemplate,
1485 SEC_ASN1WriteProc output_proc, void *output_arg)
1486 {
1487 SEC_ASN1EncoderContext *ecx;
1488 SECStatus rv;
1489
1490 ecx = SEC_ASN1EncoderStart(src, theTemplate, output_proc, output_arg);
1491 if (ecx == NULL) {
1492 return SECFailure;
1493 }
1494
1495 rv = SEC_ASN1EncoderUpdate(ecx, NULL, 0);
1496
1497 SEC_ASN1EncoderFinish(ecx);
1498 return rv;
1499 }
1500
1501
1502 /*
1503 * XXX depth and data_kind are unused; is there a PC way to silence warnings?
1504 * (I mean "politically correct", not anything to do with intel/win platform)
1505 */
1506 void
1507 sec_asn1e_encode_item_count(void *arg, const char *buf, size_t len,
1508 int depth, SEC_ASN1EncodingPart data_kind)
1509 {
1510 size_t *count;
1511
1512 count = (unsigned long*)arg;
1513 PORT_Assert(count != NULL);
1514
1515 *count += len;
1516 }
1517
1518
1519 /* XXX depth and data_kind are unused; is there a PC way to silence warnings? */
1520 void
1521 sec_asn1e_encode_item_store(void *arg, const char *buf, size_t len,
1522 int depth, SEC_ASN1EncodingPart data_kind)
1523 {
1524 SecAsn1Item *dest;
1525
1526 dest = (SecAsn1Item*)arg;
1527 PORT_Assert(dest != NULL);
1528
1529 if (len > 0) {
1530 PORT_Memcpy(dest->Data + dest->Length, buf, len);
1531 dest->Length += len;
1532 }
1533 }
1534
1535
1536 /*
1537 * Allocate an entire SecAsn1Item, or just the data part of it, to hold
1538 * "len" bytes of stuff. Allocate from the given pool, if specified,
1539 * otherwise just do a vanilla PORT_Alloc.
1540 *
1541 * XXX This seems like a reasonable general-purpose function (for SECITEM_)?
1542 */
1543 SecAsn1Item *
1544 sec_asn1e_allocate_item(PRArenaPool *poolp, SecAsn1Item *dest, unsigned long len)
1545 {
1546 if (poolp != NULL) {
1547 void *release;
1548
1549 release = PORT_ArenaMark(poolp);
1550 if (dest == NULL) {
1551 dest = (SecAsn1Item*)PORT_ArenaAlloc(poolp, sizeof(SecAsn1Item));
1552 }
1553 if (dest != NULL) {
1554 dest->Data = (unsigned char*)PORT_ArenaAlloc(poolp, len);
1555 if (dest->Data == NULL) {
1556 dest = NULL;
1557 }
1558 }
1559 if (dest == NULL) {
1560 /* one or both allocations failed; release everything */
1561 PORT_ArenaRelease(poolp, release);
1562 } else {
1563 /* everything okay; unmark the arena */
1564 PORT_ArenaUnmark(poolp, release);
1565 }
1566 } else {
1567 SecAsn1Item *indest;
1568
1569 indest = dest;
1570 if (dest == NULL) {
1571 dest = (SecAsn1Item*)PORT_Alloc(sizeof(SecAsn1Item));
1572 }
1573 if (dest != NULL) {
1574 #ifndef __APPLE__
1575 dest->type = siBuffer;
1576 #endif
1577 dest->Data = (unsigned char*)PORT_Alloc(len);
1578 if (dest->Data == NULL) {
1579 if (indest == NULL) {
1580 PORT_Free(dest);
1581 }
1582 dest = NULL;
1583 }
1584 }
1585 }
1586
1587 return dest;
1588 }
1589
1590
1591 SecAsn1Item *
1592 SEC_ASN1EncodeItem(PRArenaPool *poolp, SecAsn1Item *dest, const void *src,
1593 const SecAsn1Template *theTemplate)
1594 {
1595 unsigned long encoding_length;
1596 SECStatus rv;
1597
1598 PORT_Assert(dest == NULL || dest->Data == NULL);
1599
1600 encoding_length = 0;
1601 rv = SEC_ASN1Encode(src, theTemplate,
1602 sec_asn1e_encode_item_count, &encoding_length);
1603 if (rv != SECSuccess) {
1604 return NULL;
1605 }
1606
1607 dest = sec_asn1e_allocate_item(poolp, dest, encoding_length);
1608 if (dest == NULL) {
1609 return NULL;
1610 }
1611
1612 /* XXX necessary? This really just checks for a bug in the allocate fn */
1613 PORT_Assert(dest->Data != NULL);
1614 if (dest->Data == NULL) {
1615 return NULL;
1616 }
1617
1618 dest->Length = 0;
1619 (void)SEC_ASN1Encode(src, theTemplate, sec_asn1e_encode_item_store, dest);
1620
1621 PORT_Assert(encoding_length == dest->Length);
1622 return dest;
1623 }
1624
1625
1626 static SecAsn1Item *
1627 sec_asn1e_integer(PRArenaPool *poolp, SecAsn1Item *dest, unsigned long value,
1628 PRBool make_unsigned)
1629 {
1630 unsigned long copy;
1631 unsigned char sign;
1632 int len = 0;
1633
1634 /*
1635 * Determine the length of the encoded value (minimum of 1).
1636 */
1637 copy = value;
1638 do {
1639 len++;
1640 sign = (unsigned char)(copy & 0x80);
1641 copy >>= 8;
1642 } while (copy);
1643
1644 /*
1645 * If this is an unsigned encoding, and the high bit of the last
1646 * byte we counted was set, we need to add one to the length so
1647 * we put a high-order zero byte in the encoding.
1648 */
1649 if (sign && make_unsigned) {
1650 len++;
1651 }
1652
1653 /*
1654 * Allocate the item (if necessary) and the data pointer within.
1655 */
1656 dest = sec_asn1e_allocate_item(poolp, dest, len);
1657 if (dest == NULL) {
1658 return NULL;
1659 }
1660
1661 /*
1662 * Store the value, byte by byte, in the item.
1663 */
1664 dest->Length = len;
1665 while (len) {
1666 dest->Data[--len] = (unsigned char)value;
1667 value >>= 8;
1668 }
1669 PORT_Assert(value == 0);
1670
1671 return dest;
1672 }
1673
1674
1675 SecAsn1Item *
1676 SEC_ASN1EncodeInteger(PRArenaPool *poolp, SecAsn1Item *dest, long value)
1677 {
1678 return sec_asn1e_integer(poolp, dest, (unsigned long) value, PR_FALSE);
1679 }
1680
1681
1682 extern SecAsn1Item *
1683 SEC_ASN1EncodeUnsignedInteger(PRArenaPool *poolp,
1684 SecAsn1Item *dest, unsigned long value)
1685 {
1686 return sec_asn1e_integer(poolp, dest, value, PR_TRUE);
1687 }