cfbb9cb19776a6c23d467aa52f2d6c8949d1dfd2
[kai/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         unsigned int timeout = (unsigned int)-1;
103         const char *kwnames[] = {
104                 "binding", "lp_ctx", "credentials", "timeout", "basis_connection", NULL
105         };
106
107         if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s|OOIO:samr", discard_const_p(char *, kwnames), &binding_string, &py_lp_ctx, &py_credentials, &timeout, &py_basis)) {
108                 return NULL;
109         }
110
111         status = dcerpc_init();
112         if (!NT_STATUS_IS_OK(status)) {
113                 PyErr_SetNTSTATUS(status);
114                 return NULL;
115         }
116
117         ret = PyObject_New(dcerpc_InterfaceObject, type);
118         ret->pipe = NULL;
119         ret->binding_handle = NULL;
120         ret->mem_ctx = talloc_new(NULL);
121         if (ret->mem_ctx == NULL) {
122                 PyErr_NoMemory();
123                 return NULL;
124         }
125
126         if (strncmp(binding_string, "irpc:", 5) == 0) {
127                 struct tevent_context *event_ctx;
128                 struct loadparm_context *lp_ctx;
129
130                 event_ctx = s4_event_context_init(ret->mem_ctx);
131                 if (event_ctx == NULL) {
132                         PyErr_SetString(PyExc_TypeError, "Expected loadparm context");
133                         TALLOC_FREE(ret->mem_ctx);
134                         return NULL;
135                 }
136
137                 lp_ctx = lpcfg_from_py_object(event_ctx, py_lp_ctx);
138                 if (lp_ctx == NULL) {
139                         PyErr_SetString(PyExc_TypeError, "Expected loadparm context");
140                         TALLOC_FREE(ret->mem_ctx);
141                         return NULL;
142                 }
143
144                 status = pyrpc_irpc_connect(ret->mem_ctx, binding_string+5, table,
145                                             event_ctx, lp_ctx, &ret->binding_handle);
146                 if (!NT_STATUS_IS_OK(status)) {
147                         PyErr_SetNTSTATUS(status);
148                         TALLOC_FREE(ret->mem_ctx);
149                         return NULL;
150                 }
151         } else if (py_basis != Py_None) {
152                 struct dcerpc_pipe *base_pipe;
153                 PyObject *py_base;
154                 PyTypeObject *ClientConnection_Type;
155
156                 py_base = PyImport_ImportModule("samba.dcerpc.base");
157                 if (py_base == NULL) {
158                         TALLOC_FREE(ret->mem_ctx);
159                         return NULL;
160                 }
161
162                 ClientConnection_Type = (PyTypeObject *)PyObject_GetAttrString(py_base, "ClientConnection");
163                 if (ClientConnection_Type == NULL) {
164                         PyErr_SetNone(PyExc_TypeError);
165                         TALLOC_FREE(ret->mem_ctx);
166                         return NULL;
167                 }
168
169                 if (!PyObject_TypeCheck(py_basis, ClientConnection_Type)) {
170                         PyErr_SetString(PyExc_TypeError, "basis_connection must be a DCE/RPC connection");
171                         TALLOC_FREE(ret->mem_ctx);
172                         return NULL;
173                 }
174
175                 base_pipe = talloc_reference(ret->mem_ctx,
176                                          ((dcerpc_InterfaceObject *)py_basis)->pipe);
177                 if (base_pipe == NULL) {
178                         PyErr_NoMemory();
179                         TALLOC_FREE(ret->mem_ctx);
180                         return NULL;
181                 }
182
183                 status = dcerpc_secondary_context(base_pipe, &ret->pipe, table);
184                 if (!NT_STATUS_IS_OK(status)) {
185                         PyErr_SetNTSTATUS(status);
186                         TALLOC_FREE(ret->mem_ctx);
187                         return NULL;
188                 }
189
190                 ret->pipe = talloc_steal(ret->mem_ctx, ret->pipe);
191         } else {
192                 struct tevent_context *event_ctx;
193                 struct loadparm_context *lp_ctx;
194                 struct cli_credentials *credentials;
195
196                 event_ctx = s4_event_context_init(ret->mem_ctx);
197                 if (event_ctx == NULL) {
198                         PyErr_SetString(PyExc_TypeError, "Expected loadparm context");
199                         TALLOC_FREE(ret->mem_ctx);
200                         return NULL;
201                 }
202
203                 lp_ctx = lpcfg_from_py_object(event_ctx, py_lp_ctx);
204                 if (lp_ctx == NULL) {
205                         PyErr_SetString(PyExc_TypeError, "Expected loadparm context");
206                         TALLOC_FREE(ret->mem_ctx);
207                         return NULL;
208                 }
209
210                 credentials = cli_credentials_from_py_object(py_credentials);
211                 if (credentials == NULL) {
212                         PyErr_SetString(PyExc_TypeError, "Expected credentials");
213                         TALLOC_FREE(ret->mem_ctx);
214                         return NULL;
215                 }
216                 status = dcerpc_pipe_connect(ret->mem_ctx, &ret->pipe, binding_string,
217                              table, credentials, event_ctx, lp_ctx);
218                 if (!NT_STATUS_IS_OK(status)) {
219                         PyErr_SetNTSTATUS(status);
220                         TALLOC_FREE(ret->mem_ctx);
221                         return NULL;
222                 }
223
224                 /*
225                  * the event context is cached under the connection,
226                  * so let it be a child of it.
227                  */
228                 talloc_steal(ret->pipe->conn, event_ctx);
229         }
230
231         if (ret->pipe) {
232                 ret->pipe->conn->flags |= DCERPC_NDR_REF_ALLOC;
233                 ret->binding_handle = ret->pipe->binding_handle;
234         }
235
236         /* reset timeout for the handle */
237         if ((timeout != ((unsigned int)-1)) && (ret->binding_handle != NULL)) {
238                 dcerpc_binding_handle_set_timeout(ret->binding_handle, timeout);
239         }
240
241         return (PyObject *)ret;
242 }
243
244 static PyObject *py_dcerpc_run_function(dcerpc_InterfaceObject *iface,
245                                         const struct PyNdrRpcMethodDef *md,
246                                         PyObject *args, PyObject *kwargs)
247 {
248         TALLOC_CTX *mem_ctx;
249         NTSTATUS status;
250         void *r;
251         PyObject *result = Py_None;
252
253         if (md->pack_in_data == NULL || md->unpack_out_data == NULL) {
254                 PyErr_SetString(PyExc_NotImplementedError, "No marshalling code available yet");
255                 return NULL;
256         }
257
258         mem_ctx = talloc_new(NULL);
259         if (mem_ctx == NULL) {
260                 PyErr_NoMemory();
261                 return NULL;
262         }
263
264         r = talloc_zero_size(mem_ctx, md->table->calls[md->opnum].struct_size);
265         if (r == NULL) {
266                 PyErr_NoMemory();
267                 return NULL;
268         }
269
270         if (!md->pack_in_data(args, kwargs, r)) {
271                 talloc_free(mem_ctx);
272                 return NULL;
273         }
274
275         status = md->call(iface->binding_handle, mem_ctx, r);
276         if (!NT_STATUS_IS_OK(status)) {
277                 PyErr_SetDCERPCStatus(iface->pipe, status);
278                 talloc_free(mem_ctx);
279                 return NULL;
280         }
281
282         result = md->unpack_out_data(r);
283
284         talloc_free(mem_ctx);
285         return result;
286 }
287
288 static PyObject *py_dcerpc_call_wrapper(PyObject *self, PyObject *args, void *wrapped, PyObject *kwargs)
289 {       
290         dcerpc_InterfaceObject *iface = (dcerpc_InterfaceObject *)self;
291         const struct PyNdrRpcMethodDef *md = (const struct PyNdrRpcMethodDef *)wrapped;
292
293         return py_dcerpc_run_function(iface, md, args, kwargs);
294 }
295
296 bool PyInterface_AddNdrRpcMethods(PyTypeObject *ifacetype, const struct PyNdrRpcMethodDef *mds)
297 {
298         int i;
299         for (i = 0; mds[i].name; i++) {
300                 PyObject *ret;
301                 struct wrapperbase *wb = (struct wrapperbase *)calloc(sizeof(struct wrapperbase), 1);
302
303                 if (wb == NULL) {
304                         return false;
305                 }
306                 wb->name = discard_const_p(char, mds[i].name);
307                 wb->flags = PyWrapperFlag_KEYWORDS;
308                 wb->wrapper = (wrapperfunc)py_dcerpc_call_wrapper;
309                 wb->doc = discard_const_p(char, mds[i].doc);
310
311                 ret = PyDescr_NewWrapper(ifacetype, wb, discard_const_p(void, &mds[i]));
312
313                 PyDict_SetItemString(ifacetype->tp_dict, mds[i].name, 
314                                      (PyObject *)ret);
315         }
316
317         return true;
318 }
319
320 PyObject *py_dcerpc_syntax_init_helper(PyTypeObject *type, PyObject *args, PyObject *kwargs,
321                                        const struct ndr_syntax_id *syntax)
322 {
323         PyObject *ret;
324         struct ndr_syntax_id *obj;
325         const char *kwnames[] = { NULL };
326
327         if (!PyArg_ParseTupleAndKeywords(args, kwargs, ":abstract_syntax", discard_const_p(char *, kwnames))) {
328                 return NULL;
329         }
330
331         ret = pytalloc_new(struct ndr_syntax_id, type);
332         if (ret == NULL) {
333                 return NULL;
334         }
335
336         obj = (struct ndr_syntax_id *)pytalloc_get_ptr(ret);
337         *obj = *syntax;
338
339         return ret;
340 }
341
342 void PyErr_SetDCERPCStatus(struct dcerpc_pipe *p, NTSTATUS status)
343 {
344         if (p && NT_STATUS_EQUAL(status, NT_STATUS_NET_WRITE_FAULT)) {
345                 status = dcerpc_fault_to_nt_status(p->last_fault_code);
346         }
347         PyErr_SetNTSTATUS(status);
348 }
349
350
351 /*
352   take a NDR structure that has a type in a python module and return
353   it as a python object
354
355   r is the NDR structure pointer (a C structure)
356
357   r_ctx is the context that is a parent of r. It will be referenced by
358   the resulting python object
359
360   This MUST only be used by objects that are based on pytalloc_Object
361   otherwise the pytalloc_reference_ex() will fail.
362  */
363 PyObject *py_return_ndr_struct(const char *module_name, const char *type_name,
364                                TALLOC_CTX *r_ctx, void *r)
365 {
366         PyTypeObject *py_type;
367         PyObject *module;
368
369         if (r == NULL) {
370                 Py_RETURN_NONE;
371         }
372
373         module = PyImport_ImportModule(module_name);
374         if (module == NULL) {
375                 return NULL;
376         }
377
378         py_type = (PyTypeObject *)PyObject_GetAttrString(module, type_name);
379         if (py_type == NULL) {
380                 return NULL;
381         }
382
383         return pytalloc_reference_ex(py_type, r_ctx, r);
384 }
385
386 PyObject *PyString_FromStringOrNULL(const char *str)
387 {
388         if (str == NULL) {
389                 Py_RETURN_NONE;
390         }
391         return PyString_FromString(str);
392 }
393
394 PyObject *pyrpc_import_union(PyTypeObject *type, TALLOC_CTX *mem_ctx, int level,
395                              const void *in, const char *typename)
396 {
397         static const char *mem_ctx_type = "TALLOC_CTX";
398         PyObject *mem_ctx_obj = NULL;
399         PyObject *in_obj = NULL;
400         PyObject *ret = NULL;
401
402         mem_ctx_obj = PyCObject_FromVoidPtrAndDesc(mem_ctx,
403                                         discard_const_p(char, mem_ctx_type),
404                                         NULL);
405         if (mem_ctx_obj == NULL) {
406                 return NULL;
407         }
408
409         in_obj = PyCObject_FromVoidPtrAndDesc(discard_const(in),
410                                         discard_const_p(char, typename),
411                                         NULL);
412         if (in_obj == NULL) {
413                 Py_XDECREF(mem_ctx_obj);
414                 return NULL;
415         }
416
417         ret = PyObject_CallMethod((PyObject *)type,
418                                   discard_const_p(char, "__import__"),
419                                   discard_const_p(char, "OiO"),
420                                   mem_ctx_obj, level, in_obj);
421         Py_XDECREF(mem_ctx_obj);
422         Py_XDECREF(in_obj);
423         if (ret == NULL) {
424                 return NULL;
425         }
426
427         return ret;
428 }
429
430 void *pyrpc_export_union(PyTypeObject *type, TALLOC_CTX *mem_ctx, int level,
431                          PyObject *in, const char *typename)
432 {
433         static const char *mem_ctx_type = "TALLOC_CTX";
434         PyObject *mem_ctx_obj = NULL;
435         PyObject *ret_obj = NULL;
436         const char *ret_desc = NULL;
437         void *ret = NULL;
438         int cmp;
439
440         mem_ctx_obj = PyCObject_FromVoidPtrAndDesc(mem_ctx,
441                                         discard_const_p(char, mem_ctx_type),
442                                         NULL);
443         if (mem_ctx_obj == NULL) {
444                 return NULL;
445         }
446
447         ret_obj = PyObject_CallMethod((PyObject *)type,
448                                       discard_const_p(char, "__export__"),
449                                       discard_const_p(char, "OiO"),
450                                       mem_ctx_obj, level, in);
451         Py_XDECREF(mem_ctx_obj);
452         if (ret_obj == NULL) {
453                 return NULL;
454         }
455
456         if (!PyCObject_Check(ret_obj)) {
457                 Py_XDECREF(ret_obj);
458                 PyErr_Format(PyExc_TypeError,
459                              "New %s.__export__() returned no PyCObject!",
460                              type->tp_name);
461                 return NULL;
462         }
463
464         ret_desc = (const char *)PyCObject_GetDesc(ret_obj);
465         if (ret_desc == NULL) {
466                 Py_XDECREF(ret_obj);
467                 PyErr_Format(PyExc_TypeError,
468                              "New %s.__export__() returned no PyCObject_GetDesc()!",
469                              type->tp_name);
470                 return NULL;
471         }
472
473         cmp = strncmp(typename, ret_desc, strlen(typename) + 1);
474         if (cmp != 0) {
475                 Py_XDECREF(ret_obj);
476                 PyErr_Format(PyExc_TypeError,
477                              "New %s.__export__() returned PyCObject_GetDesc() != %s!",
478                              type->tp_name, typename);
479                 return NULL;
480         }
481
482         ret = PyCObject_AsVoidPtr(ret_obj);
483         Py_XDECREF(ret_obj);
484         return ret;
485 }