s3/torture: local_rbtree: avoid birthday collisions
[samba4-gss.git] / python / modules.c
blob7934f3e35dbd35ca80ea9b49115e6ac317749dff
1 /*
2 Unix SMB/CIFS implementation.
3 Samba utility functions
4 Copyright (C) Jelmer Vernooij <jelmer@samba.org> 2007
6 This program is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 3 of the License, or
9 (at your option) any later version.
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with this program. If not, see <http://www.gnu.org/licenses/>.
20 #include "lib/replace/system/python.h"
21 #include "py3compat.h"
22 #include "includes.h"
23 #include "python/modules.h"
24 #include "dynconfig/dynconfig.h"
26 static bool PySys_PathPrepend(PyObject *list, const char *path)
28 bool ok;
29 PyObject *py_path = PyUnicode_FromString(path);
30 if (py_path == NULL) {
31 return false;
33 ok = PyList_Insert(list, 0, py_path) == 0;
34 Py_XDECREF(py_path);
35 return ok;
38 bool py_update_path(void)
40 PyObject *mod_sys = NULL;
41 PyObject *py_path = NULL;
43 mod_sys = PyImport_ImportModule("sys");
44 if (mod_sys == NULL) {
45 return false;
48 py_path = PyObject_GetAttrString(mod_sys, "path");
49 if (py_path == NULL) {
50 goto error;
53 if (!PyList_Check(py_path)) {
54 goto error;
57 if (!PySys_PathPrepend(py_path, dyn_PYTHONDIR)) {
58 goto error;
61 if (strcmp(dyn_PYTHONARCHDIR, dyn_PYTHONDIR) != 0) {
62 if (!PySys_PathPrepend(py_path, dyn_PYTHONARCHDIR)) {
63 goto error;
66 Py_XDECREF(py_path);
67 Py_XDECREF(mod_sys);
68 return true;
69 error:
70 Py_XDECREF(py_path);
71 Py_XDECREF(mod_sys);
72 return false;
75 char **PyList_AsStringList(TALLOC_CTX *mem_ctx, PyObject *list,
76 const char *paramname)
78 char **ret;
79 Py_ssize_t i;
80 if (!PyList_Check(list)) {
81 PyErr_Format(PyExc_TypeError, "%s is not a list", paramname);
82 return NULL;
84 ret = talloc_array(NULL, char *, PyList_Size(list)+1);
85 if (ret == NULL) {
86 PyErr_NoMemory();
87 return NULL;
90 for (i = 0; i < PyList_Size(list); i++) {
91 const char *value;
92 Py_ssize_t size;
93 PyObject *item = PyList_GetItem(list, i);
94 if (!PyUnicode_Check(item)) {
95 PyErr_Format(PyExc_TypeError, "%s should be strings", paramname);
96 talloc_free(ret);
97 return NULL;
99 value = PyUnicode_AsUTF8AndSize(item, &size);
100 if (value == NULL) {
101 talloc_free(ret);
102 return NULL;
104 ret[i] = talloc_strndup(ret, value, size);
105 if (ret[i] == NULL) {
106 PyErr_NoMemory();
107 talloc_free(ret);
108 return NULL;
111 ret[i] = NULL;
112 return ret;