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