Remove use of global loadparm in python modules.
[kai/samba-autobuild/.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 #include "librpc/gen_ndr/py_irpc.h"
33
34 PyAPI_DATA(PyTypeObject) messaging_Type;
35 PyAPI_DATA(PyTypeObject) irpc_ClientConnectionType;
36
37 /* FIXME: This prototype should be in param/pyparam.h */
38 struct loadparm_context *py_default_loadparm_context(TALLOC_CTX *mem_ctx);
39
40 static bool server_id_from_py(PyObject *object, struct server_id *server_id)
41 {
42         if (!PyTuple_Check(object)) {
43                 PyErr_SetString(PyExc_ValueError, "Expected tuple");
44                 return false;
45         }
46
47         if (PyTuple_Size(object) == 3) {
48                 return PyArg_ParseTuple(object, "iii", &server_id->id, &server_id->id2, &server_id->node);
49         } else {
50                 int id, id2;
51                 if (!PyArg_ParseTuple(object, "ii", &id, &id2))
52                         return false;
53                 *server_id = cluster_id(id, id2);
54                 return true;
55         }
56 }
57
58 typedef struct {
59         PyObject_HEAD
60         TALLOC_CTX *mem_ctx;
61         struct messaging_context *msg_ctx;
62 } messaging_Object;
63
64 PyObject *py_messaging_connect(PyTypeObject *self, PyObject *args, PyObject *kwargs)
65 {
66         struct event_context *ev;
67         const char *kwnames[] = { "own_id", "messaging_path", NULL };
68         PyObject *own_id = Py_None;
69         const char *messaging_path = NULL;
70         messaging_Object *ret;
71
72         if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|Oz:connect", 
73                 discard_const_p(char *, kwnames), &own_id, &messaging_path)) {
74                 return NULL;
75         }
76
77         ret = PyObject_New(messaging_Object, &messaging_Type);
78         if (ret == NULL)
79                 return NULL;
80
81         ret->mem_ctx = talloc_new(NULL);
82
83         ev = s4_event_context_init(ret->mem_ctx);
84
85         if (messaging_path == NULL) {
86                 messaging_path = lp_messaging_path(ret->mem_ctx, 
87                                                                    py_default_loadparm_context(ret->mem_ctx));
88         } else {
89                 messaging_path = talloc_strdup(ret->mem_ctx, messaging_path);
90         }
91
92         if (own_id != Py_None) {
93                 struct server_id server_id;
94
95                 if (!server_id_from_py(own_id, &server_id)) 
96                         return NULL;
97
98                 ret->msg_ctx = messaging_init(ret->mem_ctx, 
99                                             messaging_path,
100                                             server_id,
101                                         py_iconv_convenience(ret->mem_ctx),
102                                             ev);
103         } else {
104                 ret->msg_ctx = messaging_client_init(ret->mem_ctx, 
105                                             messaging_path,
106                                         py_iconv_convenience(ret->mem_ctx),
107                                             ev);
108         }
109
110         if (ret->msg_ctx == NULL) {
111                 PyErr_SetString(PyExc_RuntimeError, "messaging_connect unable to create a messaging context");
112                 talloc_free(ret->mem_ctx);
113                 return NULL;
114         }
115
116         return (PyObject *)ret;
117 }
118
119 static void py_messaging_dealloc(PyObject *self)
120 {
121         messaging_Object *iface = (messaging_Object *)self;
122         talloc_free(iface->msg_ctx);
123         PyObject_Del(self);
124 }
125
126 static PyObject *py_messaging_send(PyObject *self, PyObject *args, PyObject *kwargs)
127 {
128         messaging_Object *iface = (messaging_Object *)self;
129         uint32_t msg_type;
130         DATA_BLOB data;
131         PyObject *target;
132         NTSTATUS status;
133         struct server_id server;
134         const char *kwnames[] = { "target", "msg_type", "data", NULL };
135         int length;
136
137         if (!PyArg_ParseTupleAndKeywords(args, kwargs, "Ois#|:send", 
138                 discard_const_p(char *, kwnames), &target, &msg_type, &data.data, &length)) {
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         return Py_None;
154 }
155
156 static void py_msg_callback_wrapper(struct messaging_context *msg, void *private, 
157                                uint32_t msg_type, 
158                                struct server_id server_id, DATA_BLOB *data)
159 {
160         PyObject *callback = (PyObject *)private;
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:send", 
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:send", 
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         return Py_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|:send", 
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         return Py_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|:send", 
247                 discard_const_p(char *, kwnames), &name)) {
248                 return NULL;
249         }
250
251         irpc_remove_name(iface->msg_ctx, name);
252
253         return Py_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         const char *server_name;
305         struct server_id *dest_ids;
306         struct messaging_context *msg_ctx;
307         TALLOC_CTX *mem_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 event_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 = lp_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                                         py_iconv_convenience(ret->mem_ctx),
357                                             ev);
358         } else {
359                 ret->msg_ctx = messaging_client_init(ret->mem_ctx, 
360                                             messaging_path,
361                                         py_iconv_convenience(ret->mem_ctx),
362                                             ev);
363         }
364
365         if (ret->msg_ctx == NULL) {
366                 PyErr_SetString(PyExc_RuntimeError, "irpc_connect unable to create a messaging context");
367                 talloc_free(ret->mem_ctx);
368                 return NULL;
369         }
370
371         ret->dest_ids = irpc_servers_byname(ret->msg_ctx, ret->mem_ctx, ret->server_name);
372         if (ret->dest_ids == NULL || ret->dest_ids[0].id == 0) {
373                 talloc_free(ret->mem_ctx);
374                 PyErr_SetNTSTATUS(NT_STATUS_OBJECT_NAME_NOT_FOUND);
375                 return NULL;
376         } else {
377                 return (PyObject *)ret;
378         }
379 }
380
381 typedef struct {
382         PyObject_HEAD
383         struct irpc_request **reqs;
384         int count;
385         int current;
386         TALLOC_CTX *mem_ctx;
387         py_data_unpack_fn unpack_fn;
388 } irpc_ResultObject;
389
390         
391 static PyObject *irpc_result_next(irpc_ResultObject *iterator)
392 {
393         NTSTATUS status;
394
395         if (iterator->current >= iterator->count) {
396                 PyErr_SetString(PyExc_StopIteration, "No more results");
397                 return NULL;
398         }
399
400         status = irpc_call_recv(iterator->reqs[iterator->current]);
401         iterator->current++;
402         if (!NT_STATUS_IS_OK(status)) {
403                 PyErr_SetNTSTATUS(status);
404                 return NULL;
405         }
406
407         return iterator->unpack_fn(iterator->reqs[iterator->current-1]->r);
408 }
409
410 static PyObject *irpc_result_len(irpc_ResultObject *self)
411 {
412         return PyLong_FromLong(self->count);
413 }
414
415 static PyMethodDef irpc_result_methods[] = {
416         { "__len__", (PyCFunction)irpc_result_len, METH_NOARGS, 
417                 "Number of elements returned"},
418         { NULL }
419 };
420
421 static void irpc_result_dealloc(PyObject *self)
422 {
423         talloc_free(((irpc_ResultObject *)self)->mem_ctx);
424         PyObject_Del(self);
425 }
426
427 PyTypeObject irpc_ResultIteratorType = {
428         PyObject_HEAD_INIT(NULL) 0,
429         .tp_name = "irpc.ResultIterator",
430         .tp_basicsize = sizeof(irpc_ResultObject),
431         .tp_flags = Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE,
432         .tp_iternext = (iternextfunc)irpc_result_next,
433         .tp_iter = PyObject_SelfIter,
434         .tp_methods = irpc_result_methods,
435         .tp_dealloc = irpc_result_dealloc,
436 };
437
438 static PyObject *py_irpc_call(irpc_ClientConnectionObject *p, struct PyNdrRpcMethodDef *method_def, PyObject *args, PyObject *kwargs)
439 {
440         void *ptr;
441         struct irpc_request **reqs;
442         int i, count;
443         NTSTATUS status;
444         TALLOC_CTX *mem_ctx = talloc_new(NULL);
445         irpc_ResultObject *ret;
446
447         /* allocate the C structure */
448         ptr = talloc_zero_size(mem_ctx, method_def->table->calls[method_def->opnum].struct_size);
449         if (ptr == NULL) {
450                 status = NT_STATUS_NO_MEMORY;
451                 goto done;
452         }
453
454         /* convert the mpr object into a C structure */
455         if (!method_def->pack_in_data(args, kwargs, ptr)) {
456                 talloc_free(mem_ctx);
457                 return NULL;
458         }
459
460         for (count=0;p->dest_ids[count].id;count++) /* noop */ ;
461
462         /* we need to make a call per server */
463         reqs = talloc_array(mem_ctx, struct irpc_request *, count);
464         if (reqs == NULL) {
465                 status = NT_STATUS_NO_MEMORY;
466                 goto done;
467         }
468
469         /* make the actual calls */
470         for (i=0;i<count;i++) {
471                 reqs[i] = irpc_call_send(p->msg_ctx, p->dest_ids[i], 
472                                          method_def->table, method_def->opnum, ptr, ptr);
473                 if (reqs[i] == NULL) {
474                         status = NT_STATUS_NO_MEMORY;
475                         goto done;
476                 }
477                 talloc_steal(reqs, reqs[i]);
478         }
479
480         ret = PyObject_New(irpc_ResultObject, &irpc_ResultIteratorType);
481         ret->mem_ctx = mem_ctx;
482         ret->reqs = reqs;
483         ret->count = count;
484         ret->current = 0;
485         ret->unpack_fn = method_def->unpack_out_data;
486
487         return (PyObject *)ret;
488 done:
489         talloc_free(mem_ctx);
490         PyErr_SetNTSTATUS(status);
491         return NULL;
492 }
493
494 static PyObject *py_irpc_call_wrapper(PyObject *self, PyObject *args, void *wrapped, PyObject *kwargs)
495 {       
496         irpc_ClientConnectionObject *iface = (irpc_ClientConnectionObject *)self;
497         struct PyNdrRpcMethodDef *md = wrapped;
498
499         return py_irpc_call(iface, md, args, kwargs);
500 }
501
502 static void py_irpc_dealloc(PyObject *self)
503 {
504         irpc_ClientConnectionObject *iface = (irpc_ClientConnectionObject *)self;
505         talloc_free(iface->mem_ctx);
506         PyObject_Del(self);
507 }
508
509 PyTypeObject irpc_ClientConnectionType = {
510         PyObject_HEAD_INIT(NULL) 0,
511         .tp_name = "irpc.ClientConnection",
512         .tp_basicsize = sizeof(irpc_ClientConnectionObject),
513         .tp_flags = Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE,
514         .tp_new = py_irpc_connect,
515         .tp_dealloc = py_irpc_dealloc,
516         .tp_doc = "ClientConnection(server, own_id=None, messaging_path=None)\n" \
517                   "Create a new IRPC client connection to communicate with the servers in the specified path.\n" \
518                   "If no path is specified, the default path from smb.conf will be used."
519 };
520
521 static bool irpc_AddNdrRpcMethods(PyTypeObject *ifacetype, const struct PyNdrRpcMethodDef *mds)
522 {
523         int i;
524         for (i = 0; mds[i].name; i++) {
525                 PyObject *ret;
526                 struct wrapperbase *wb = calloc(sizeof(struct wrapperbase), 1);
527
528                 wb->name = discard_const_p(char, mds[i].name);
529                 wb->flags = PyWrapperFlag_KEYWORDS;
530                 wb->wrapper = (wrapperfunc)py_irpc_call_wrapper;
531                 wb->doc = discard_const_p(char, mds[i].doc);
532                 
533                 ret = PyDescr_NewWrapper(ifacetype, wb, discard_const_p(void, &mds[i]));
534
535                 PyDict_SetItemString(ifacetype->tp_dict, mds[i].name, 
536                                      (PyObject *)ret);
537         }
538
539         return true;
540 }
541
542 void initmessaging(void)
543 {
544         extern void initirpc(void);
545         PyObject *mod;
546
547         if (PyType_Ready(&irpc_ClientConnectionType) < 0)
548                 return;
549
550         if (PyType_Ready(&messaging_Type) < 0)
551                 return;
552
553         if (PyType_Ready(&irpc_ResultIteratorType) < 0) 
554                 return;
555
556         if (!irpc_AddNdrRpcMethods(&irpc_ClientConnectionType, py_ndr_irpc_methods))
557                 return;
558
559         mod = Py_InitModule3("messaging", NULL, "Internal RPC");
560         if (mod == NULL)
561                 return;
562
563         initirpc();
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 }