a_dup.c 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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. ERR_raise(ERR_LIB_ASN1, ERR_R_MALLOC_FAILURE);
  27. return NULL;
  28. }
  29. p = b;
  30. i = i2d(x, &p);
  31. p2 = b;
  32. ret = d2i(NULL, &p2, i);
  33. OPENSSL_free(b);
  34. return ret;
  35. }
  36. #endif
  37. /*
  38. * ASN1_ITEM version of dup: this follows the model above except we don't
  39. * need to allocate the buffer. At some point this could be rewritten to
  40. * directly dup the underlying structure instead of doing and encode and
  41. * decode.
  42. */
  43. void *ASN1_item_dup(const ASN1_ITEM *it, const void *x)
  44. {
  45. ASN1_aux_cb *asn1_cb = NULL;
  46. unsigned char *b = NULL;
  47. const unsigned char *p;
  48. long i;
  49. ASN1_VALUE *ret;
  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. && !asn1_cb(ASN1_OP_DUP_PRE, (ASN1_VALUE **)&x, it, NULL))
  59. goto auxerr;
  60. i = ASN1_item_i2d(x, &b, it);
  61. if (b == NULL) {
  62. ERR_raise(ERR_LIB_ASN1, ERR_R_MALLOC_FAILURE);
  63. return NULL;
  64. }
  65. p = b;
  66. ret = ASN1_item_d2i(NULL, &p, i, it);
  67. OPENSSL_free(b);
  68. if (asn1_cb != NULL
  69. && !asn1_cb(ASN1_OP_DUP_POST, &ret, it, (void *)x))
  70. goto auxerr;
  71. return ret;
  72. auxerr:
  73. ERR_raise_data(ERR_LIB_ASN1, ASN1_R_AUX_ERROR, "Type=%s", it->sname);
  74. return NULL;
  75. }