pidl: Keep only a single copy of samba.dcerpc.base.ClientConnection.
[kamenim/samba.git] / source4 / lib / messaging / pymessaging.c
1 /* 
2    Unix SMB/CIFS implementation.
3    Copyright © Jelmer Vernooij <jelmer@samba.org> 2008
4
5    Based on the equivalent for EJS:
6    Copyright © Andrew Tridgell <tridge@samba.org> 2005
7    
8    This program is free software; you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 3 of the License, or
11    (at your option) any later version.
12    
13    This program is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17    
18    You should have received a copy of the GNU General Public License
19    along with this program.  If not, see <http://www.gnu.org/licenses/>.
20 */
21
22 #include <Python.h>
23 #include "includes.h"
24 #include "scripting/python/modules.h"
25 #include "libcli/util/pyerrors.h"
26 #include "librpc/rpc/pyrpc_util.h"
27 #include "librpc/ndr/libndr.h"
28 #include "lib/messaging/irpc.h"
29 #include "lib/messaging/messaging.h"
30 #include "lib/events/events.h"
31 #include "cluster/cluster.h"
32 #include "param/param.h"
33 #include "param/pyparam.h"
34
35 PyAPI_DATA(PyTypeObject) messaging_Type;
36 PyAPI_DATA(PyTypeObject) irpc_ClientConnectionType;
37
38 /* FIXME: This prototype should be in py_irpc.h, or shared otherwise */
39 extern const struct PyNdrRpcMethodDef py_ndr_irpc_methods[];
40
41 static bool server_id_from_py(PyObject *object, struct server_id *server_id)
42 {
43         if (!PyTuple_Check(object)) {
44                 PyErr_SetString(PyExc_ValueError, "Expected tuple");
45                 return false;
46         }
47
48         if (PyTuple_Size(object) == 3) {
49                 return PyArg_ParseTuple(object, "iii", &server_id->id, &server_id->id2, &server_id->node);
50         } else {
51                 int id, id2;
52                 if (!PyArg_ParseTuple(object, "ii", &id, &id2))
53                         return false;
54                 *server_id = cluster_id(id, id2);
55                 return true;
56         }
57 }
58
59 typedef struct {
60         PyObject_HEAD
61         TALLOC_CTX *mem_ctx;
62         struct messaging_context *msg_ctx;
63 } messaging_Object;
64
65 PyObject *py_messaging_connect(PyTypeObject *self, PyObject *args, PyObject *kwargs)
66 {
67         struct tevent_context *ev;
68         const char *kwnames[] = { "own_id", "messaging_path", NULL };
69         PyObject *own_id = Py_None;
70         const char *messaging_path = NULL;
71         messaging_Object *ret;
72
73         if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|Oz:connect", 
74                 discard_const_p(char *, kwnames), &own_id, &messaging_path)) {
75                 return NULL;
76         }
77
78         ret = PyObject_New(messaging_Object, &messaging_Type);
79         if (ret == NULL)
80                 return NULL;
81
82         ret->mem_ctx = talloc_new(NULL);
83
84         ev = s4_event_context_init(ret->mem_ctx);
85
86         if (messaging_path == NULL) {
87                 messaging_path = lpcfg_messaging_path(ret->mem_ctx,
88                                                                    py_default_loadparm_context(ret->mem_ctx));
89         } else {
90                 messaging_path = talloc_strdup(ret->mem_ctx, messaging_path);
91         }
92
93         if (own_id != Py_None) {
94                 struct server_id server_id;
95
96                 if (!server_id_from_py(own_id, &server_id)) 
97                         return NULL;
98
99                 ret->msg_ctx = messaging_init(ret->mem_ctx, 
100                                             messaging_path,
101                                             server_id,
102                                             ev);
103         } else {
104                 ret->msg_ctx = messaging_client_init(ret->mem_ctx, 
105                                             messaging_path,
106                                             ev);
107         }
108
109         if (ret->msg_ctx == NULL) {
110                 PyErr_SetString(PyExc_RuntimeError, "messaging_connect unable to create a messaging context");
111                 talloc_free(ret->mem_ctx);
112                 return NULL;
113         }
114
115         return (PyObject *)ret;
116 }
117
118 static void py_messaging_dealloc(PyObject *self)
119 {
120         messaging_Object *iface = (messaging_Object *)self;
121         talloc_free(iface->msg_ctx);
122         PyObject_Del(self);
123 }
124
125 static PyObject *py_messaging_send(PyObject *self, PyObject *args, PyObject *kwargs)
126 {
127         messaging_Object *iface = (messaging_Object *)self;
128         uint32_t msg_type;
129         DATA_BLOB data;
130         PyObject *target;
131         NTSTATUS status;
132         struct server_id server;
133         const char *kwnames[] = { "target", "msg_type", "data", NULL };
134         int length;
135
136         if (!PyArg_ParseTupleAndKeywords(args, kwargs, "Ois#:send", 
137                 discard_const_p(char *, kwnames), &target, &msg_type, &data.data, &length)) {
138
139                 return NULL;
140         }
141
142         data.length = length;
143
144         if (!server_id_from_py(target, &server)) 
145                 return NULL;
146
147         status = messaging_send(iface->msg_ctx, server, msg_type, &data);
148         if (NT_STATUS_IS_ERR(status)) {
149                 PyErr_SetNTSTATUS(status);
150                 return NULL;
151         }
152
153         Py_RETURN_NONE;
154 }
155
156 static void py_msg_callback_wrapper(struct messaging_context *msg, void *private_data,
157                                uint32_t msg_type, 
158                                struct server_id server_id, DATA_BLOB *data)
159 {
160         PyObject *callback = (PyObject *)private_data;
161
162         PyObject_CallFunction(callback, discard_const_p(char, "i(iii)s#"), msg_type, 
163                               server_id.id, server_id.id2, server_id.node, 
164                               data->data, data->length);
165 }
166
167 static PyObject *py_messaging_register(PyObject *self, PyObject *args, PyObject *kwargs)
168 {
169         messaging_Object *iface = (messaging_Object *)self;
170         int msg_type = -1;
171         PyObject *callback;
172         NTSTATUS status;
173         const char *kwnames[] = { "callback", "msg_type", NULL };
174         
175         if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O|i:register", 
176                 discard_const_p(char *, kwnames), &callback, &msg_type)) {
177                 return NULL;
178         }
179
180         Py_INCREF(callback);
181
182         if (msg_type == -1) {
183                 uint32_t msg_type32 = msg_type;
184                 status = messaging_register_tmp(iface->msg_ctx, callback,
185                                                 py_msg_callback_wrapper, &msg_type32);
186                 msg_type = msg_type32;
187         } else {
188                 status = messaging_register(iface->msg_ctx, callback,
189                                     msg_type, py_msg_callback_wrapper);
190         }
191         if (NT_STATUS_IS_ERR(status)) {
192                 PyErr_SetNTSTATUS(status);
193                 return NULL;
194         }
195
196         return PyLong_FromLong(msg_type);
197 }
198
199 static PyObject *py_messaging_deregister(PyObject *self, PyObject *args, PyObject *kwargs)
200 {
201         messaging_Object *iface = (messaging_Object *)self;
202         int msg_type = -1;
203         PyObject *callback;
204         const char *kwnames[] = { "callback", "msg_type", NULL };
205
206         if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O|i:deregister",
207                 discard_const_p(char *, kwnames), &callback, &msg_type)) {
208                 return NULL;
209         }
210
211         messaging_deregister(iface->msg_ctx, msg_type, callback);
212
213         Py_DECREF(callback);
214
215         Py_RETURN_NONE;
216 }
217
218 static PyObject *py_messaging_add_name(PyObject *self, PyObject *args, PyObject *kwargs)
219 {
220         messaging_Object *iface = (messaging_Object *)self;
221         NTSTATUS status;
222         char *name;
223         const char *kwnames[] = { "name", NULL };
224
225         if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s|:add_name", 
226                 discard_const_p(char *, kwnames), &name)) {
227                 return NULL;
228         }
229
230         status = irpc_add_name(iface->msg_ctx, name);
231         if (NT_STATUS_IS_ERR(status)) {
232                 PyErr_SetNTSTATUS(status);
233                 return NULL;
234         }
235
236         Py_RETURN_NONE;
237 }
238
239
240 static PyObject *py_messaging_remove_name(PyObject *self, PyObject *args, PyObject *kwargs)
241 {
242         messaging_Object *iface = (messaging_Object *)self;
243         char *name;
244         const char *kwnames[] = { "name", NULL };
245
246         if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s|:remove_name",
247                 discard_const_p(char *, kwnames), &name)) {
248                 return NULL;
249         }
250
251         irpc_remove_name(iface->msg_ctx, name);
252
253         Py_RETURN_NONE;
254 }
255
256 static PyMethodDef py_messaging_methods[] = {
257         { "send", (PyCFunction)py_messaging_send, METH_VARARGS|METH_KEYWORDS, 
258                 "S.send(target, msg_type, data) -> None\nSend a message" },
259         { "register", (PyCFunction)py_messaging_register, METH_VARARGS|METH_KEYWORDS,
260                 "S.register(callback, msg_type=None) -> msg_type\nRegister a message handler" },
261         { "deregister", (PyCFunction)py_messaging_deregister, METH_VARARGS|METH_KEYWORDS,
262                 "S.deregister(callback, msg_type) -> None\nDeregister a message handler" },
263         { "add_name", (PyCFunction)py_messaging_add_name, METH_VARARGS|METH_KEYWORDS, "S.add_name(name) -> None\nListen on another name" },
264         { "remove_name", (PyCFunction)py_messaging_remove_name, METH_VARARGS|METH_KEYWORDS, "S.remove_name(name) -> None\nStop listening on a name" },
265         { NULL, NULL, 0, NULL }
266 };
267
268 static PyObject *py_messaging_server_id(PyObject *obj, void *closure)
269 {
270         messaging_Object *iface = (messaging_Object *)obj;
271         struct server_id server_id = messaging_get_server_id(iface->msg_ctx);
272
273         return Py_BuildValue("(iii)", server_id.id, server_id.id2, 
274                              server_id.node);
275 }
276
277 static PyGetSetDef py_messaging_getset[] = {
278         { discard_const_p(char, "server_id"), py_messaging_server_id, NULL, 
279           discard_const_p(char, "local server id") },
280         { NULL },
281 };
282
283
284 PyTypeObject messaging_Type = {
285         PyObject_HEAD_INIT(NULL) 0,
286         .tp_name = "irpc.Messaging",
287         .tp_basicsize = sizeof(messaging_Object),
288         .tp_flags = Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE,
289         .tp_new = py_messaging_connect,
290         .tp_dealloc = py_messaging_dealloc,
291         .tp_methods = py_messaging_methods,
292         .tp_getset = py_messaging_getset,
293         .tp_doc = "Messaging(own_id=None, messaging_path=None)\n" \
294                   "Create a new object that can be used to communicate with the peers in the specified messaging path.\n" \
295                   "If no path is specified, the default path from smb.conf will be used."
296 };
297
298
299 /*
300   state of a irpc 'connection'
301 */
302 typedef struct {
303         PyObject_HEAD
304         TALLOC_CTX *mem_ctx;
305         const char *server_name;
306         struct server_id *dest_ids;
307         struct messaging_context *msg_ctx;
308 } irpc_ClientConnectionObject;
309
310 /*
311   setup a context for talking to a irpc server
312      example: 
313         status = irpc.connect("smb_server");
314 */
315
316 PyObject *py_irpc_connect(PyTypeObject *self, PyObject *args, PyObject *kwargs)
317 {
318         struct tevent_context *ev;
319         const char *kwnames[] = { "server", "own_id", "messaging_path", NULL };
320         char *server;
321         const char *messaging_path = NULL;
322         PyObject *own_id = Py_None;
323         irpc_ClientConnectionObject *ret;
324
325         if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s|Oz:connect", 
326                 discard_const_p(char *, kwnames), &server, &own_id, &messaging_path)) {
327                 return NULL;
328         }
329
330         ret = PyObject_New(irpc_ClientConnectionObject, &irpc_ClientConnectionType);
331         if (ret == NULL)
332                 return NULL;
333
334         ret->mem_ctx = talloc_new(NULL);
335
336         ret->server_name = server;
337
338         ev = s4_event_context_init(ret->mem_ctx);
339
340         if (messaging_path == NULL) {
341                 messaging_path = lpcfg_messaging_path(ret->mem_ctx,
342                                                                    py_default_loadparm_context(ret->mem_ctx));
343         } else {
344                 messaging_path = talloc_strdup(ret->mem_ctx, messaging_path);
345         }
346
347         if (own_id != Py_None) {
348                 struct server_id server_id;
349
350                 if (!server_id_from_py(own_id, &server_id)) 
351                         return NULL;
352
353                 ret->msg_ctx = messaging_init(ret->mem_ctx, 
354                                             messaging_path,
355                                             server_id,
356                                             ev);
357         } else {
358                 ret->msg_ctx = messaging_client_init(ret->mem_ctx, 
359                                             messaging_path,
360                                             ev);
361         }
362
363         if (ret->msg_ctx == NULL) {
364                 PyErr_SetString(PyExc_RuntimeError, "irpc_connect unable to create a messaging context");
365                 talloc_free(ret->mem_ctx);
366                 return NULL;
367         }
368
369         ret->dest_ids = irpc_servers_byname(ret->msg_ctx, ret->mem_ctx, ret->server_name);
370         if (ret->dest_ids == NULL || ret->dest_ids[0].id == 0) {
371                 talloc_free(ret->mem_ctx);
372                 PyErr_SetNTSTATUS(NT_STATUS_OBJECT_NAME_NOT_FOUND);
373                 return NULL;
374         } else {
375                 return (PyObject *)ret;
376         }
377 }
378
379 typedef struct {
380         PyObject_HEAD
381         TALLOC_CTX *mem_ctx;
382         struct irpc_request **reqs;
383         int count;
384         int current;
385         py_data_unpack_fn unpack_fn;
386 } irpc_ResultObject;
387
388         
389 static PyObject *irpc_result_next(irpc_ResultObject *iterator)
390 {
391         NTSTATUS status;
392
393         if (iterator->current >= iterator->count) {
394                 PyErr_SetString(PyExc_StopIteration, "No more results");
395                 return NULL;
396         }
397
398         status = irpc_call_recv(iterator->reqs[iterator->current]);
399         iterator->current++;
400         if (!NT_STATUS_IS_OK(status)) {
401                 PyErr_SetNTSTATUS(status);
402                 return NULL;
403         }
404
405         return iterator->unpack_fn(iterator->reqs[iterator->current-1]->r);
406 }
407
408 static PyObject *irpc_result_len(irpc_ResultObject *self)
409 {
410         return PyLong_FromLong(self->count);
411 }
412
413 static PyMethodDef irpc_result_methods[] = {
414         { "__len__", (PyCFunction)irpc_result_len, METH_NOARGS, 
415                 "Number of elements returned"},
416         { NULL }
417 };
418
419 static void irpc_result_dealloc(PyObject *self)
420 {
421         talloc_free(((irpc_ResultObject *)self)->mem_ctx);
422         PyObject_Del(self);
423 }
424
425 PyTypeObject irpc_ResultIteratorType = {
426         PyObject_HEAD_INIT(NULL) 0,
427         .tp_name = "irpc.ResultIterator",
428         .tp_basicsize = sizeof(irpc_ResultObject),
429         .tp_flags = Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE,
430         .tp_iternext = (iternextfunc)irpc_result_next,
431         .tp_iter = PyObject_SelfIter,
432         .tp_methods = irpc_result_methods,
433         .tp_dealloc = irpc_result_dealloc,
434 };
435
436 static PyObject *py_irpc_call(irpc_ClientConnectionObject *p, struct PyNdrRpcMethodDef *method_def, PyObject *args, PyObject *kwargs)
437 {
438         void *ptr;
439         struct irpc_request **reqs;
440         int i, count;
441         NTSTATUS status;
442         TALLOC_CTX *mem_ctx = talloc_new(NULL);
443         irpc_ResultObject *ret;
444
445         /* allocate the C structure */
446         ptr = talloc_zero_size(mem_ctx, method_def->table->calls[method_def->opnum].struct_size);
447         if (ptr == NULL) {
448                 status = NT_STATUS_NO_MEMORY;
449                 goto done;
450         }
451
452         /* convert the mpr object into a C structure */
453         if (!method_def->pack_in_data(args, kwargs, ptr)) {
454                 talloc_free(mem_ctx);
455                 return NULL;
456         }
457
458         for (count=0;p->dest_ids[count].id;count++) /* noop */ ;
459
460         /* we need to make a call per server */
461         reqs = talloc_array(mem_ctx, struct irpc_request *, count);
462         if (reqs == NULL) {
463                 status = NT_STATUS_NO_MEMORY;
464                 goto done;
465         }
466
467         /* make the actual calls */
468         for (i=0;i<count;i++) {
469                 reqs[i] = irpc_call_send(p->msg_ctx, p->dest_ids[i], 
470                                          method_def->table, method_def->opnum, ptr, ptr);
471                 if (reqs[i] == NULL) {
472                         status = NT_STATUS_NO_MEMORY;
473                         goto done;
474                 }
475                 talloc_steal(reqs, reqs[i]);
476         }
477
478         ret = PyObject_New(irpc_ResultObject, &irpc_ResultIteratorType);
479         ret->mem_ctx = mem_ctx;
480         ret->reqs = reqs;
481         ret->count = count;
482         ret->current = 0;
483         ret->unpack_fn = method_def->unpack_out_data;
484
485         return (PyObject *)ret;
486 done:
487         talloc_free(mem_ctx);
488         PyErr_SetNTSTATUS(status);
489         return NULL;
490 }
491
492 static PyObject *py_irpc_call_wrapper(PyObject *self, PyObject *args, void *wrapped, PyObject *kwargs)
493 {       
494         irpc_ClientConnectionObject *iface = (irpc_ClientConnectionObject *)self;
495         struct PyNdrRpcMethodDef *md = wrapped;
496
497         return py_irpc_call(iface, md, args, kwargs);
498 }
499
500 static void py_irpc_dealloc(PyObject *self)
501 {
502         irpc_ClientConnectionObject *iface = (irpc_ClientConnectionObject *)self;
503         talloc_free(iface->mem_ctx);
504         PyObject_Del(self);
505 }
506
507 PyTypeObject irpc_ClientConnectionType = {
508         PyObject_HEAD_INIT(NULL) 0,
509         .tp_name = "irpc.ClientConnection",
510         .tp_basicsize = sizeof(irpc_ClientConnectionObject),
511         .tp_flags = Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE,
512         .tp_new = py_irpc_connect,
513         .tp_dealloc = py_irpc_dealloc,
514         .tp_doc = "ClientConnection(server, own_id=None, messaging_path=None)\n" \
515                   "Create a new IRPC client connection to communicate with the servers in the specified path.\n" \
516                   "If no path is specified, the default path from smb.conf will be used."
517 };
518
519 static bool irpc_AddNdrRpcMethods(PyTypeObject *ifacetype, const struct PyNdrRpcMethodDef *mds)
520 {
521         int i;
522         for (i = 0; mds[i].name; i++) {
523                 PyObject *ret;
524                 struct wrapperbase *wb = calloc(sizeof(struct wrapperbase), 1);
525
526                 wb->name = discard_const_p(char, mds[i].name);
527                 wb->flags = PyWrapperFlag_KEYWORDS;
528                 wb->wrapper = (wrapperfunc)py_irpc_call_wrapper;
529                 wb->doc = discard_const_p(char, mds[i].doc);
530                 
531                 ret = PyDescr_NewWrapper(ifacetype, wb, discard_const_p(void, &mds[i]));
532
533                 PyDict_SetItemString(ifacetype->tp_dict, mds[i].name, 
534                                      (PyObject *)ret);
535         }
536
537         return true;
538 }
539
540 void initmessaging(void)
541 {
542         PyObject *mod;
543         PyObject *dep_irpc;
544
545         dep_irpc = PyImport_ImportModule("samba.dcerpc.irpc");
546         if (dep_irpc == NULL)
547                 return;
548
549         if (PyType_Ready(&irpc_ClientConnectionType) < 0)
550                 return;
551
552         if (PyType_Ready(&messaging_Type) < 0)
553                 return;
554
555         if (PyType_Ready(&irpc_ResultIteratorType) < 0) 
556                 return;
557
558         if (!irpc_AddNdrRpcMethods(&irpc_ClientConnectionType, py_ndr_irpc_methods))
559                 return;
560
561         mod = Py_InitModule3("messaging", NULL, "Internal RPC");
562         if (mod == NULL)
563                 return;
564
565         Py_INCREF((PyObject *)&irpc_ClientConnectionType);
566         PyModule_AddObject(mod, "ClientConnection", (PyObject *)&irpc_ClientConnectionType);
567
568         Py_INCREF((PyObject *)&messaging_Type);
569         PyModule_AddObject(mod, "Messaging", (PyObject *)&messaging_Type);
570 }