pyrpc: Clarify failure mode after pytalloc_reference_ex() improvements
[gd/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 "includes.h"
25 #include "librpc/rpc/pyrpc_util.h"
26 #include "librpc/rpc/dcerpc.h"
27 #include "librpc/rpc/pyrpc.h"
28 #include "param/pyparam.h"
29 #include "auth/credentials/pycredentials.h"
30 #include "lib/events/events.h"
31 #include "lib/messaging/messaging.h"
32 #include "lib/messaging/irpc.h"
33
34 bool py_check_dcerpc_type(PyObject *obj, const char *module, const char *type_name)
35 {
36         PyObject *mod;
37         PyTypeObject *type;
38         bool ret;
39
40         mod = PyImport_ImportModule(module);
41
42         if (mod == NULL) {
43                 PyErr_Format(PyExc_RuntimeError, "Unable to import %s to check type %s",
44                         module, type_name);
45                 return false;
46         }
47
48         type = (PyTypeObject *)PyObject_GetAttrString(mod, type_name);
49         Py_DECREF(mod);
50         if (type == NULL) {
51                 PyErr_Format(PyExc_RuntimeError, "Unable to find type %s in module %s",
52                         module, type_name);
53                 return false;
54         }
55
56         ret = PyObject_TypeCheck(obj, type);
57         Py_DECREF(type);
58
59         if (!ret)
60                 PyErr_Format(PyExc_TypeError, "Expected type %s.%s, got %s",
61                         module, type_name, Py_TYPE(obj)->tp_name);
62
63         return ret;
64 }
65
66 /*
67   connect to a IRPC pipe from python
68  */
69 static NTSTATUS pyrpc_irpc_connect(TALLOC_CTX *mem_ctx, const char *irpc_server,
70                                    const struct ndr_interface_table *table,
71                                    struct tevent_context *event_ctx,
72                                    struct loadparm_context *lp_ctx,
73                                    struct dcerpc_binding_handle **binding_handle)
74 {
75         struct imessaging_context *msg;
76
77         msg = imessaging_client_init(mem_ctx, lp_ctx, event_ctx);
78         NT_STATUS_HAVE_NO_MEMORY(msg);
79
80         *binding_handle = irpc_binding_handle_by_name(mem_ctx, msg, irpc_server, table);
81         if (*binding_handle == NULL) {
82                 talloc_free(msg);
83                 return NT_STATUS_INVALID_PIPE_STATE;
84         }
85
86         /*
87          * Note: this allows nested event loops to happen,
88          * but as there's no top level event loop it's not that critical.
89          */
90         dcerpc_binding_handle_set_sync_ev(*binding_handle, event_ctx);
91
92         return NT_STATUS_OK;
93 }
94
95 PyObject *py_dcerpc_interface_init_helper(PyTypeObject *type, PyObject *args, PyObject *kwargs,
96                                           const struct ndr_interface_table *table)
97 {
98         dcerpc_InterfaceObject *ret;
99         const char *binding_string;
100         PyObject *py_lp_ctx = Py_None, *py_credentials = Py_None, *py_basis = Py_None;
101         NTSTATUS status;
102         const char *kwnames[] = {
103                 "binding", "lp_ctx", "credentials", "basis_connection", NULL
104         };
105
106         if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s|OOO:samr", discard_const_p(char *, kwnames), &binding_string, &py_lp_ctx, &py_credentials, &py_basis)) {
107                 return NULL;
108         }
109
110         status = dcerpc_init();
111         if (!NT_STATUS_IS_OK(status)) {
112                 PyErr_SetNTSTATUS(status);
113                 return NULL;
114         }
115
116         ret = PyObject_New(dcerpc_InterfaceObject, type);
117         ret->pipe = NULL;
118         ret->binding_handle = NULL;
119         ret->mem_ctx = talloc_new(NULL);
120         if (ret->mem_ctx == NULL) {
121                 PyErr_NoMemory();
122                 return NULL;
123         }
124
125         if (strncmp(binding_string, "irpc:", 5) == 0) {
126                 struct tevent_context *event_ctx;
127                 struct loadparm_context *lp_ctx;
128
129                 event_ctx = s4_event_context_init(ret->mem_ctx);
130                 if (event_ctx == NULL) {
131                         PyErr_SetString(PyExc_TypeError, "Expected loadparm context");
132                         TALLOC_FREE(ret->mem_ctx);
133                         return NULL;
134                 }
135
136                 lp_ctx = lpcfg_from_py_object(event_ctx, py_lp_ctx);
137                 if (lp_ctx == NULL) {
138                         PyErr_SetString(PyExc_TypeError, "Expected loadparm context");
139                         TALLOC_FREE(ret->mem_ctx);
140                         return NULL;
141                 }
142
143                 status = pyrpc_irpc_connect(ret->mem_ctx, binding_string+5, table,
144                                             event_ctx, lp_ctx, &ret->binding_handle);
145                 if (!NT_STATUS_IS_OK(status)) {
146                         PyErr_SetNTSTATUS(status);
147                         TALLOC_FREE(ret->mem_ctx);
148                         return NULL;
149                 }
150         } else if (py_basis != Py_None) {
151                 struct dcerpc_pipe *base_pipe;
152                 PyObject *py_base;
153                 PyTypeObject *ClientConnection_Type;
154
155                 py_base = PyImport_ImportModule("samba.dcerpc.base");
156                 if (py_base == NULL) {
157                         TALLOC_FREE(ret->mem_ctx);
158                         return NULL;
159                 }
160
161                 ClientConnection_Type = (PyTypeObject *)PyObject_GetAttrString(py_base, "ClientConnection");
162                 if (ClientConnection_Type == NULL) {
163                         PyErr_SetNone(PyExc_TypeError);
164                         TALLOC_FREE(ret->mem_ctx);
165                         return NULL;
166                 }
167
168                 if (!PyObject_TypeCheck(py_basis, ClientConnection_Type)) {
169                         PyErr_SetString(PyExc_TypeError, "basis_connection must be a DCE/RPC connection");
170                         TALLOC_FREE(ret->mem_ctx);
171                         return NULL;
172                 }
173
174                 base_pipe = talloc_reference(ret->mem_ctx,
175                                          ((dcerpc_InterfaceObject *)py_basis)->pipe);
176                 if (base_pipe == NULL) {
177                         PyErr_NoMemory();
178                         TALLOC_FREE(ret->mem_ctx);
179                         return NULL;
180                 }
181
182                 status = dcerpc_secondary_context(base_pipe, &ret->pipe, table);
183                 if (!NT_STATUS_IS_OK(status)) {
184                         PyErr_SetNTSTATUS(status);
185                         TALLOC_FREE(ret->mem_ctx);
186                         return NULL;
187                 }
188
189                 ret->pipe = talloc_steal(ret->mem_ctx, ret->pipe);
190         } else {
191                 struct tevent_context *event_ctx;
192                 struct loadparm_context *lp_ctx;
193                 struct cli_credentials *credentials;
194
195                 event_ctx = s4_event_context_init(ret->mem_ctx);
196                 if (event_ctx == NULL) {
197                         PyErr_SetString(PyExc_TypeError, "Expected loadparm context");
198                         TALLOC_FREE(ret->mem_ctx);
199                         return NULL;
200                 }
201
202                 lp_ctx = lpcfg_from_py_object(event_ctx, py_lp_ctx);
203                 if (lp_ctx == NULL) {
204                         PyErr_SetString(PyExc_TypeError, "Expected loadparm context");
205                         TALLOC_FREE(ret->mem_ctx);
206                         return NULL;
207                 }
208
209                 credentials = cli_credentials_from_py_object(py_credentials);
210                 if (credentials == NULL) {
211                         PyErr_SetString(PyExc_TypeError, "Expected credentials");
212                         TALLOC_FREE(ret->mem_ctx);
213                         return NULL;
214                 }
215                 status = dcerpc_pipe_connect(ret->mem_ctx, &ret->pipe, binding_string,
216                              table, credentials, event_ctx, lp_ctx);
217                 if (!NT_STATUS_IS_OK(status)) {
218                         PyErr_SetNTSTATUS(status);
219                         TALLOC_FREE(ret->mem_ctx);
220                         return NULL;
221                 }
222
223                 /*
224                  * the event context is cached under the connection,
225                  * so let it be a child of it.
226                  */
227                 talloc_steal(ret->pipe->conn, event_ctx);
228         }
229
230         if (ret->pipe) {
231                 ret->pipe->conn->flags |= DCERPC_NDR_REF_ALLOC;
232                 ret->binding_handle = ret->pipe->binding_handle;
233         }
234         return (PyObject *)ret;
235 }
236
237 static PyObject *py_dcerpc_run_function(dcerpc_InterfaceObject *iface,
238                                         const struct PyNdrRpcMethodDef *md,
239                                         PyObject *args, PyObject *kwargs)
240 {
241         TALLOC_CTX *mem_ctx;
242         NTSTATUS status;
243         void *r;
244         PyObject *result = Py_None;
245
246         if (md->pack_in_data == NULL || md->unpack_out_data == NULL) {
247                 PyErr_SetString(PyExc_NotImplementedError, "No marshalling code available yet");
248                 return NULL;
249         }
250
251         mem_ctx = talloc_new(NULL);
252         if (mem_ctx == NULL) {
253                 PyErr_NoMemory();
254                 return NULL;
255         }
256
257         r = talloc_zero_size(mem_ctx, md->table->calls[md->opnum].struct_size);
258         if (r == NULL) {
259                 PyErr_NoMemory();
260                 return NULL;
261         }
262
263         if (!md->pack_in_data(args, kwargs, r)) {
264                 talloc_free(mem_ctx);
265                 return NULL;
266         }
267
268         status = md->call(iface->binding_handle, mem_ctx, r);
269         if (!NT_STATUS_IS_OK(status)) {
270                 PyErr_SetDCERPCStatus(iface->pipe, status);
271                 talloc_free(mem_ctx);
272                 return NULL;
273         }
274
275         result = md->unpack_out_data(r);
276
277         talloc_free(mem_ctx);
278         return result;
279 }
280
281 static PyObject *py_dcerpc_call_wrapper(PyObject *self, PyObject *args, void *wrapped, PyObject *kwargs)
282 {       
283         dcerpc_InterfaceObject *iface = (dcerpc_InterfaceObject *)self;
284         const struct PyNdrRpcMethodDef *md = (const struct PyNdrRpcMethodDef *)wrapped;
285
286         return py_dcerpc_run_function(iface, md, args, kwargs);
287 }
288
289 bool PyInterface_AddNdrRpcMethods(PyTypeObject *ifacetype, const struct PyNdrRpcMethodDef *mds)
290 {
291         int i;
292         for (i = 0; mds[i].name; i++) {
293                 PyObject *ret;
294                 struct wrapperbase *wb = (struct wrapperbase *)calloc(sizeof(struct wrapperbase), 1);
295
296                 if (wb == NULL) {
297                         return false;
298                 }
299                 wb->name = discard_const_p(char, mds[i].name);
300                 wb->flags = PyWrapperFlag_KEYWORDS;
301                 wb->wrapper = (wrapperfunc)py_dcerpc_call_wrapper;
302                 wb->doc = discard_const_p(char, mds[i].doc);
303
304                 ret = PyDescr_NewWrapper(ifacetype, wb, discard_const_p(void, &mds[i]));
305
306                 PyDict_SetItemString(ifacetype->tp_dict, mds[i].name, 
307                                      (PyObject *)ret);
308         }
309
310         return true;
311 }
312
313 PyObject *py_dcerpc_syntax_init_helper(PyTypeObject *type, PyObject *args, PyObject *kwargs,
314                                        const struct ndr_syntax_id *syntax)
315 {
316         PyObject *ret;
317         struct ndr_syntax_id *obj;
318         const char *kwnames[] = { NULL };
319
320         if (!PyArg_ParseTupleAndKeywords(args, kwargs, ":abstract_syntax", discard_const_p(char *, kwnames))) {
321                 return NULL;
322         }
323
324         ret = pytalloc_new(struct ndr_syntax_id, type);
325         if (ret == NULL) {
326                 return NULL;
327         }
328
329         obj = (struct ndr_syntax_id *)pytalloc_get_ptr(ret);
330         *obj = *syntax;
331
332         return ret;
333 }
334
335 void PyErr_SetDCERPCStatus(struct dcerpc_pipe *p, NTSTATUS status)
336 {
337         if (p && NT_STATUS_EQUAL(status, NT_STATUS_NET_WRITE_FAULT)) {
338                 status = dcerpc_fault_to_nt_status(p->last_fault_code);
339         }
340         PyErr_SetNTSTATUS(status);
341 }
342
343
344 /*
345   take a NDR structure that has a type in a python module and return
346   it as a python object
347
348   r is the NDR structure pointer (a C structure)
349
350   r_ctx is the context that is a parent of r. It will be referenced by
351   the resulting python object
352
353   This MUST only be used by objects that are based on pytalloc_Object
354   otherwise the pytalloc_reference_ex() will fail.
355  */
356 PyObject *py_return_ndr_struct(const char *module_name, const char *type_name,
357                                TALLOC_CTX *r_ctx, void *r)
358 {
359         PyTypeObject *py_type;
360         PyObject *module;
361
362         if (r == NULL) {
363                 Py_RETURN_NONE;
364         }
365
366         module = PyImport_ImportModule(module_name);
367         if (module == NULL) {
368                 return NULL;
369         }
370
371         py_type = (PyTypeObject *)PyObject_GetAttrString(module, type_name);
372         if (py_type == NULL) {
373                 return NULL;
374         }
375
376         return pytalloc_reference_ex(py_type, r_ctx, r);
377 }
378
379 PyObject *PyString_FromStringOrNULL(const char *str)
380 {
381         if (str == NULL) {
382                 Py_RETURN_NONE;
383         }
384         return PyString_FromString(str);
385 }