a_dup.c 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. /*
  2. * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
  3. *
  4. * Licensed under the Apache License 2.0 (the "License"). You may not use
  5. * this file except in compliance with the License. You can obtain a copy
  6. * in the file LICENSE in the source distribution or at
  7. * https://www.openssl.org/source/license.html
  8. */
  9. #include <stdio.h>
  10. #include "internal/cryptlib.h"
  11. #include <openssl/asn1t.h>
  12. #ifndef NO_OLD_ASN1
  13. void *ASN1_dup(i2d_of_void *i2d, d2i_of_void *d2i, const void *x)
  14. {
  15. unsigned char *b, *p;
  16. const unsigned char *p2;
  17. int i;
  18. char *ret;
  19. if (x == NULL)
  20. return NULL;
  21. i = i2d(x, NULL);
  22. if (i <= 0)
  23. return NULL;
  24. b = OPENSSL_malloc(i + 10);
  25. if (b == NULL)
  26. return NULL;
  27. p = b;
  28. i = i2d(x, &p);
  29. p2 = b;
  30. ret = d2i(NULL, &p2, i);
  31. OPENSSL_free(b);
  32. return ret;
  33. }
  34. #endif
  35. /*
  36. * ASN1_ITEM version of dup: this follows the model above except we don't
  37. * need to allocate the buffer. At some point this could be rewritten to
  38. * directly dup the underlying structure instead of doing and encode and
  39. * decode.
  40. */
  41. void *ASN1_item_dup(const ASN1_ITEM *it, const void *x)
  42. {
  43. ASN1_aux_cb *asn1_cb = NULL;
  44. unsigned char *b = NULL;
  45. const unsigned char *p;
  46. long i;
  47. ASN1_VALUE *ret;
  48. OSSL_LIB_CTX *libctx = NULL;
  49. const char *propq = NULL;
  50. if (x == NULL)
  51. return NULL;
  52. if (it->itype == ASN1_ITYPE_SEQUENCE || it->itype == ASN1_ITYPE_CHOICE
  53. || it->itype == ASN1_ITYPE_NDEF_SEQUENCE) {
  54. const ASN1_AUX *aux = it->funcs;
  55. asn1_cb = aux != NULL ? aux->asn1_cb : NULL;
  56. }
  57. if (asn1_cb != NULL) {
  58. if (!asn1_cb(ASN1_OP_DUP_PRE, (ASN1_VALUE **)&x, it, NULL)
  59. || !asn1_cb(ASN1_OP_GET0_LIBCTX, (ASN1_VALUE **)&x, it, &libctx)
  60. || !asn1_cb(ASN1_OP_GET0_PROPQ, (ASN1_VALUE **)&x, it, &propq))
  61. goto auxerr;
  62. }
  63. i = ASN1_item_i2d(x, &b, it);
  64. if (b == NULL) {
  65. ERR_raise(ERR_LIB_ASN1, ERR_R_ASN1_LIB);
  66. return NULL;
  67. }
  68. p = b;
  69. ret = ASN1_item_d2i_ex(NULL, &p, i, it, libctx, propq);
  70. OPENSSL_free(b);
  71. if (asn1_cb != NULL
  72. && !asn1_cb(ASN1_OP_DUP_POST, &ret, it, (void *)x))
  73. goto auxerr;
  74. return ret;
  75. auxerr:
  76. ERR_raise_data(ERR_LIB_ASN1, ASN1_R_AUX_ERROR, "Type=%s", it->sname);
  77. return NULL;
  78. }