s4/pyrpc_util: appropriately decrement refcounts on failure
[nivanova/samba-autobuild/.git] / source4 / librpc / rpc / pyrpc_util.c
1 /*
2    Unix SMB/CIFS implementation.
3
4    Python interface to DCE/RPC library - utility functions.
5
6    Copyright (C) 2010 Jelmer Vernooij <jelmer@samba.org>
7    Copyright (C) 2010 Andrew Tridgell <tridge@samba.org>
8
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.
13
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.
18
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/>.
21 */
22
23 #include <Python.h>
24 #include "python/py3compat.h"
25 #include "includes.h"
26 #include "librpc/rpc/pyrpc_util.h"
27 #include "librpc/rpc/dcerpc.h"
28 #include "librpc/rpc/pyrpc.h"
29 #include "param/pyparam.h"
30 #include "auth/credentials/pycredentials.h"
31 #include "lib/events/events.h"
32 #include "lib/messaging/messaging.h"
33 #include "lib/messaging/irpc.h"
34
35 bool py_check_dcerpc_type(PyObject *obj, const char *module, const char *type_name)
36 {
37         PyObject *mod;
38         PyTypeObject *type;
39         bool ret;
40
41         mod = PyImport_ImportModule(module);
42
43         if (mod == NULL) {
44                 PyErr_Format(PyExc_RuntimeError, "Unable to import %s to check type %s",
45                         module, type_name);
46                 return false;
47         }
48
49         type = (PyTypeObject *)PyObject_GetAttrString(mod, type_name);
50         Py_DECREF(mod);
51         if (type == NULL) {
52                 PyErr_Format(PyExc_RuntimeError, "Unable to find type %s in module %s",
53                         module, type_name);
54                 return false;
55         }
56
57         ret = PyObject_TypeCheck(obj, type);
58         Py_DECREF(type);
59
60         if (!ret)
61                 PyErr_Format(PyExc_TypeError, "Expected type %s.%s, got %s",
62                         module, type_name, Py_TYPE(obj)->tp_name);
63
64         return ret;
65 }
66
67 /*
68   connect to a IRPC pipe from python
69  */
70 static NTSTATUS pyrpc_irpc_connect(TALLOC_CTX *mem_ctx, const char *irpc_server,
71                                    const struct ndr_interface_table *table,
72                                    struct tevent_context *event_ctx,
73                                    struct loadparm_context *lp_ctx,
74                                    struct dcerpc_binding_handle **binding_handle)
75 {
76         struct imessaging_context *msg;
77
78         msg = imessaging_client_init(mem_ctx, lp_ctx, event_ctx);
79         NT_STATUS_HAVE_NO_MEMORY(msg);
80
81         *binding_handle = irpc_binding_handle_by_name(mem_ctx, msg, irpc_server, table);
82         if (*binding_handle == NULL) {
83                 talloc_free(msg);
84                 return NT_STATUS_INVALID_PIPE_STATE;
85         }
86
87         /*
88          * Note: this allows nested event loops to happen,
89          * but as there's no top level event loop it's not that critical.
90          */
91         dcerpc_binding_handle_set_sync_ev(*binding_handle, event_ctx);
92
93         return NT_STATUS_OK;
94 }
95
96 PyObject *py_dcerpc_interface_init_helper(PyTypeObject *type, PyObject *args, PyObject *kwargs,
97                                           const struct ndr_interface_table *table)
98 {
99         dcerpc_InterfaceObject *ret;
100         const char *binding_string;
101         PyObject *py_lp_ctx = Py_None, *py_credentials = Py_None, *py_basis = Py_None;
102         NTSTATUS status;
103         unsigned int timeout = (unsigned int)-1;
104         const char *kwnames[] = {
105                 "binding", "lp_ctx", "credentials", "timeout", "basis_connection", NULL
106         };
107
108         if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s|OOIO:samr", discard_const_p(char *, kwnames), &binding_string, &py_lp_ctx, &py_credentials, &timeout, &py_basis)) {
109                 return NULL;
110         }
111
112         status = dcerpc_init();
113         if (!NT_STATUS_IS_OK(status)) {
114                 PyErr_SetNTSTATUS(status);
115                 return NULL;
116         }
117
118         ret = PyObject_New(dcerpc_InterfaceObject, type);
119         ret->pipe = NULL;
120         ret->binding_handle = NULL;
121         ret->mem_ctx = talloc_new(NULL);
122         if (ret->mem_ctx == NULL) {
123                 PyErr_NoMemory();
124                 return NULL;
125         }
126
127         if (strncmp(binding_string, "irpc:", 5) == 0) {
128                 struct tevent_context *event_ctx;
129                 struct loadparm_context *lp_ctx;
130
131                 event_ctx = s4_event_context_init(ret->mem_ctx);
132                 if (event_ctx == NULL) {
133                         PyErr_SetString(PyExc_TypeError, "Expected loadparm context");
134                         TALLOC_FREE(ret->mem_ctx);
135                         Py_DECREF(ret);
136                         return NULL;
137                 }
138
139                 lp_ctx = lpcfg_from_py_object(event_ctx, py_lp_ctx);
140                 if (lp_ctx == NULL) {
141                         PyErr_SetString(PyExc_TypeError, "Expected loadparm context");
142                         TALLOC_FREE(ret->mem_ctx);
143                         Py_DECREF(ret);
144                         return NULL;
145                 }
146
147                 status = pyrpc_irpc_connect(ret->mem_ctx, binding_string+5, table,
148                                             event_ctx, lp_ctx, &ret->binding_handle);
149                 if (!NT_STATUS_IS_OK(status)) {
150                         PyErr_SetNTSTATUS(status);
151                         TALLOC_FREE(ret->mem_ctx);
152                         Py_DECREF(ret);
153                         return NULL;
154                 }
155         } else if (py_basis != Py_None) {
156                 struct dcerpc_pipe *base_pipe;
157                 PyObject *py_base;
158                 PyTypeObject *ClientConnection_Type;
159
160                 py_base = PyImport_ImportModule("samba.dcerpc.base");
161                 if (py_base == NULL) {
162                         TALLOC_FREE(ret->mem_ctx);
163                         Py_DECREF(ret);
164                         return NULL;
165                 }
166
167                 ClientConnection_Type = (PyTypeObject *)PyObject_GetAttrString(py_base, "ClientConnection");
168                 if (ClientConnection_Type == NULL) {
169                         PyErr_SetNone(PyExc_TypeError);
170                         TALLOC_FREE(ret->mem_ctx);
171                         Py_DECREF(ret);
172                         Py_DECREF(py_base);
173                         return NULL;
174                 }
175
176                 if (!PyObject_TypeCheck(py_basis, ClientConnection_Type)) {
177                         PyErr_SetString(PyExc_TypeError, "basis_connection must be a DCE/RPC connection");
178                         TALLOC_FREE(ret->mem_ctx);
179                         Py_DECREF(ret);
180                         Py_DECREF(py_base);
181                         Py_DECREF(ClientConnection_Type);
182                         return NULL;
183                 }
184
185                 base_pipe = talloc_reference(ret->mem_ctx,
186                                          ((dcerpc_InterfaceObject *)py_basis)->pipe);
187                 if (base_pipe == NULL) {
188                         PyErr_NoMemory();
189                         TALLOC_FREE(ret->mem_ctx);
190                         Py_DECREF(ret);
191                         Py_DECREF(py_base);
192                         Py_DECREF(ClientConnection_Type);
193                         return NULL;
194                 }
195
196                 status = dcerpc_secondary_context(base_pipe, &ret->pipe, table);
197                 if (!NT_STATUS_IS_OK(status)) {
198                         PyErr_SetNTSTATUS(status);
199                         TALLOC_FREE(ret->mem_ctx);
200                         Py_DECREF(ret);
201                         Py_DECREF(py_base);
202                         Py_DECREF(ClientConnection_Type);
203                         return NULL;
204                 }
205
206                 ret->pipe = talloc_steal(ret->mem_ctx, ret->pipe);
207                 Py_XDECREF(ClientConnection_Type);
208                 Py_XDECREF(py_base);
209         } else {
210                 struct tevent_context *event_ctx;
211                 struct loadparm_context *lp_ctx;
212                 struct cli_credentials *credentials;
213
214                 event_ctx = s4_event_context_init(ret->mem_ctx);
215                 if (event_ctx == NULL) {
216                         PyErr_SetString(PyExc_TypeError, "Expected loadparm context");
217                         TALLOC_FREE(ret->mem_ctx);
218                         Py_DECREF(ret);
219                         return NULL;
220                 }
221
222                 lp_ctx = lpcfg_from_py_object(event_ctx, py_lp_ctx);
223                 if (lp_ctx == NULL) {
224                         PyErr_SetString(PyExc_TypeError, "Expected loadparm context");
225                         TALLOC_FREE(ret->mem_ctx);
226                         Py_DECREF(ret);
227                         return NULL;
228                 }
229
230                 credentials = cli_credentials_from_py_object(py_credentials);
231                 if (credentials == NULL) {
232                         PyErr_SetString(PyExc_TypeError, "Expected credentials");
233                         TALLOC_FREE(ret->mem_ctx);
234                         Py_DECREF(ret);
235                         return NULL;
236                 }
237                 status = dcerpc_pipe_connect(ret->mem_ctx, &ret->pipe, binding_string,
238                              table, credentials, event_ctx, lp_ctx);
239                 if (!NT_STATUS_IS_OK(status)) {
240                         PyErr_SetNTSTATUS(status);
241                         TALLOC_FREE(ret->mem_ctx);
242                         Py_DECREF(ret);
243                         return NULL;
244                 }
245
246                 /*
247                  * the event context is cached under the connection,
248                  * so let it be a child of it.
249                  */
250                 talloc_steal(ret->pipe->conn, event_ctx);
251         }
252
253         if (ret->pipe) {
254                 ret->pipe->conn->flags |= DCERPC_NDR_REF_ALLOC;
255                 ret->binding_handle = ret->pipe->binding_handle;
256         }
257
258         /* reset timeout for the handle */
259         if ((timeout != ((unsigned int)-1)) && (ret->binding_handle != NULL)) {
260                 dcerpc_binding_handle_set_timeout(ret->binding_handle, timeout);
261         }
262
263         return (PyObject *)ret;
264 }
265
266 static PyObject *py_dcerpc_run_function(dcerpc_InterfaceObject *iface,
267                                         const struct PyNdrRpcMethodDef *md,
268                                         PyObject *args, PyObject *kwargs)
269 {
270         TALLOC_CTX *mem_ctx;
271         NTSTATUS status;
272         void *r;
273         PyObject *result = Py_None;
274
275         if (md->pack_in_data == NULL || md->unpack_out_data == NULL) {
276                 PyErr_SetString(PyExc_NotImplementedError, "No marshalling code available yet");
277                 return NULL;
278         }
279
280         mem_ctx = talloc_new(NULL);
281         if (mem_ctx == NULL) {
282                 PyErr_NoMemory();
283                 return NULL;
284         }
285
286         r = talloc_zero_size(mem_ctx, md->table->calls[md->opnum].struct_size);
287         if (r == NULL) {
288                 PyErr_NoMemory();
289                 return NULL;
290         }
291
292         if (!md->pack_in_data(args, kwargs, r)) {
293                 talloc_free(mem_ctx);
294                 return NULL;
295         }
296
297         status = md->call(iface->binding_handle, mem_ctx, r);
298         if (!NT_STATUS_IS_OK(status)) {
299                 PyErr_SetDCERPCStatus(iface->pipe, status);
300                 talloc_free(mem_ctx);
301                 return NULL;
302         }
303
304         result = md->unpack_out_data(r);
305
306         talloc_free(mem_ctx);
307         return result;
308 }
309
310 static PyObject *py_dcerpc_call_wrapper(PyObject *self, PyObject *args, void *wrapped, PyObject *kwargs)
311 {       
312         dcerpc_InterfaceObject *iface = (dcerpc_InterfaceObject *)self;
313         const struct PyNdrRpcMethodDef *md = (const struct PyNdrRpcMethodDef *)wrapped;
314
315         return py_dcerpc_run_function(iface, md, args, kwargs);
316 }
317
318 bool PyInterface_AddNdrRpcMethods(PyTypeObject *ifacetype, const struct PyNdrRpcMethodDef *mds)
319 {
320         int i;
321         for (i = 0; mds[i].name; i++) {
322                 PyObject *ret;
323                 struct wrapperbase *wb = (struct wrapperbase *)calloc(sizeof(struct wrapperbase), 1);
324
325                 if (wb == NULL) {
326                         return false;
327                 }
328                 wb->name = discard_const_p(char, mds[i].name);
329                 wb->flags = PyWrapperFlag_KEYWORDS;
330                 wb->wrapper = (wrapperfunc)py_dcerpc_call_wrapper;
331                 wb->doc = discard_const_p(char, mds[i].doc);
332
333                 ret = PyDescr_NewWrapper(ifacetype, wb, discard_const_p(void, &mds[i]));
334
335                 PyDict_SetItemString(ifacetype->tp_dict, mds[i].name, 
336                                      (PyObject *)ret);
337         }
338
339         return true;
340 }
341
342 PyObject *py_dcerpc_syntax_init_helper(PyTypeObject *type, PyObject *args, PyObject *kwargs,
343                                        const struct ndr_syntax_id *syntax)
344 {
345         PyObject *ret;
346         struct ndr_syntax_id *obj;
347         const char *kwnames[] = { NULL };
348
349         if (!PyArg_ParseTupleAndKeywords(args, kwargs, ":abstract_syntax", discard_const_p(char *, kwnames))) {
350                 return NULL;
351         }
352
353         ret = pytalloc_new(struct ndr_syntax_id, type);
354         if (ret == NULL) {
355                 return NULL;
356         }
357
358         obj = pytalloc_get_type(ret, struct ndr_syntax_id);
359         *obj = *syntax;
360
361         return ret;
362 }
363
364 void PyErr_SetDCERPCStatus(struct dcerpc_pipe *p, NTSTATUS status)
365 {
366         if (p && NT_STATUS_EQUAL(status, NT_STATUS_NET_WRITE_FAULT)) {
367                 status = dcerpc_fault_to_nt_status(p->last_fault_code);
368         }
369         PyErr_SetNTSTATUS(status);
370 }
371
372
373 /*
374   take a NDR structure that has a type in a python module and return
375   it as a python object
376
377   r is the NDR structure pointer (a C structure)
378
379   r_ctx is the context that is a parent of r. It will be referenced by
380   the resulting python object
381
382   This MUST only be used by objects that are based on pytalloc_Object
383   otherwise the pytalloc_reference_ex() will fail.
384  */
385 PyObject *py_return_ndr_struct(const char *module_name, const char *type_name,
386                                TALLOC_CTX *r_ctx, void *r)
387 {
388         PyTypeObject *py_type;
389         PyObject *module;
390
391         if (r == NULL) {
392                 Py_RETURN_NONE;
393         }
394
395         module = PyImport_ImportModule(module_name);
396         if (module == NULL) {
397                 return NULL;
398         }
399
400         py_type = (PyTypeObject *)PyObject_GetAttrString(module, type_name);
401         if (py_type == NULL) {
402                 Py_DECREF(module);
403                 return NULL;
404         }
405
406         return pytalloc_reference_ex(py_type, r_ctx, r);
407 }
408
409 PyObject *PyString_FromStringOrNULL(const char *str)
410 {
411         if (str == NULL) {
412                 Py_RETURN_NONE;
413         }
414         return PyStr_FromString(str);
415 }
416
417 PyObject *pyrpc_import_union(PyTypeObject *type, TALLOC_CTX *mem_ctx, int level,
418                              const void *in, const char *typename)
419 {
420         PyObject *mem_ctx_obj = NULL;
421         PyObject *in_obj = NULL;
422         PyObject *ret = NULL;
423
424         mem_ctx_obj = pytalloc_GenericObject_reference(mem_ctx);
425         if (mem_ctx_obj == NULL) {
426                 return NULL;
427         }
428
429         in_obj = pytalloc_GenericObject_reference_ex(mem_ctx, discard_const(in));
430         if (in_obj == NULL) {
431                 Py_XDECREF(mem_ctx_obj);
432                 return NULL;
433         }
434
435         ret = PyObject_CallMethod((PyObject *)type,
436                                   discard_const_p(char, "__import__"),
437                                   discard_const_p(char, "OiO"),
438                                   mem_ctx_obj, level, in_obj);
439         Py_XDECREF(mem_ctx_obj);
440         Py_XDECREF(in_obj);
441         if (ret == NULL) {
442                 return NULL;
443         }
444
445         return ret;
446 }
447
448 void *pyrpc_export_union(PyTypeObject *type, TALLOC_CTX *mem_ctx, int level,
449                          PyObject *in, const char *typename)
450 {
451         PyObject *mem_ctx_obj = NULL;
452         PyObject *ret_obj = NULL;
453         void *ret = NULL;
454
455         mem_ctx_obj = pytalloc_GenericObject_reference(mem_ctx);
456         if (mem_ctx_obj == NULL) {
457                 return NULL;
458         }
459
460         ret_obj = PyObject_CallMethod((PyObject *)type,
461                                       discard_const_p(char, "__export__"),
462                                       discard_const_p(char, "OiO"),
463                                       mem_ctx_obj, level, in);
464         Py_XDECREF(mem_ctx_obj);
465         if (ret_obj == NULL) {
466                 return NULL;
467         }
468
469         ret = _pytalloc_get_type(ret_obj, typename);
470         Py_XDECREF(ret_obj);
471         return ret;
472 }
473
474 PyObject *py_dcerpc_ndr_pointer_deref(PyTypeObject *type, PyObject *obj)
475 {
476         if (!PyObject_TypeCheck(obj, type)) {
477                 PyErr_Format(PyExc_TypeError,
478                              "Expected type '%s' but got type '%s'",
479                              (type)->tp_name, Py_TYPE(obj)->tp_name);
480                 return NULL;
481         }
482
483         return PyObject_GetAttrString(obj, discard_const_p(char, "value"));
484 }
485
486 PyObject *py_dcerpc_ndr_pointer_wrap(PyTypeObject *type, PyObject *obj)
487 {
488         PyObject *args = NULL;
489         PyObject *ret_obj = NULL;
490
491         args = PyTuple_New(1);
492         if (args == NULL) {
493                 return NULL;
494         }
495         Py_XINCREF(obj);
496         PyTuple_SetItem(args, 0, obj);
497
498         ret_obj = PyObject_Call((PyObject *)type, args, NULL);
499         Py_XDECREF(args);
500         return ret_obj;
501 }