4 * Copyright (C) AB Strakt
5 * See LICENSE for details.
7 * Export utility functions and macros.
8 * See the file RATIONALE for a short explanation of why this module was written.
13 #ifndef PyOpenSSL_UTIL_H_
14 #define PyOpenSSL_UTIL_H_
17 #include <openssl/err.h>
20 * pymemcompat written by Michael Hudson and lets you program to the
21 * Python 2.3 memory API while keeping backwards compatibility.
23 #include "pymemcompat.h"
26 * py3k defines macros that help with Python 2.x/3.x compatibility.
31 extern PyObject *error_queue_to_list(void);
32 extern void exception_from_error_queue(PyObject *the_Error);
33 extern void flush_error_queue(void);
36 * These are needed because there is no "official" way to specify
37 * WHERE to save the thread state.
42 * Get the current Python threadstate and put it somewhere any code running
43 * in this thread can get it, if it needs to restore the threadstate to run
46 # define MY_BEGIN_ALLOW_THREADS(ignored) \
47 PyThread_delete_key_value(_pyOpenSSL_tstate_key); \
48 PyThread_set_key_value(_pyOpenSSL_tstate_key, PyEval_SaveThread());
51 * Get the previous Python threadstate and restore it.
53 # define MY_END_ALLOW_THREADS(ignored) \
54 PyEval_RestoreThread(PyThread_get_key_value(_pyOpenSSL_tstate_key));
57 # define MY_BEGIN_ALLOW_THREADS(st)
58 # define MY_END_ALLOW_THREADS(st) { st = NULL; }
61 #if !defined(PY_MAJOR_VERSION) || PY_VERSION_HEX < 0x02000000
63 PyModule_AddObject(PyObject *m, char *name, PyObject *o)
66 if (!PyModule_Check(m) || o == NULL)
68 dict = PyModule_GetDict(m);
71 if (PyDict_SetItemString(dict, name, o))
78 PyModule_AddIntConstant(PyObject *m, char *name, long value)
80 return PyModule_AddObject(m, name, PyInt_FromLong(value));
83 static int PyObject_AsFileDescriptor(PyObject *o)
91 else if (PyLong_Check(o)) {
92 fd = PyLong_AsLong(o);
94 else if ((meth = PyObject_GetAttrString(o, "fileno")) != NULL)
96 PyObject *fno = PyEval_CallObject(meth, NULL);
101 if (PyInt_Check(fno)) {
102 fd = PyInt_AsLong(fno);
105 else if (PyLong_Check(fno)) {
106 fd = PyLong_AsLong(fno);
110 PyErr_SetString(PyExc_TypeError, "fileno() returned a non-integer");
116 PyErr_SetString(PyExc_TypeError, "argument must be an int, or have a fileno() method.");
121 PyErr_Format(PyExc_ValueError, "file descriptor cannot be a negative integer (%i)", fd);
128 #if !defined(PY_SSIZE_T_MIN)
129 typedef int Py_ssize_t;
130 #define PY_SSIZE_T_MAX INT_MAX
131 #define PY_SSIZE_T_MIN INT_MIN
134 #if (PY_VERSION_HEX < 0x02600000)
135 extern PyObject* PyOpenSSL_LongToHex(PyObject *o);
137 #define PyOpenSSL_LongToHex(o) PyNumber_ToBase(o, 16)