blob: 592660e786c897e9100c3668e9ea433a9e3813c0 [file] [log] [blame]
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001/*
2 * util.h
3 *
4 * Copyright (C) AB Strakt 2001, All rights reserved
5 *
6 * Export utility functions and macros.
7 * See the file RATIONALE for a short explanation of why this module was written.
8 *
9 * Reviewed 2001-07-23
10 *
11 * @(#) $Id: util.h,v 1.8 2002/08/16 10:08:09 martin Exp $
12 */
13#ifndef PyOpenSSL_UTIL_H_
14#define PyOpenSSL_UTIL_H_
15
16#include <Python.h>
17#include <openssl/err.h>
18
19/*
20 * pymemcompat written by Michael Hudson and lets you program to the
21 * Python 2.3 memory API while keeping backwards compatability.
22 */
23#include "pymemcompat.h"
24
25extern PyObject *error_queue_to_list(void);
26extern void flush_error_queue(void);
27
28/*
29 * These are needed because there is no "official" way to specify
30 * WHERE to save the thread state.
31 */
32#ifdef WITH_THREAD
33# define MY_BEGIN_ALLOW_THREADS(st) \
34 { st = PyEval_SaveThread(); }
35# define MY_END_ALLOW_THREADS(st) \
36 { PyEval_RestoreThread(st); st = NULL; }
37#else
38# define MY_BEGIN_ALLOW_THREADS(st)
39# define MY_END_ALLOW_THREADS(st) { st = NULL; }
40#endif
41
42#if !defined(PY_MAJOR_VERSION) || PY_VERSION_HEX < 0x02000000
43static int
44PyModule_AddObject(PyObject *m, char *name, PyObject *o)
45{
46 PyObject *dict;
47 if (!PyModule_Check(m) || o == NULL)
48 return -1;
49 dict = PyModule_GetDict(m);
50 if (dict == NULL)
51 return -1;
52 if (PyDict_SetItemString(dict, name, o))
53 return -1;
54 Py_DECREF(o);
55 return 0;
56}
57
58static int
59PyModule_AddIntConstant(PyObject *m, char *name, long value)
60{
61 return PyModule_AddObject(m, name, PyInt_FromLong(value));
62}
63
64static int PyObject_AsFileDescriptor(PyObject *o)
65{
66 int fd;
67 PyObject *meth;
68
69 if (PyInt_Check(o)) {
70 fd = PyInt_AsLong(o);
71 }
72 else if (PyLong_Check(o)) {
73 fd = PyLong_AsLong(o);
74 }
75 else if ((meth = PyObject_GetAttrString(o, "fileno")) != NULL)
76 {
77 PyObject *fno = PyEval_CallObject(meth, NULL);
78 Py_DECREF(meth);
79 if (fno == NULL)
80 return -1;
81
82 if (PyInt_Check(fno)) {
83 fd = PyInt_AsLong(fno);
84 Py_DECREF(fno);
85 }
86 else if (PyLong_Check(fno)) {
87 fd = PyLong_AsLong(fno);
88 Py_DECREF(fno);
89 }
90 else {
91 PyErr_SetString(PyExc_TypeError, "fileno() returned a non-integer");
92 Py_DECREF(fno);
93 return -1;
94 }
95 }
96 else {
97 PyErr_SetString(PyExc_TypeError, "argument must be an int, or have a fileno() method.");
98 return -1;
99 }
100
101 if (fd < 0) {
102 PyErr_Format(PyExc_ValueError, "file descriptor cannot be a negative integer (%i)", fd);
103 return -1;
104 }
105 return fd;
106}
107#endif
108
109
110
111#endif