s4:lib/tevent: rename structs
[sfrench/samba-autobuild/.git] / source4 / librpc / rpc / pyrpc.c
1 /* 
2    Unix SMB/CIFS implementation.
3    Samba utility functions
4    Copyright (C) Jelmer Vernooij <jelmer@samba.org> 2008
5    
6    This program is free software; you can redistribute it and/or modify
7    it under the terms of the GNU General Public License as published by
8    the Free Software Foundation; either version 3 of the License, or
9    (at your option) any later version.
10    
11    This program is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14    GNU General Public License for more details.
15    
16    You should have received a copy of the GNU General Public License
17    along with this program.  If not, see <http://www.gnu.org/licenses/>.
18 */
19
20 #include "includes.h"
21 #include <Python.h>
22 #include <structmember.h>
23 #include "librpc/rpc/pyrpc.h"
24 #include "librpc/rpc/dcerpc.h"
25 #include "lib/events/events.h"
26 #include "param/pyparam.h"
27
28 static PyObject *py_dcerpc_run_function(dcerpc_InterfaceObject *iface, struct PyNdrRpcMethodDef *md, PyObject *args, PyObject *kwargs)
29 {
30         TALLOC_CTX *mem_ctx;
31         NTSTATUS status;
32         void *r;
33         PyObject *result = Py_None;
34
35         if (md->pack_in_data == NULL || md->unpack_out_data == NULL) {
36                 PyErr_SetString(PyExc_NotImplementedError, "No marshalling code available yet");
37                 return NULL;
38         }
39
40         mem_ctx = talloc_new(NULL);
41         if (mem_ctx == NULL)
42                 return NULL;
43
44         r = talloc_zero_size(mem_ctx, md->table->calls[md->opnum].struct_size);
45         if (r == NULL)
46                 return NULL;
47
48         if (!md->pack_in_data(args, kwargs, r)) {
49                 talloc_free(mem_ctx);
50                 return NULL;
51         }
52
53         status = md->call(iface->pipe, mem_ctx, r);
54         if (NT_STATUS_IS_ERR(status)) {
55                 PyErr_SetDCERPCStatus(iface->pipe, status);
56                 talloc_free(mem_ctx);
57                 return NULL;
58         }
59
60         result = md->unpack_out_data(r);
61
62         talloc_free(mem_ctx);
63         return result;
64 }
65
66 static PyObject *py_dcerpc_call_wrapper(PyObject *self, PyObject *args, void *wrapped, PyObject *kwargs)
67 {       
68         dcerpc_InterfaceObject *iface = (dcerpc_InterfaceObject *)self;
69         struct PyNdrRpcMethodDef *md = wrapped;
70
71         return py_dcerpc_run_function(iface, md, args, kwargs);
72 }
73
74
75 bool PyInterface_AddNdrRpcMethods(PyTypeObject *ifacetype, const struct PyNdrRpcMethodDef *mds)
76 {
77         int i;
78         for (i = 0; mds[i].name; i++) {
79                 PyObject *ret;
80                 struct wrapperbase *wb = calloc(sizeof(struct wrapperbase), 1);
81
82                 wb->name = discard_const_p(char, mds[i].name);
83                 wb->flags = PyWrapperFlag_KEYWORDS;
84                 wb->wrapper = (wrapperfunc)py_dcerpc_call_wrapper;
85                 wb->doc = discard_const_p(char, mds[i].doc);
86                 
87                 ret = PyDescr_NewWrapper(ifacetype, wb, discard_const_p(void, &mds[i]));
88
89                 PyDict_SetItemString(ifacetype->tp_dict, mds[i].name, 
90                                      (PyObject *)ret);
91         }
92
93         return true;
94 }
95
96 static bool PyString_AsGUID(PyObject *object, struct GUID *uuid)
97 {
98         NTSTATUS status;
99         status = GUID_from_string(PyString_AsString(object), uuid);
100         if (NT_STATUS_IS_ERR(status)) {
101                 PyErr_SetNTSTATUS(status);
102                 return false;
103         }
104         return true;
105 }
106
107 static bool ndr_syntax_from_py_object(PyObject *object, struct ndr_syntax_id *syntax_id)
108 {
109         ZERO_STRUCTP(syntax_id);
110
111         if (PyString_Check(object)) {
112                 return PyString_AsGUID(object, &syntax_id->uuid);
113         } else if (PyTuple_Check(object)) {
114                 if (PyTuple_Size(object) < 1 || PyTuple_Size(object) > 2) {
115                         PyErr_SetString(PyExc_ValueError, "Syntax ID tuple has invalid size");
116                         return false;
117                 }
118
119                 if (!PyString_Check(PyTuple_GetItem(object, 0))) {
120                         PyErr_SetString(PyExc_ValueError, "Expected GUID as first element in tuple");
121                         return false;
122                 }
123
124                 if (!PyString_AsGUID(PyTuple_GetItem(object, 0), &syntax_id->uuid)) 
125                         return false;
126
127                 if (!PyInt_Check(PyTuple_GetItem(object, 1))) {
128                         PyErr_SetString(PyExc_ValueError, "Expected version as second element in tuple");
129                         return false;
130                 }
131
132                 syntax_id->if_version = PyInt_AsLong(PyTuple_GetItem(object, 1));
133                 return true;
134         }
135
136         PyErr_SetString(PyExc_TypeError, "Expected UUID or syntax id tuple");
137         return false;
138 }       
139
140 static PyObject *py_iface_server_name(PyObject *obj, void *closure)
141 {
142         const char *server_name;
143         dcerpc_InterfaceObject *iface = (dcerpc_InterfaceObject *)obj;
144         
145         server_name = dcerpc_server_name(iface->pipe);
146         if (server_name == NULL)
147                 return Py_None;
148
149         return PyString_FromString(server_name);
150 }
151
152 static PyObject *py_ndr_syntax_id(struct ndr_syntax_id *syntax_id)
153 {
154         PyObject *ret;
155         char *uuid_str;
156
157         uuid_str = GUID_string(NULL, &syntax_id->uuid);
158         if (uuid_str == NULL)
159                 return NULL;
160
161         ret = Py_BuildValue("(s,i)", uuid_str, syntax_id->if_version);
162
163         talloc_free(uuid_str);
164
165         return ret;
166 }
167
168 static PyObject *py_iface_abstract_syntax(PyObject *obj, void *closure)
169 {
170         dcerpc_InterfaceObject *iface = (dcerpc_InterfaceObject *)obj;
171
172         return py_ndr_syntax_id(&iface->pipe->syntax);
173 }
174
175 static PyObject *py_iface_transfer_syntax(PyObject *obj, void *closure)
176 {
177         dcerpc_InterfaceObject *iface = (dcerpc_InterfaceObject *)obj;
178
179         return py_ndr_syntax_id(&iface->pipe->transfer_syntax);
180 }
181
182 static PyGetSetDef dcerpc_interface_getsetters[] = {
183         { discard_const_p(char, "server_name"), py_iface_server_name, NULL,
184           discard_const_p(char, "name of the server, if connected over SMB") },
185         { discard_const_p(char, "abstract_syntax"), py_iface_abstract_syntax, NULL, 
186           discard_const_p(char, "syntax id of the abstract syntax") },
187         { discard_const_p(char, "transfer_syntax"), py_iface_transfer_syntax, NULL, 
188           discard_const_p(char, "syntax id of the transfersyntax") },
189         { NULL }
190 };
191
192 static PyMemberDef dcerpc_interface_members[] = {
193         { discard_const_p(char, "request_timeout"), T_INT, 
194           offsetof(struct dcerpc_pipe, request_timeout), 0,
195           discard_const_p(char, "request timeout, in seconds") },
196         { NULL }
197 };
198
199 void PyErr_SetDCERPCStatus(struct dcerpc_pipe *p, NTSTATUS status)
200 {
201         if (p != NULL && NT_STATUS_EQUAL(status, NT_STATUS_NET_WRITE_FAULT)) {
202                 const char *errstr = dcerpc_errstr(NULL, p->last_fault_code);
203                 PyErr_SetObject(PyExc_RuntimeError, 
204                         Py_BuildValue("(i,s)", p->last_fault_code,
205                                       errstr));
206         } else {
207                 PyErr_SetNTSTATUS(status);
208         }
209 }
210
211 static PyObject *py_iface_request(PyObject *self, PyObject *args, PyObject *kwargs)
212 {
213         dcerpc_InterfaceObject *iface = (dcerpc_InterfaceObject *)self;
214         int opnum;
215         DATA_BLOB data_in, data_out;
216         NTSTATUS status;
217         char *in_data;
218         int in_length;
219         PyObject *ret;
220         PyObject *object = NULL;
221         struct GUID object_guid;
222         TALLOC_CTX *mem_ctx = talloc_new(NULL);
223         const char *kwnames[] = { "opnum", "data", "object", NULL };
224
225         if (!PyArg_ParseTupleAndKeywords(args, kwargs, "is#|O:request", 
226                 discard_const_p(char *, kwnames), &opnum, &in_data, &in_length, &object)) {
227                 return NULL;
228         }
229
230         data_in.data = (uint8_t *)talloc_memdup(mem_ctx, in_data, in_length);
231         data_in.length = in_length;
232
233         ZERO_STRUCT(data_out);
234
235         if (object != NULL && !PyString_AsGUID(object, &object_guid)) {
236                 return NULL;
237         }
238
239         status = dcerpc_request(iface->pipe, object?&object_guid:NULL,
240                                 opnum, false, mem_ctx, &data_in, &data_out);
241
242         if (NT_STATUS_IS_ERR(status)) {
243                 PyErr_SetDCERPCStatus(iface->pipe, status);
244                 talloc_free(mem_ctx);
245                 return NULL;
246         }
247
248         ret = PyString_FromStringAndSize((char *)data_out.data, data_out.length);
249
250         talloc_free(mem_ctx);
251         return ret;
252 }
253
254 static PyObject *py_iface_alter_context(PyObject *self, PyObject *args, PyObject *kwargs)
255 {
256         dcerpc_InterfaceObject *iface = (dcerpc_InterfaceObject *)self;
257         NTSTATUS status;
258         const char *kwnames[] = { "abstract_syntax", "transfer_syntax", NULL };
259         PyObject *py_abstract_syntax = Py_None, *py_transfer_syntax = Py_None;
260         struct ndr_syntax_id abstract_syntax, transfer_syntax;
261
262         if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O|O:alter_context", 
263                 discard_const_p(char *, kwnames), &py_abstract_syntax,
264                 &py_transfer_syntax)) {
265                 return NULL;
266         }
267
268         if (!ndr_syntax_from_py_object(py_abstract_syntax, &abstract_syntax))
269                 return NULL;
270
271         if (py_transfer_syntax == Py_None) {
272                 transfer_syntax = ndr_transfer_syntax;
273         } else {
274                 if (!ndr_syntax_from_py_object(py_transfer_syntax, 
275                                                &transfer_syntax))
276                         return NULL;
277         }
278
279         status = dcerpc_alter_context(iface->pipe, iface->pipe, &abstract_syntax, 
280                                       &transfer_syntax);
281
282         if (NT_STATUS_IS_ERR(status)) {
283                 PyErr_SetDCERPCStatus(iface->pipe, status);
284                 return NULL;
285         }
286
287         return Py_None;
288 }
289
290 PyObject *py_dcerpc_interface_init_helper(PyTypeObject *type, PyObject *args, PyObject *kwargs, const struct ndr_interface_table *table)
291 {
292         dcerpc_InterfaceObject *ret;
293         const char *binding_string;
294         struct cli_credentials *credentials;
295         struct loadparm_context *lp_ctx = NULL;
296         PyObject *py_lp_ctx = Py_None, *py_credentials = Py_None, *py_basis = Py_None;
297         TALLOC_CTX *mem_ctx = NULL;
298         struct tevent_context *event_ctx;
299         NTSTATUS status;
300
301         const char *kwnames[] = {
302                 "binding", "lp_ctx", "credentials", "basis_connection", NULL
303         };
304         extern struct cli_credentials *cli_credentials_from_py_object(PyObject *py_obj);
305
306         if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s|OOO:samr", discard_const_p(char *, kwnames), &binding_string, &py_lp_ctx, &py_credentials, &py_basis)) {
307                 return NULL;
308         }
309
310         lp_ctx = lp_from_py_object(py_lp_ctx);
311         if (lp_ctx == NULL) {
312                 PyErr_SetString(PyExc_TypeError, "Expected loadparm context");
313                 return NULL;
314         }
315
316         status = dcerpc_init(lp_ctx);
317         if (!NT_STATUS_IS_OK(status)) {
318                 PyErr_SetNTSTATUS(status);
319                 return NULL;
320         }
321         credentials = cli_credentials_from_py_object(py_credentials);
322         if (credentials == NULL) {
323                 PyErr_SetString(PyExc_TypeError, "Expected credentials");
324                 return NULL;
325         }
326         ret = PyObject_New(dcerpc_InterfaceObject, type);
327
328         event_ctx = event_context_init(mem_ctx);
329
330         if (py_basis != Py_None) {
331                 struct dcerpc_pipe *base_pipe;
332
333                 if (!PyObject_TypeCheck(py_basis, &dcerpc_InterfaceType)) {
334                         PyErr_SetString(PyExc_ValueError, "basis_connection must be a DCE/RPC connection");
335                         talloc_free(mem_ctx);
336                         return NULL;
337                 }
338
339                 base_pipe = ((dcerpc_InterfaceObject *)py_basis)->pipe;
340
341                 status = dcerpc_secondary_context(base_pipe, &ret->pipe, table);
342         } else {
343                 status = dcerpc_pipe_connect(NULL, &ret->pipe, binding_string, 
344                              table, credentials, event_ctx, lp_ctx);
345         }
346         if (NT_STATUS_IS_ERR(status)) {
347                 PyErr_SetNTSTATUS(status);
348                 talloc_free(mem_ctx);
349                 return NULL;
350         }
351
352         ret->pipe->conn->flags |= DCERPC_NDR_REF_ALLOC;
353         return (PyObject *)ret;
354 }
355
356 static PyMethodDef dcerpc_interface_methods[] = {
357         { "request", (PyCFunction)py_iface_request, METH_VARARGS|METH_KEYWORDS, "S.request(opnum, data, object=None) -> data\nMake a raw request" },
358         { "alter_context", (PyCFunction)py_iface_alter_context, METH_VARARGS|METH_KEYWORDS, "S.alter_context(syntax)\nChange to a different interface" },
359         { NULL, NULL, 0, NULL },
360 };
361
362
363 static void dcerpc_interface_dealloc(PyObject* self)
364 {
365         dcerpc_InterfaceObject *interface = (dcerpc_InterfaceObject *)self;
366         talloc_free(interface->pipe);
367         PyObject_Del(self);
368 }
369
370 static PyObject *dcerpc_interface_new(PyTypeObject *self, PyObject *args, PyObject *kwargs)
371 {
372         dcerpc_InterfaceObject *ret;
373         const char *binding_string;
374         struct cli_credentials *credentials;
375         struct loadparm_context *lp_ctx = NULL;
376         PyObject *py_lp_ctx = Py_None, *py_credentials = Py_None;
377         TALLOC_CTX *mem_ctx = NULL;
378         struct tevent_context *event_ctx;
379         NTSTATUS status;
380
381         PyObject *syntax, *py_basis = Py_None;
382         const char *kwnames[] = {
383                 "binding", "syntax", "lp_ctx", "credentials", "basis_connection", NULL
384         };
385         extern struct cli_credentials *cli_credentials_from_py_object(PyObject *py_obj);
386         struct ndr_interface_table *table;
387
388         if (!PyArg_ParseTupleAndKeywords(args, kwargs, "sO|OOO:connect", discard_const_p(char *, kwnames), &binding_string, &syntax, &py_lp_ctx, &py_credentials, &py_basis)) {
389                 return NULL;
390         }
391
392         lp_ctx = lp_from_py_object(py_lp_ctx);
393         if (lp_ctx == NULL) {
394                 PyErr_SetString(PyExc_TypeError, "Expected loadparm context");
395                 return NULL;
396         }
397
398         credentials = cli_credentials_from_py_object(py_credentials);
399         if (credentials == NULL) {
400                 PyErr_SetString(PyExc_TypeError, "Expected credentials");
401                 return NULL;
402         }
403         ret = PyObject_New(dcerpc_InterfaceObject, &dcerpc_InterfaceType);
404
405         event_ctx = s4_event_context_init(mem_ctx);
406
407         /* Create a dummy interface table struct. TODO: In the future, we should rather just allow 
408          * connecting without requiring an interface table.
409          */
410
411         table = talloc_zero(mem_ctx, struct ndr_interface_table);
412
413         if (table == NULL) {
414                 PyErr_SetString(PyExc_MemoryError, "Allocating interface table");
415                 return NULL;
416         }
417
418         if (!ndr_syntax_from_py_object(syntax, &table->syntax_id)) {
419                 return NULL;
420         }
421
422         ret->pipe = NULL;
423
424         if (py_basis != Py_None) {
425                 struct dcerpc_pipe *base_pipe;
426
427                 if (!PyObject_TypeCheck(py_basis, &dcerpc_InterfaceType)) {
428                         PyErr_SetString(PyExc_ValueError, "basis_connection must be a DCE/RPC connection");
429                         talloc_free(mem_ctx);
430                         return NULL;
431                 }
432
433                 base_pipe = ((dcerpc_InterfaceObject *)py_basis)->pipe;
434
435                 status = dcerpc_secondary_context(base_pipe, &ret->pipe, 
436                                      table);
437                 ret->pipe = talloc_steal(NULL, ret->pipe);
438         } else {
439                 status = dcerpc_pipe_connect(NULL, &ret->pipe, binding_string, 
440                              table, credentials, event_ctx, lp_ctx);
441         }
442
443         if (NT_STATUS_IS_ERR(status)) {
444                 PyErr_SetDCERPCStatus(ret->pipe, status);
445                 talloc_free(mem_ctx);
446                 return NULL;
447         }
448         ret->pipe->conn->flags |= DCERPC_NDR_REF_ALLOC;
449         return (PyObject *)ret;
450 }
451
452 PyTypeObject dcerpc_InterfaceType = {
453         PyObject_HEAD_INIT(NULL) 0,
454         .tp_name = "dcerpc.ClientConnection",
455         .tp_basicsize = sizeof(dcerpc_InterfaceObject),
456         .tp_dealloc = dcerpc_interface_dealloc,
457         .tp_getset = dcerpc_interface_getsetters,
458         .tp_members = dcerpc_interface_members,
459         .tp_methods = dcerpc_interface_methods,
460         .tp_doc = "ClientConnection(binding, syntax, lp_ctx=None, credentials=None) -> connection\n"
461 "\n"
462 "binding should be a DCE/RPC binding string (for example: ncacn_ip_tcp:127.0.0.1)\n"
463 "syntax should be a tuple with a GUID and version number of an interface\n"
464 "lp_ctx should be a path to a smb.conf file or a param.LoadParm object\n"
465 "credentials should be a credentials.Credentials object.\n\n",
466         .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
467         .tp_new = dcerpc_interface_new,
468 };
469
470 void initbase(void)
471 {
472         PyObject *m;
473
474         if (PyType_Ready(&dcerpc_InterfaceType) < 0)
475                 return;
476
477         m = Py_InitModule3("base", NULL, "DCE/RPC protocol implementation");
478         if (m == NULL)
479                 return;
480
481         Py_INCREF((PyObject *)&dcerpc_InterfaceType);
482         PyModule_AddObject(m, "ClientConnection", (PyObject *)&dcerpc_InterfaceType);
483 }