util.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. /*
  2. * util.c
  3. *
  4. * Copyright (C) AB Strakt
  5. * Copyright (C) Jean-Paul Calderone
  6. * See LICENSE for details.
  7. *
  8. * Utility functions.
  9. * See the file RATIONALE for a short explanation of why this module was written.
  10. *
  11. * Reviewed 2001-07-23
  12. */
  13. #include <Python.h>
  14. #include "util.h"
  15. /*
  16. * Flush OpenSSL's error queue and return a list of errors (a (library,
  17. * function, reason) string tuple)
  18. *
  19. * Arguments: None
  20. * Returns: A list of errors (new reference)
  21. */
  22. PyObject *
  23. error_queue_to_list(void) {
  24. PyObject *errlist, *tuple;
  25. long err;
  26. errlist = PyList_New(0);
  27. while ((err = ERR_get_error()) != 0) {
  28. tuple = Py_BuildValue("(sss)", ERR_lib_error_string(err),
  29. ERR_func_error_string(err),
  30. ERR_reason_error_string(err));
  31. PyList_Append(errlist, tuple);
  32. Py_DECREF(tuple);
  33. }
  34. return errlist;
  35. }
  36. void exception_from_error_queue(PyObject *the_Error) {
  37. PyObject *errlist = error_queue_to_list();
  38. PyErr_SetObject(the_Error, errlist);
  39. Py_DECREF(errlist);
  40. }
  41. /*
  42. * Flush OpenSSL's error queue and ignore the result
  43. *
  44. * Arguments: None
  45. * Returns: None
  46. */
  47. void
  48. flush_error_queue(void) {
  49. /*
  50. * Make sure to save the errors to a local. Py_DECREF might expand such
  51. * that it evaluates its argument more than once, which would lead to
  52. * very nasty things if we just invoked it with error_queue_to_list().
  53. */
  54. PyObject *list = error_queue_to_list();
  55. Py_DECREF(list);
  56. }
  57. #if (PY_VERSION_HEX < 0x02600000)
  58. PyObject* PyOpenSSL_LongToHex(PyObject *o) {
  59. PyObject *hex = NULL;
  60. PyObject *format = NULL;
  61. PyObject *format_args = NULL;
  62. if ((format_args = Py_BuildValue("(O)", o)) == NULL) {
  63. goto err;
  64. }
  65. if ((format = PyString_FromString("%x")) == NULL) {
  66. goto err;
  67. }
  68. if ((hex = PyString_Format(format, format_args)) == NULL) {
  69. goto err;
  70. }
  71. return hex;
  72. err:
  73. if (format_args) {
  74. Py_DECREF(format_args);
  75. }
  76. if (format) {
  77. Py_DECREF(format);
  78. }
  79. if (hex) {
  80. Py_DECREF(hex);
  81. }
  82. return NULL;
  83. }
  84. #endif