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