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