TODO pyrpc_string_array_{from,to}_PyList()
[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 "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         if (ret == NULL) {
120                 PyErr_NoMemory();
121                 return NULL;
122         }
123
124         ret->pipe = NULL;
125         ret->binding_handle = NULL;
126         ret->mem_ctx = talloc_new(NULL);
127         if (ret->mem_ctx == NULL) {
128                 PyErr_NoMemory();
129                 return NULL;
130         }
131
132         if (strncmp(binding_string, "irpc:", 5) == 0) {
133                 struct tevent_context *event_ctx;
134                 struct loadparm_context *lp_ctx;
135
136                 event_ctx = s4_event_context_init(ret->mem_ctx);
137                 if (event_ctx == NULL) {
138                         PyErr_SetString(PyExc_TypeError, "Expected loadparm context");
139                         TALLOC_FREE(ret->mem_ctx);
140                         Py_DECREF(ret);
141                         return NULL;
142                 }
143
144                 lp_ctx = lpcfg_from_py_object(event_ctx, py_lp_ctx);
145                 if (lp_ctx == NULL) {
146                         PyErr_SetString(PyExc_TypeError, "Expected loadparm context");
147                         TALLOC_FREE(ret->mem_ctx);
148                         Py_DECREF(ret);
149                         return NULL;
150                 }
151
152                 status = pyrpc_irpc_connect(ret->mem_ctx, binding_string+5, table,
153                                             event_ctx, lp_ctx, &ret->binding_handle);
154                 if (!NT_STATUS_IS_OK(status)) {
155                         PyErr_SetNTSTATUS(status);
156                         TALLOC_FREE(ret->mem_ctx);
157                         Py_DECREF(ret);
158                         return NULL;
159                 }
160         } else if (py_basis != Py_None) {
161                 struct dcerpc_pipe *base_pipe;
162                 PyObject *py_base;
163                 PyTypeObject *ClientConnection_Type;
164
165                 py_base = PyImport_ImportModule("samba.dcerpc.base");
166                 if (py_base == NULL) {
167                         TALLOC_FREE(ret->mem_ctx);
168                         Py_DECREF(ret);
169                         return NULL;
170                 }
171
172                 ClientConnection_Type = (PyTypeObject *)PyObject_GetAttrString(py_base, "ClientConnection");
173                 if (ClientConnection_Type == NULL) {
174                         PyErr_SetNone(PyExc_TypeError);
175                         TALLOC_FREE(ret->mem_ctx);
176                         Py_DECREF(ret);
177                         Py_DECREF(py_base);
178                         return NULL;
179                 }
180
181                 if (!PyObject_TypeCheck(py_basis, ClientConnection_Type)) {
182                         PyErr_SetString(PyExc_TypeError, "basis_connection must be a DCE/RPC connection");
183                         TALLOC_FREE(ret->mem_ctx);
184                         Py_DECREF(ret);
185                         Py_DECREF(py_base);
186                         Py_DECREF(ClientConnection_Type);
187                         return NULL;
188                 }
189
190                 base_pipe = talloc_reference(ret->mem_ctx,
191                                          ((dcerpc_InterfaceObject *)py_basis)->pipe);
192                 if (base_pipe == NULL) {
193                         PyErr_NoMemory();
194                         TALLOC_FREE(ret->mem_ctx);
195                         Py_DECREF(ret);
196                         Py_DECREF(py_base);
197                         Py_DECREF(ClientConnection_Type);
198                         return NULL;
199                 }
200
201                 status = dcerpc_secondary_context(base_pipe, &ret->pipe, table);
202                 if (!NT_STATUS_IS_OK(status)) {
203                         PyErr_SetNTSTATUS(status);
204                         TALLOC_FREE(ret->mem_ctx);
205                         Py_DECREF(ret);
206                         Py_DECREF(py_base);
207                         Py_DECREF(ClientConnection_Type);
208                         return NULL;
209                 }
210
211                 ret->pipe = talloc_steal(ret->mem_ctx, ret->pipe);
212                 Py_XDECREF(ClientConnection_Type);
213                 Py_XDECREF(py_base);
214         } else {
215                 struct tevent_context *event_ctx;
216                 struct loadparm_context *lp_ctx;
217                 struct cli_credentials *credentials;
218
219                 event_ctx = s4_event_context_init(ret->mem_ctx);
220                 if (event_ctx == NULL) {
221                         PyErr_SetString(PyExc_TypeError, "Expected loadparm context");
222                         TALLOC_FREE(ret->mem_ctx);
223                         Py_DECREF(ret);
224                         return NULL;
225                 }
226
227                 lp_ctx = lpcfg_from_py_object(event_ctx, py_lp_ctx);
228                 if (lp_ctx == NULL) {
229                         PyErr_SetString(PyExc_TypeError, "Expected loadparm context");
230                         TALLOC_FREE(ret->mem_ctx);
231                         Py_DECREF(ret);
232                         return NULL;
233                 }
234
235                 credentials = cli_credentials_from_py_object(py_credentials);
236                 if (credentials == NULL) {
237                         PyErr_SetString(PyExc_TypeError, "Expected credentials");
238                         TALLOC_FREE(ret->mem_ctx);
239                         Py_DECREF(ret);
240                         return NULL;
241                 }
242                 status = dcerpc_pipe_connect(ret->mem_ctx, &ret->pipe, binding_string,
243                              table, credentials, event_ctx, lp_ctx);
244                 if (!NT_STATUS_IS_OK(status)) {
245                         PyErr_SetNTSTATUS(status);
246                         TALLOC_FREE(ret->mem_ctx);
247                         Py_DECREF(ret);
248                         return NULL;
249                 }
250
251                 /*
252                  * the event context is cached under the connection,
253                  * so let it be a child of it.
254                  */
255                 talloc_steal(ret->pipe->conn, event_ctx);
256         }
257
258         if (ret->pipe) {
259                 ret->pipe->conn->flags |= DCERPC_NDR_REF_ALLOC;
260                 ret->binding_handle = ret->pipe->binding_handle;
261         }
262
263         /* reset timeout for the handle */
264         if ((timeout != ((unsigned int)-1)) && (ret->binding_handle != NULL)) {
265                 dcerpc_binding_handle_set_timeout(ret->binding_handle, timeout);
266         }
267
268         return (PyObject *)ret;
269 }
270
271 static PyObject *py_dcerpc_run_function(dcerpc_InterfaceObject *iface,
272                                         const struct PyNdrRpcMethodDef *md,
273                                         PyObject *args, PyObject *kwargs)
274 {
275         TALLOC_CTX *mem_ctx;
276         NTSTATUS status;
277         void *r;
278         PyObject *result = Py_None;
279
280         if (md->pack_in_data == NULL || md->unpack_out_data == NULL) {
281                 PyErr_SetString(PyExc_NotImplementedError, "No marshalling code available yet");
282                 return NULL;
283         }
284
285         mem_ctx = talloc_new(NULL);
286         if (mem_ctx == NULL) {
287                 PyErr_NoMemory();
288                 return NULL;
289         }
290
291         r = talloc_zero_size(mem_ctx, md->table->calls[md->opnum].struct_size);
292         if (r == NULL) {
293                 PyErr_NoMemory();
294                 return NULL;
295         }
296
297         if (!md->pack_in_data(args, kwargs, r)) {
298                 talloc_free(mem_ctx);
299                 return NULL;
300         }
301
302         status = md->call(iface->binding_handle, mem_ctx, r);
303         if (!NT_STATUS_IS_OK(status)) {
304                 PyErr_SetDCERPCStatus(iface->pipe, status);
305                 talloc_free(mem_ctx);
306                 return NULL;
307         }
308
309         result = md->unpack_out_data(r);
310
311         talloc_free(mem_ctx);
312         return result;
313 }
314
315 static PyObject *py_dcerpc_call_wrapper(PyObject *self, PyObject *args, void *wrapped, PyObject *kwargs)
316 {       
317         dcerpc_InterfaceObject *iface = (dcerpc_InterfaceObject *)self;
318         const struct PyNdrRpcMethodDef *md = (const struct PyNdrRpcMethodDef *)wrapped;
319
320         return py_dcerpc_run_function(iface, md, args, kwargs);
321 }
322
323 bool PyInterface_AddNdrRpcMethods(PyTypeObject *ifacetype, const struct PyNdrRpcMethodDef *mds)
324 {
325         int i;
326         for (i = 0; mds[i].name; i++) {
327                 PyObject *ret;
328                 struct wrapperbase *wb = (struct wrapperbase *)calloc(sizeof(struct wrapperbase), 1);
329
330                 if (wb == NULL) {
331                         return false;
332                 }
333                 wb->name = discard_const_p(char, mds[i].name);
334                 wb->flags = PyWrapperFlag_KEYWORDS;
335                 wb->wrapper = (wrapperfunc)py_dcerpc_call_wrapper;
336                 wb->doc = discard_const_p(char, mds[i].doc);
337
338                 ret = PyDescr_NewWrapper(ifacetype, wb, discard_const_p(void, &mds[i]));
339
340                 PyDict_SetItemString(ifacetype->tp_dict, mds[i].name, 
341                                      (PyObject *)ret);
342                 Py_CLEAR(ret);
343         }
344
345         return true;
346 }
347
348 PyObject *py_dcerpc_syntax_init_helper(PyTypeObject *type, PyObject *args, PyObject *kwargs,
349                                        const struct ndr_syntax_id *syntax)
350 {
351         PyObject *ret;
352         struct ndr_syntax_id *obj;
353         const char *kwnames[] = { NULL };
354
355         if (!PyArg_ParseTupleAndKeywords(args, kwargs, ":abstract_syntax", discard_const_p(char *, kwnames))) {
356                 return NULL;
357         }
358
359         ret = pytalloc_new(struct ndr_syntax_id, type);
360         if (ret == NULL) {
361                 return NULL;
362         }
363
364         obj = pytalloc_get_type(ret, struct ndr_syntax_id);
365         *obj = *syntax;
366
367         return ret;
368 }
369
370 void PyErr_SetDCERPCStatus(struct dcerpc_pipe *p, NTSTATUS status)
371 {
372         if (p && NT_STATUS_EQUAL(status, NT_STATUS_NET_WRITE_FAULT)) {
373                 status = dcerpc_fault_to_nt_status(p->last_fault_code);
374         }
375         PyErr_SetNTSTATUS(status);
376 }
377
378
379 /*
380   take a NDR structure that has a type in a python module and return
381   it as a python object
382
383   r is the NDR structure pointer (a C structure)
384
385   r_ctx is the context that is a parent of r. It will be referenced by
386   the resulting python object
387
388   This MUST only be used by objects that are based on pytalloc_Object
389   otherwise the pytalloc_reference_ex() will fail.
390  */
391 PyObject *py_return_ndr_struct(const char *module_name, const char *type_name,
392                                TALLOC_CTX *r_ctx, void *r)
393 {
394         PyTypeObject *py_type;
395         PyObject *module;
396         PyObject *result = NULL;
397
398         if (r == NULL) {
399                 Py_RETURN_NONE;
400         }
401
402         module = PyImport_ImportModule(module_name);
403         if (module == NULL) {
404                 return NULL;
405         }
406
407         py_type = (PyTypeObject *)PyObject_GetAttrString(module, type_name);
408         if (py_type == NULL) {
409                 Py_DECREF(module);
410                 return NULL;
411         }
412
413         result = pytalloc_reference_ex(py_type, r_ctx, r);
414         Py_CLEAR(module);
415         Py_CLEAR(py_type);
416         return result;
417 }
418
419 PyObject *PyString_FromStringOrNULL(const char *str)
420 {
421         if (str == NULL) {
422                 Py_RETURN_NONE;
423         }
424         return PyStr_FromString(str);
425 }
426
427 const char **pyrpc_string_array_from_PyList(TALLOC_CTX *mem_ctx, PyObject *list,
428                                             const char *debug_name)
429 {
430         const char **ret = NULL;
431         Py_ssize_t i;
432
433         if (!PyList_Check(list)) {
434                 PyErr_Format(PyExc_TypeError, "%s is not a list", debug_name);
435                 return NULL;
436         }
437
438         ret = talloc_array(NULL, const char *, PyList_Size(list)+1);
439         if (ret == NULL) {
440                 PyErr_NoMemory();
441                 return NULL;
442         }
443
444         for (i = 0; i < PyList_Size(list); i++) {
445                 const char *str = NULL;
446                 Py_ssize_t size;
447                 PyObject *item = PyList_GetItem(list, i);
448                 if (!PyStr_Check(item)) {
449                         PyErr_Format(PyExc_TypeError, "%s should be strings",
450                                      debug_name);
451                         talloc_free(ret);
452                         return NULL;
453                 }
454                 str = PyStr_AsUTF8AndSize(item, &size);
455                 if (str == NULL) {
456                         talloc_free(ret);
457                         return NULL;
458                 }
459                 ret[i] = talloc_strndup(ret, str, size);
460                 if (ret[i] == NULL) {
461                         talloc_free(ret);
462                         PyErr_NoMemory();
463                         return NULL;
464                 }
465         }
466
467         ret[i] = NULL;
468         return ret;
469 }
470
471 PyObject *pyrpc_string_array_to_PyList(const char **string_array)
472 {
473         /*
474          * TODO
475          */
476         Py_RETURN_NONE;
477 }
478
479 PyObject *pyrpc_import_union(PyTypeObject *type, TALLOC_CTX *mem_ctx, int level,
480                              const void *in, const char *typename)
481 {
482         PyObject *mem_ctx_obj = NULL;
483         PyObject *in_obj = NULL;
484         PyObject *ret = NULL;
485
486         mem_ctx_obj = pytalloc_GenericObject_reference(mem_ctx);
487         if (mem_ctx_obj == NULL) {
488                 return NULL;
489         }
490
491         in_obj = pytalloc_GenericObject_reference_ex(mem_ctx, discard_const(in));
492         if (in_obj == NULL) {
493                 Py_XDECREF(mem_ctx_obj);
494                 return NULL;
495         }
496
497         ret = PyObject_CallMethod((PyObject *)type,
498                                   discard_const_p(char, "__import__"),
499                                   discard_const_p(char, "OiO"),
500                                   mem_ctx_obj, level, in_obj);
501         Py_XDECREF(mem_ctx_obj);
502         Py_XDECREF(in_obj);
503         if (ret == NULL) {
504                 return NULL;
505         }
506
507         return ret;
508 }
509
510 void *pyrpc_export_union(PyTypeObject *type, TALLOC_CTX *mem_ctx, int level,
511                          PyObject *in, const char *typename)
512 {
513         PyObject *mem_ctx_obj = NULL;
514         PyObject *ret_obj = NULL;
515         void *ret = NULL;
516
517         mem_ctx_obj = pytalloc_GenericObject_reference(mem_ctx);
518         if (mem_ctx_obj == NULL) {
519                 return NULL;
520         }
521
522         ret_obj = PyObject_CallMethod((PyObject *)type,
523                                       discard_const_p(char, "__export__"),
524                                       discard_const_p(char, "OiO"),
525                                       mem_ctx_obj, level, in);
526         Py_XDECREF(mem_ctx_obj);
527         if (ret_obj == NULL) {
528                 return NULL;
529         }
530
531         ret = _pytalloc_get_type(ret_obj, typename);
532         Py_XDECREF(ret_obj);
533         return ret;
534 }
535
536 PyObject *py_dcerpc_ndr_pointer_deref(PyTypeObject *type, PyObject *obj)
537 {
538         if (!PyObject_TypeCheck(obj, type)) {
539                 PyErr_Format(PyExc_TypeError,
540                              "Expected type '%s' but got type '%s'",
541                              (type)->tp_name, Py_TYPE(obj)->tp_name);
542                 return NULL;
543         }
544
545         return PyObject_GetAttrString(obj, discard_const_p(char, "value"));
546 }
547
548 PyObject *py_dcerpc_ndr_pointer_wrap(PyTypeObject *type, PyObject *obj)
549 {
550         PyObject *args = NULL;
551         PyObject *ret_obj = NULL;
552
553         args = PyTuple_New(1);
554         if (args == NULL) {
555                 return NULL;
556         }
557         Py_XINCREF(obj);
558         PyTuple_SetItem(args, 0, obj);
559
560         ret_obj = PyObject_Call((PyObject *)type, args, NULL);
561         Py_XDECREF(args);
562         return ret_obj;
563 }