29e501cdfefc06d7570e4639f226c97f0e4a8a4e
[metze/samba/wip.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 "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"
35
36 bool py_check_dcerpc_type(PyObject *obj, const char *module, const char *type_name)
37 {
38         PyObject *mod;
39         PyTypeObject *type;
40         bool ret;
41
42         mod = PyImport_ImportModule(module);
43
44         if (mod == NULL) {
45                 PyErr_Format(PyExc_RuntimeError, "Unable to import %s to check type %s",
46                         module, type_name);
47                 return false;
48         }
49
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;
56         }
57
58         ret = PyObject_TypeCheck(obj, type);
59         Py_DECREF(type);
60
61         if (!ret)
62                 PyErr_Format(PyExc_TypeError, "Expected type %s.%s, got %s",
63                         module, type_name, Py_TYPE(obj)->tp_name);
64
65         return ret;
66 }
67
68 /*
69   connect to a IRPC pipe from python
70  */
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)
76 {
77         struct imessaging_context *msg;
78
79         msg = imessaging_client_init(mem_ctx, lp_ctx, event_ctx);
80         NT_STATUS_HAVE_NO_MEMORY(msg);
81
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;
86         }
87
88         /*
89          * Note: this allows nested event loops to happen,
90          * but as there's no top level event loop it's not that critical.
91          */
92         dcerpc_binding_handle_set_sync_ev(*binding_handle, event_ctx);
93
94         return NT_STATUS_OK;
95 }
96
97 PyObject *py_dcerpc_interface_init_helper(PyTypeObject *type, PyObject *args, PyObject *kwargs,
98                                           const struct ndr_interface_table *table)
99 {
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
107         };
108
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;
111         }
112
113         status = dcerpc_init();
114         if (!NT_STATUS_IS_OK(status)) {
115                 PyErr_SetNTSTATUS(status);
116                 return NULL;
117         }
118
119         ret = PyObject_New(dcerpc_InterfaceObject, type);
120         if (ret == NULL) {
121                 PyErr_NoMemory();
122                 return NULL;
123         }
124
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;
132         }
133
134         if (strncmp(binding_string, "irpc:", 5) == 0) {
135                 struct loadparm_context *lp_ctx;
136
137                 ret->ev = s4_event_context_init(ret->mem_ctx);
138                 if (ret->ev == NULL) {
139                         PyErr_SetString(PyExc_TypeError, "Expected loadparm context");
140                         Py_DECREF(ret);
141                         return NULL;
142                 }
143
144                 lp_ctx = lpcfg_from_py_object(ret->ev, py_lp_ctx);
145                 if (lp_ctx == NULL) {
146                         PyErr_SetString(PyExc_TypeError, "Expected loadparm context");
147                         Py_DECREF(ret);
148                         return NULL;
149                 }
150
151                 status = pyrpc_irpc_connect(ret->mem_ctx, binding_string+5, table,
152                                             ret->ev, lp_ctx, &ret->binding_handle);
153                 if (!NT_STATUS_IS_OK(status)) {
154                         PyErr_SetNTSTATUS(status);
155                         Py_DECREF(ret);
156                         return NULL;
157                 }
158         } else if (py_basis != Py_None) {
159                 struct dcerpc_pipe *base_pipe;
160                 PyObject *py_base;
161                 PyTypeObject *ClientConnection_Type;
162
163                 py_base = PyImport_ImportModule("samba.dcerpc.base");
164                 if (py_base == NULL) {
165                         Py_DECREF(ret);
166                         return NULL;
167                 }
168
169                 ClientConnection_Type = (PyTypeObject *)PyObject_GetAttrString(py_base, "ClientConnection");
170                 if (ClientConnection_Type == NULL) {
171                         PyErr_SetNone(PyExc_TypeError);
172                         Py_DECREF(ret);
173                         Py_DECREF(py_base);
174                         return NULL;
175                 }
176
177                 if (!PyObject_TypeCheck(py_basis, ClientConnection_Type)) {
178                         PyErr_SetString(PyExc_TypeError, "basis_connection must be a DCE/RPC connection");
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                         Py_DECREF(ret);
190                         Py_DECREF(py_base);
191                         Py_DECREF(ClientConnection_Type);
192                         return NULL;
193                 }
194
195                 ret->ev = talloc_reference(
196                         ret->mem_ctx,
197                         ((dcerpc_InterfaceObject *)py_basis)->ev);
198                 if (ret->ev == NULL) {
199                         PyErr_NoMemory();
200                         Py_DECREF(ret);
201                         Py_DECREF(py_base);
202                         Py_DECREF(ClientConnection_Type);
203                         return NULL;
204                 }
205
206                 status = dcerpc_secondary_context(base_pipe, &ret->pipe, table);
207                 if (!NT_STATUS_IS_OK(status)) {
208                         PyErr_SetNTSTATUS(status);
209                         Py_DECREF(ret);
210                         Py_DECREF(py_base);
211                         Py_DECREF(ClientConnection_Type);
212                         return NULL;
213                 }
214
215                 ret->pipe = talloc_steal(ret->mem_ctx, ret->pipe);
216                 Py_XDECREF(ClientConnection_Type);
217                 Py_XDECREF(py_base);
218         } else {
219                 struct loadparm_context *lp_ctx;
220                 struct cli_credentials *credentials;
221
222                 ret->ev = s4_event_context_init(ret->mem_ctx);
223                 if (ret->ev == NULL) {
224                         PyErr_SetString(PyExc_TypeError, "Expected loadparm context");
225                         Py_DECREF(ret);
226                         return NULL;
227                 }
228
229                 lp_ctx = lpcfg_from_py_object(ret->ev, py_lp_ctx);
230                 if (lp_ctx == NULL) {
231                         PyErr_SetString(PyExc_TypeError, "Expected loadparm context");
232                         Py_DECREF(ret);
233                         return NULL;
234                 }
235
236                 credentials = cli_credentials_from_py_object(py_credentials);
237                 if (credentials == NULL) {
238                         PyErr_SetString(PyExc_TypeError, "Expected credentials");
239                         Py_DECREF(ret);
240                         return NULL;
241                 }
242                 status = dcerpc_pipe_connect(ret->mem_ctx, &ret->pipe, binding_string,
243                              table, credentials, ret->ev, lp_ctx);
244                 if (!NT_STATUS_IS_OK(status)) {
245                         PyErr_SetNTSTATUS(status);
246                         Py_DECREF(ret);
247                         return NULL;
248                 }
249         }
250
251         if (ret->pipe) {
252                 ret->pipe->conn->flags |= DCERPC_NDR_REF_ALLOC;
253                 ret->binding_handle = ret->pipe->binding_handle;
254         }
255
256         /* reset timeout for the handle */
257         if ((timeout != ((unsigned int)-1)) && (ret->binding_handle != NULL)) {
258                 dcerpc_binding_handle_set_timeout(ret->binding_handle, timeout);
259         }
260
261         return (PyObject *)ret;
262 }
263
264 static PyObject *py_dcerpc_run_function(dcerpc_InterfaceObject *iface,
265                                         const struct PyNdrRpcMethodDef *md,
266                                         PyObject *args, PyObject *kwargs)
267 {
268         TALLOC_CTX *mem_ctx;
269         NTSTATUS status;
270         void *r;
271         PyObject *result = Py_None;
272
273         if (md->pack_in_data == NULL || md->unpack_out_data == NULL) {
274                 PyErr_SetString(PyExc_NotImplementedError, "No marshalling code available yet");
275                 return NULL;
276         }
277
278         mem_ctx = talloc_new(NULL);
279         if (mem_ctx == NULL) {
280                 PyErr_NoMemory();
281                 return NULL;
282         }
283
284         r = talloc_zero_size(mem_ctx, md->table->calls[md->opnum].struct_size);
285         if (r == NULL) {
286                 PyErr_NoMemory();
287                 return NULL;
288         }
289
290         if (!md->pack_in_data(args, kwargs, r)) {
291                 talloc_free(mem_ctx);
292                 return NULL;
293         }
294
295         status = md->call(iface->binding_handle, mem_ctx, r);
296         if (!NT_STATUS_IS_OK(status)) {
297                 PyErr_SetDCERPCStatus(iface->pipe, status);
298                 talloc_free(mem_ctx);
299                 return NULL;
300         }
301
302         result = md->unpack_out_data(r);
303
304         talloc_free(mem_ctx);
305         return result;
306 }
307
308 static PyObject *py_dcerpc_call_wrapper(PyObject *self, PyObject *args, void *wrapped, PyObject *kwargs)
309 {       
310         dcerpc_InterfaceObject *iface = (dcerpc_InterfaceObject *)self;
311         const struct PyNdrRpcMethodDef *md = (const struct PyNdrRpcMethodDef *)wrapped;
312
313         return py_dcerpc_run_function(iface, md, args, kwargs);
314 }
315
316 bool PyInterface_AddNdrRpcMethods(PyTypeObject *ifacetype, const struct PyNdrRpcMethodDef *mds)
317 {
318         int i;
319         for (i = 0; mds[i].name; i++) {
320                 PyObject *ret;
321                 struct wrapperbase *wb = (struct wrapperbase *)calloc(sizeof(struct wrapperbase), 1);
322
323                 if (wb == NULL) {
324                         return false;
325                 }
326                 wb->name = discard_const_p(char, mds[i].name);
327                 wb->flags = PyWrapperFlag_KEYWORDS;
328                 wb->wrapper = PY_DISCARD_FUNC_SIG(wrapperfunc,
329                                                   py_dcerpc_call_wrapper);
330                 wb->doc = discard_const_p(char, mds[i].doc);
331
332                 ret = PyDescr_NewWrapper(ifacetype, wb, discard_const_p(void, &mds[i]));
333
334                 PyDict_SetItemString(ifacetype->tp_dict, mds[i].name, 
335                                      (PyObject *)ret);
336                 Py_CLEAR(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         PyObject *result = NULL;
391
392         if (r == NULL) {
393                 Py_RETURN_NONE;
394         }
395
396         module = PyImport_ImportModule(module_name);
397         if (module == NULL) {
398                 return NULL;
399         }
400
401         py_type = (PyTypeObject *)PyObject_GetAttrString(module, type_name);
402         if (py_type == NULL) {
403                 Py_DECREF(module);
404                 return NULL;
405         }
406
407         result = pytalloc_reference_ex(py_type, r_ctx, r);
408         Py_CLEAR(module);
409         Py_CLEAR(py_type);
410         return result;
411 }
412
413 PyObject *PyString_FromStringOrNULL(const char *str)
414 {
415         if (str == NULL) {
416                 Py_RETURN_NONE;
417         }
418         return PyStr_FromString(str);
419 }
420
421 PyObject *pyrpc_import_union(PyTypeObject *type, TALLOC_CTX *mem_ctx, int level,
422                              const void *in, const char *typename)
423 {
424         PyObject *mem_ctx_obj = NULL;
425         PyObject *in_obj = NULL;
426         PyObject *ret = NULL;
427
428         mem_ctx_obj = pytalloc_GenericObject_reference(mem_ctx);
429         if (mem_ctx_obj == NULL) {
430                 return NULL;
431         }
432
433         in_obj = pytalloc_GenericObject_reference_ex(mem_ctx, discard_const(in));
434         if (in_obj == NULL) {
435                 Py_XDECREF(mem_ctx_obj);
436                 return NULL;
437         }
438
439         ret = PyObject_CallMethod((PyObject *)type,
440                                   discard_const_p(char, "__import__"),
441                                   discard_const_p(char, "OiO"),
442                                   mem_ctx_obj, level, in_obj);
443         Py_XDECREF(mem_ctx_obj);
444         Py_XDECREF(in_obj);
445         if (ret == NULL) {
446                 return NULL;
447         }
448
449         return ret;
450 }
451
452 void *pyrpc_export_union(PyTypeObject *type, TALLOC_CTX *mem_ctx, int level,
453                          PyObject *in, const char *typename)
454 {
455         PyObject *mem_ctx_obj = NULL;
456         PyObject *ret_obj = NULL;
457         void *ret = NULL;
458
459         mem_ctx_obj = pytalloc_GenericObject_reference(mem_ctx);
460         if (mem_ctx_obj == NULL) {
461                 return NULL;
462         }
463
464         ret_obj = PyObject_CallMethod((PyObject *)type,
465                                       discard_const_p(char, "__export__"),
466                                       discard_const_p(char, "OiO"),
467                                       mem_ctx_obj, level, in);
468         Py_XDECREF(mem_ctx_obj);
469         if (ret_obj == NULL) {
470                 return NULL;
471         }
472
473         ret = _pytalloc_get_type(ret_obj, typename);
474         Py_XDECREF(ret_obj);
475         return ret;
476 }
477
478 PyObject *py_dcerpc_ndr_pointer_deref(PyTypeObject *type, PyObject *obj)
479 {
480         if (!PyObject_TypeCheck(obj, type)) {
481                 PyErr_Format(PyExc_TypeError,
482                              "Expected type '%s' but got type '%s'",
483                              (type)->tp_name, Py_TYPE(obj)->tp_name);
484                 return NULL;
485         }
486
487         return PyObject_GetAttrString(obj, discard_const_p(char, "value"));
488 }
489
490 PyObject *py_dcerpc_ndr_pointer_wrap(PyTypeObject *type, PyObject *obj)
491 {
492         PyObject *args = NULL;
493         PyObject *ret_obj = NULL;
494
495         args = PyTuple_New(1);
496         if (args == NULL) {
497                 return NULL;
498         }
499         Py_XINCREF(obj);
500         PyTuple_SetItem(args, 0, obj);
501
502         ret_obj = PyObject_Call((PyObject *)type, args, NULL);
503         Py_XDECREF(args);
504         return ret_obj;
505 }