secasn1e.c 50 KB

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