a_i2d_fp.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. /*
  2. * Copyright 1995-2020 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/buffer.h>
  12. #include <openssl/asn1.h>
  13. #ifndef NO_OLD_ASN1
  14. # ifndef OPENSSL_NO_STDIO
  15. int ASN1_i2d_fp(i2d_of_void *i2d, FILE *out, const void *x)
  16. {
  17. BIO *b;
  18. int ret;
  19. if ((b = BIO_new(BIO_s_file())) == NULL) {
  20. ERR_raise(ERR_LIB_ASN1, ERR_R_BUF_LIB);
  21. return 0;
  22. }
  23. BIO_set_fp(b, out, BIO_NOCLOSE);
  24. ret = ASN1_i2d_bio(i2d, b, x);
  25. BIO_free(b);
  26. return ret;
  27. }
  28. # endif
  29. int ASN1_i2d_bio(i2d_of_void *i2d, BIO *out, const void *x)
  30. {
  31. char *b;
  32. unsigned char *p;
  33. int i, j = 0, n, ret = 1;
  34. n = i2d(x, NULL);
  35. if (n <= 0)
  36. return 0;
  37. b = OPENSSL_malloc(n);
  38. if (b == NULL) {
  39. ERR_raise(ERR_LIB_ASN1, ERR_R_MALLOC_FAILURE);
  40. return 0;
  41. }
  42. p = (unsigned char *)b;
  43. i2d(x, &p);
  44. for (;;) {
  45. i = BIO_write(out, &(b[j]), n);
  46. if (i == n)
  47. break;
  48. if (i <= 0) {
  49. ret = 0;
  50. break;
  51. }
  52. j += i;
  53. n -= i;
  54. }
  55. OPENSSL_free(b);
  56. return ret;
  57. }
  58. #endif
  59. #ifndef OPENSSL_NO_STDIO
  60. int ASN1_item_i2d_fp(const ASN1_ITEM *it, FILE *out, const void *x)
  61. {
  62. BIO *b;
  63. int ret;
  64. if ((b = BIO_new(BIO_s_file())) == NULL) {
  65. ERR_raise(ERR_LIB_ASN1, ERR_R_BUF_LIB);
  66. return 0;
  67. }
  68. BIO_set_fp(b, out, BIO_NOCLOSE);
  69. ret = ASN1_item_i2d_bio(it, b, x);
  70. BIO_free(b);
  71. return ret;
  72. }
  73. #endif
  74. int ASN1_item_i2d_bio(const ASN1_ITEM *it, BIO *out, const void *x)
  75. {
  76. unsigned char *b = NULL;
  77. int i, j = 0, n, ret = 1;
  78. n = ASN1_item_i2d(x, &b, it);
  79. if (b == NULL) {
  80. ERR_raise(ERR_LIB_ASN1, ERR_R_MALLOC_FAILURE);
  81. return 0;
  82. }
  83. for (;;) {
  84. i = BIO_write(out, &(b[j]), n);
  85. if (i == n)
  86. break;
  87. if (i <= 0) {
  88. ret = 0;
  89. break;
  90. }
  91. j += i;
  92. n -= i;
  93. }
  94. OPENSSL_free(b);
  95. return ret;
  96. }