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