Use python.h from libreplace
[samba.git] / source4 / librpc / rpc / pyrpc_util.c
blob16d6905da7c61c5560273ed052b2b20b8c2887d6
1 /*
2 Unix SMB/CIFS implementation.
4 Python interface to DCE/RPC library - utility functions.
6 Copyright (C) 2010 Jelmer Vernooij <jelmer@samba.org>
7 Copyright (C) 2010 Andrew Tridgell <tridge@samba.org>
9 This program is free software; you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation; either version 3 of the License, or
12 (at your option) any later version.
14 This program is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 GNU General Public License for more details.
19 You should have received a copy of the GNU General Public License
20 along with this program. If not, see <http://www.gnu.org/licenses/>.
23 #include "lib/replace/system/python.h"
24 #include "python/py3compat.h"
25 #include "includes.h"
26 #include "python/modules.h"
27 #include "librpc/rpc/pyrpc_util.h"
28 #include "librpc/rpc/dcerpc.h"
29 #include "librpc/rpc/pyrpc.h"
30 #include "param/pyparam.h"
31 #include "auth/credentials/pycredentials.h"
32 #include "lib/events/events.h"
33 #include "lib/messaging/messaging.h"
34 #include "lib/messaging/irpc.h"
36 bool py_check_dcerpc_type(PyObject *obj, const char *module, const char *type_name)
38 PyObject *mod;
39 PyTypeObject *type;
40 bool ret;
42 mod = PyImport_ImportModule(module);
44 if (mod == NULL) {
45 PyErr_Format(PyExc_RuntimeError, "Unable to import %s to check type %s",
46 module, type_name);
47 return false;
50 type = (PyTypeObject *)PyObject_GetAttrString(mod, type_name);
51 Py_DECREF(mod);
52 if (type == NULL) {
53 PyErr_Format(PyExc_RuntimeError, "Unable to find type %s in module %s",
54 module, type_name);
55 return false;
58 ret = PyObject_TypeCheck(obj, type);
59 Py_DECREF(type);
61 if (!ret)
62 PyErr_Format(PyExc_TypeError, "Expected type %s.%s, got %s",
63 module, type_name, Py_TYPE(obj)->tp_name);
65 return ret;
69 connect to a IRPC pipe from python
71 static NTSTATUS pyrpc_irpc_connect(TALLOC_CTX *mem_ctx, const char *irpc_server,
72 const struct ndr_interface_table *table,
73 struct tevent_context *event_ctx,
74 struct loadparm_context *lp_ctx,
75 struct dcerpc_binding_handle **binding_handle)
77 struct imessaging_context *msg;
79 msg = imessaging_client_init(mem_ctx, lp_ctx, event_ctx);
80 NT_STATUS_HAVE_NO_MEMORY(msg);
82 *binding_handle = irpc_binding_handle_by_name(mem_ctx, msg, irpc_server, table);
83 if (*binding_handle == NULL) {
84 talloc_free(msg);
85 return NT_STATUS_INVALID_PIPE_STATE;
89 * Note: this allows nested event loops to happen,
90 * but as there's no top level event loop it's not that critical.
92 dcerpc_binding_handle_set_sync_ev(*binding_handle, event_ctx);
94 return NT_STATUS_OK;
97 PyObject *py_dcerpc_interface_init_helper(PyTypeObject *type, PyObject *args, PyObject *kwargs,
98 const struct ndr_interface_table *table)
100 dcerpc_InterfaceObject *ret;
101 const char *binding_string;
102 PyObject *py_lp_ctx = Py_None, *py_credentials = Py_None, *py_basis = Py_None;
103 NTSTATUS status;
104 unsigned int timeout = (unsigned int)-1;
105 const char *kwnames[] = {
106 "binding", "lp_ctx", "credentials", "timeout", "basis_connection", NULL
109 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s|OOIO:samr", discard_const_p(char *, kwnames), &binding_string, &py_lp_ctx, &py_credentials, &timeout, &py_basis)) {
110 return NULL;
113 status = dcerpc_init();
114 if (!NT_STATUS_IS_OK(status)) {
115 PyErr_SetNTSTATUS(status);
116 return NULL;
119 ret = PyObject_New(dcerpc_InterfaceObject, type);
120 if (ret == NULL) {
121 PyErr_NoMemory();
122 return NULL;
125 ret->pipe = NULL;
126 ret->binding_handle = NULL;
127 ret->ev = NULL;
128 ret->mem_ctx = talloc_new(NULL);
129 if (ret->mem_ctx == NULL) {
130 PyErr_NoMemory();
131 return NULL;
134 if (strncmp(binding_string, "irpc:", 5) == 0) {
135 struct loadparm_context *lp_ctx;
137 ret->ev = s4_event_context_init(ret->mem_ctx);
138 if (ret->ev == NULL) {
139 PyErr_SetString(PyExc_TypeError,
140 "Unable to initialise event context");
141 Py_DECREF(ret);
142 return NULL;
145 lp_ctx = lpcfg_from_py_object(ret->ev, py_lp_ctx);
146 if (lp_ctx == NULL) {
147 PyErr_SetString(PyExc_TypeError, "Expected loadparm context");
148 Py_DECREF(ret);
149 return NULL;
152 status = pyrpc_irpc_connect(ret->mem_ctx, binding_string+5, table,
153 ret->ev, lp_ctx, &ret->binding_handle);
154 if (!NT_STATUS_IS_OK(status)) {
155 PyErr_SetNTSTATUS(status);
156 Py_DECREF(ret);
157 return NULL;
159 } else if (py_basis != Py_None) {
160 struct dcerpc_pipe *base_pipe;
161 PyObject *py_base;
162 PyTypeObject *ClientConnection_Type;
164 py_base = PyImport_ImportModule("samba.dcerpc.base");
165 if (py_base == NULL) {
166 Py_DECREF(ret);
167 return NULL;
170 ClientConnection_Type = (PyTypeObject *)PyObject_GetAttrString(py_base, "ClientConnection");
171 if (ClientConnection_Type == NULL) {
172 PyErr_SetNone(PyExc_TypeError);
173 Py_DECREF(ret);
174 Py_DECREF(py_base);
175 return NULL;
178 if (!PyObject_TypeCheck(py_basis, ClientConnection_Type)) {
179 PyErr_SetString(PyExc_TypeError, "basis_connection must be a DCE/RPC connection");
180 Py_DECREF(ret);
181 Py_DECREF(py_base);
182 Py_DECREF(ClientConnection_Type);
183 return NULL;
186 base_pipe = talloc_reference(ret->mem_ctx,
187 ((dcerpc_InterfaceObject *)py_basis)->pipe);
188 if (base_pipe == NULL) {
189 PyErr_NoMemory();
190 Py_DECREF(ret);
191 Py_DECREF(py_base);
192 Py_DECREF(ClientConnection_Type);
193 return NULL;
196 ret->ev = talloc_reference(
197 ret->mem_ctx,
198 ((dcerpc_InterfaceObject *)py_basis)->ev);
199 if (ret->ev == NULL) {
200 PyErr_NoMemory();
201 Py_DECREF(ret);
202 Py_DECREF(py_base);
203 Py_DECREF(ClientConnection_Type);
204 return NULL;
207 status = dcerpc_secondary_context(base_pipe, &ret->pipe, table);
208 if (!NT_STATUS_IS_OK(status)) {
209 PyErr_SetNTSTATUS(status);
210 Py_DECREF(ret);
211 Py_DECREF(py_base);
212 Py_DECREF(ClientConnection_Type);
213 return NULL;
216 ret->pipe = talloc_steal(ret->mem_ctx, ret->pipe);
217 Py_XDECREF(ClientConnection_Type);
218 Py_XDECREF(py_base);
219 } else {
220 struct loadparm_context *lp_ctx;
221 struct cli_credentials *credentials;
223 ret->ev = s4_event_context_init(ret->mem_ctx);
224 if (ret->ev == NULL) {
225 PyErr_SetString(PyExc_TypeError, "Expected loadparm context");
226 Py_DECREF(ret);
227 return NULL;
230 lp_ctx = lpcfg_from_py_object(ret->ev, py_lp_ctx);
231 if (lp_ctx == NULL) {
232 PyErr_SetString(PyExc_TypeError, "Expected loadparm context");
233 Py_DECREF(ret);
234 return NULL;
237 credentials = cli_credentials_from_py_object(py_credentials);
238 if (credentials == NULL) {
239 PyErr_SetString(PyExc_TypeError, "Expected credentials");
240 Py_DECREF(ret);
241 return NULL;
243 status = dcerpc_pipe_connect(ret->mem_ctx, &ret->pipe, binding_string,
244 table, credentials, ret->ev, lp_ctx);
245 if (!NT_STATUS_IS_OK(status)) {
246 PyErr_SetNTSTATUS(status);
247 Py_DECREF(ret);
248 return NULL;
252 if (ret->pipe) {
253 ret->pipe->conn->flags |= DCERPC_NDR_REF_ALLOC;
254 ret->binding_handle = ret->pipe->binding_handle;
257 /* reset timeout for the handle */
258 if ((timeout != ((unsigned int)-1)) && (ret->binding_handle != NULL)) {
259 dcerpc_binding_handle_set_timeout(ret->binding_handle, timeout);
262 return (PyObject *)ret;
265 static PyObject *py_dcerpc_run_function(dcerpc_InterfaceObject *iface,
266 const struct PyNdrRpcMethodDef *md,
267 PyObject *args, PyObject *kwargs)
269 TALLOC_CTX *mem_ctx;
270 NTSTATUS status;
271 void *r;
272 PyObject *result = Py_None;
274 if (md->pack_in_data == NULL || md->unpack_out_data == NULL) {
275 PyErr_SetString(PyExc_NotImplementedError, "No marshalling code available yet");
276 return NULL;
279 mem_ctx = talloc_new(NULL);
280 if (mem_ctx == NULL) {
281 PyErr_NoMemory();
282 return NULL;
285 r = talloc_zero_size(mem_ctx, md->table->calls[md->opnum].struct_size);
286 if (r == NULL) {
287 PyErr_NoMemory();
288 return NULL;
291 if (!md->pack_in_data(args, kwargs, r)) {
292 talloc_free(mem_ctx);
293 return NULL;
296 status = md->call(iface->binding_handle, mem_ctx, r);
297 if (!NT_STATUS_IS_OK(status)) {
298 PyErr_SetDCERPCStatus(iface->pipe, status);
299 talloc_free(mem_ctx);
300 return NULL;
303 result = md->unpack_out_data(r);
305 talloc_free(mem_ctx);
306 return result;
309 static PyObject *py_dcerpc_call_wrapper(PyObject *self, PyObject *args, void *wrapped, PyObject *kwargs)
311 dcerpc_InterfaceObject *iface = (dcerpc_InterfaceObject *)self;
312 const struct PyNdrRpcMethodDef *md = (const struct PyNdrRpcMethodDef *)wrapped;
314 return py_dcerpc_run_function(iface, md, args, kwargs);
317 bool PyInterface_AddNdrRpcMethods(PyTypeObject *ifacetype, const struct PyNdrRpcMethodDef *mds)
319 int i;
320 for (i = 0; mds[i].name; i++) {
321 PyObject *ret;
322 struct wrapperbase *wb = (struct wrapperbase *)calloc(sizeof(struct wrapperbase), 1);
324 if (wb == NULL) {
325 return false;
327 wb->name = discard_const_p(char, mds[i].name);
328 wb->flags = PyWrapperFlag_KEYWORDS;
329 wb->wrapper = PY_DISCARD_FUNC_SIG(wrapperfunc,
330 py_dcerpc_call_wrapper);
331 wb->doc = discard_const_p(char, mds[i].doc);
333 ret = PyDescr_NewWrapper(ifacetype, wb, discard_const_p(void, &mds[i]));
335 PyDict_SetItemString(ifacetype->tp_dict, mds[i].name,
336 (PyObject *)ret);
337 Py_CLEAR(ret);
340 return true;
343 PyObject *py_dcerpc_syntax_init_helper(PyTypeObject *type, PyObject *args, PyObject *kwargs,
344 const struct ndr_syntax_id *syntax)
346 PyObject *ret;
347 struct ndr_syntax_id *obj;
348 const char *kwnames[] = { NULL };
350 if (!PyArg_ParseTupleAndKeywords(args, kwargs, ":abstract_syntax", discard_const_p(char *, kwnames))) {
351 return NULL;
354 ret = pytalloc_new(struct ndr_syntax_id, type);
355 if (ret == NULL) {
356 return NULL;
359 obj = pytalloc_get_type(ret, struct ndr_syntax_id);
360 *obj = *syntax;
362 return ret;
365 void PyErr_SetDCERPCStatus(struct dcerpc_pipe *p, NTSTATUS status)
367 if (p && NT_STATUS_EQUAL(status, NT_STATUS_NET_WRITE_FAULT)) {
368 status = dcerpc_fault_to_nt_status(p->last_fault_code);
370 PyErr_SetNTSTATUS(status);
375 take a NDR structure that has a type in a python module and return
376 it as a python object
378 r is the NDR structure pointer (a C structure)
380 r_ctx is the context that is a parent of r. It will be referenced by
381 the resulting python object
383 This MUST only be used by objects that are based on pytalloc_Object
384 otherwise the pytalloc_reference_ex() will fail.
386 PyObject *py_return_ndr_struct(const char *module_name, const char *type_name,
387 TALLOC_CTX *r_ctx, void *r)
389 PyTypeObject *py_type;
390 PyObject *module;
391 PyObject *result = NULL;
393 if (r == NULL) {
394 Py_RETURN_NONE;
397 module = PyImport_ImportModule(module_name);
398 if (module == NULL) {
399 return NULL;
402 py_type = (PyTypeObject *)PyObject_GetAttrString(module, type_name);
403 if (py_type == NULL) {
404 Py_DECREF(module);
405 return NULL;
408 result = pytalloc_reference_ex(py_type, r_ctx, r);
409 Py_CLEAR(module);
410 Py_CLEAR(py_type);
411 return result;
414 PyObject *PyString_FromStringOrNULL(const char *str)
416 if (str == NULL) {
417 Py_RETURN_NONE;
419 return PyUnicode_FromString(str);
422 PyObject *PyBytes_FromUtf16StringOrNULL(const uint16_t *str)
424 size_t len;
426 if (str == NULL) {
427 Py_RETURN_NONE;
430 len = utf16_len(str);
431 return PyBytes_FromStringAndSize((const char *)str, len);
434 uint16_t *PyUtf16String_FromBytes(TALLOC_CTX *mem_ctx, PyObject *value)
436 char *bytes = NULL;
437 Py_ssize_t len = 0;
438 uint16_t *utf16_string = NULL;
439 int ret;
441 ret = PyBytes_AsStringAndSize(value, &bytes, &len);
442 if (ret) {
443 return NULL;
446 if (len < 0) {
447 PyErr_SetString(PyExc_ValueError, "bytes length is negative");
448 return NULL;
451 /* Ensure that the bytes object contains no embedded null terminator. */
452 if ((size_t)len != utf16_len_n(bytes, len)) {
453 PyErr_SetString(PyExc_ValueError,
454 "value contains an embedded null terminator");
455 return NULL;
458 utf16_string = talloc_utf16_strlendup(mem_ctx, bytes, len);
459 if (utf16_string == NULL) {
460 PyErr_NoMemory();
461 return NULL;
464 return utf16_string;
467 PyObject *pyrpc_import_union(PyTypeObject *type, TALLOC_CTX *mem_ctx, int level,
468 const void *in, const char *typename)
470 PyObject *mem_ctx_obj = NULL;
471 PyObject *in_obj = NULL;
472 PyObject *ret = NULL;
474 mem_ctx_obj = pytalloc_GenericObject_reference(mem_ctx);
475 if (mem_ctx_obj == NULL) {
476 return NULL;
479 in_obj = pytalloc_GenericObject_reference_ex(mem_ctx, discard_const(in));
480 if (in_obj == NULL) {
481 Py_XDECREF(mem_ctx_obj);
482 return NULL;
485 ret = PyObject_CallMethod((PyObject *)type,
486 discard_const_p(char, "__import__"),
487 discard_const_p(char, "OiO"),
488 mem_ctx_obj, level, in_obj);
489 Py_XDECREF(mem_ctx_obj);
490 Py_XDECREF(in_obj);
491 if (ret == NULL) {
492 return NULL;
495 return ret;
498 void *pyrpc_export_union(PyTypeObject *type, TALLOC_CTX *mem_ctx, int level,
499 PyObject *in, const char *typename)
501 PyObject *mem_ctx_obj = NULL;
502 PyObject *ret_obj = NULL;
503 void *ret = NULL;
505 mem_ctx_obj = pytalloc_GenericObject_reference(mem_ctx);
506 if (mem_ctx_obj == NULL) {
507 return NULL;
510 ret_obj = PyObject_CallMethod((PyObject *)type,
511 discard_const_p(char, "__export__"),
512 discard_const_p(char, "OiO"),
513 mem_ctx_obj, level, in);
514 Py_XDECREF(mem_ctx_obj);
515 if (ret_obj == NULL) {
516 return NULL;
519 ret = _pytalloc_get_type(ret_obj, typename);
520 Py_XDECREF(ret_obj);
521 return ret;
524 PyObject *py_dcerpc_ndr_pointer_deref(PyTypeObject *type, PyObject *obj)
526 if (!PyObject_TypeCheck(obj, type)) {
527 PyErr_Format(PyExc_TypeError,
528 "Expected type '%s' but got type '%s'",
529 (type)->tp_name, Py_TYPE(obj)->tp_name);
530 return NULL;
533 return PyObject_GetAttrString(obj, discard_const_p(char, "value"));
536 PyObject *py_dcerpc_ndr_pointer_wrap(PyTypeObject *type, PyObject *obj)
538 PyObject *args = NULL;
539 PyObject *ret_obj = NULL;
541 args = PyTuple_New(1);
542 if (args == NULL) {
543 return NULL;
545 Py_XINCREF(obj);
546 PyTuple_SetItem(args, 0, obj);
548 ret_obj = PyObject_Call((PyObject *)type, args, NULL);
549 Py_XDECREF(args);
550 return ret_obj;