util.c 2.1 KB

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