Add wrapper for DBusServer.
[dbus-python-phuang.git] / _dbus_bindings / conn-methods.c
blob81c451440858bb3b0366fdab9696ffbb118b8208
1 /* Implementation of normal Python-accessible methods on the _dbus_bindings
2 * Connection type; separated out to keep the file size manageable.
4 * Copyright (C) 2006 Collabora Ltd. <http://www.collabora.co.uk/>
6 * Permission is hereby granted, free of charge, to any person
7 * obtaining a copy of this software and associated documentation
8 * files (the "Software"), to deal in the Software without
9 * restriction, including without limitation the rights to use, copy,
10 * modify, merge, publish, distribute, sublicense, and/or sell copies
11 * of the Software, and to permit persons to whom the Software is
12 * furnished to do so, subject to the following conditions:
14 * The above copyright notice and this permission notice shall be
15 * included in all copies or substantial portions of the Software.
17 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
18 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
19 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
20 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
21 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
22 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
24 * DEALINGS IN THE SOFTWARE.
27 #include "dbus_bindings-internal.h"
28 #include "conn-internal.h"
30 static void
31 _object_path_unregister(DBusConnection *conn, void *user_data)
33 PyGILState_STATE gil = PyGILState_Ensure();
34 PyObject *tuple = NULL;
35 Connection *conn_obj = NULL;
36 PyObject *callable;
38 conn_obj = (Connection *)DBusPyConnection_ExistingFromDBusConnection(conn);
39 if (!conn_obj) goto out;
40 TRACE(conn_obj);
42 DBG("Connection at %p unregistering object path %s",
43 conn_obj, PyString_AS_STRING((PyObject *)user_data));
44 tuple = DBusPyConnection_GetObjectPathHandlers((PyObject *)conn_obj, (PyObject *)user_data);
45 if (!tuple) goto out;
46 if (tuple == Py_None) goto out;
48 DBG("%s", "... yes we have handlers for that object path");
50 /* 0'th item is the unregisterer (if that's a word) */
51 callable = PyTuple_GetItem(tuple, 0);
52 if (callable && callable != Py_None) {
53 DBG("%s", "... and we even have an unregisterer");
54 /* any return from the unregisterer is ignored */
55 Py_XDECREF(PyObject_CallFunctionObjArgs(callable, conn_obj, NULL));
57 out:
58 Py_XDECREF(conn_obj);
59 Py_XDECREF(tuple);
60 /* the user_data (a Python str) is no longer ref'd by the DBusConnection */
61 Py_XDECREF((PyObject *)user_data);
62 if (PyErr_Occurred()) {
63 PyErr_Print();
65 PyGILState_Release(gil);
68 static DBusHandlerResult
69 _object_path_message(DBusConnection *conn, DBusMessage *message,
70 void *user_data)
72 DBusHandlerResult ret;
73 PyGILState_STATE gil = PyGILState_Ensure();
74 Connection *conn_obj = NULL;
75 PyObject *tuple = NULL;
76 PyObject *msg_obj;
77 PyObject *callable; /* borrowed */
79 dbus_message_ref(message);
80 msg_obj = DBusPyMessage_ConsumeDBusMessage(message);
81 if (!msg_obj) {
82 ret = DBUS_HANDLER_RESULT_NEED_MEMORY;
83 goto out;
86 conn_obj = (Connection *)DBusPyConnection_ExistingFromDBusConnection(conn);
87 if (!conn_obj) {
88 ret = DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
89 goto out;
91 TRACE(conn_obj);
93 DBG("Connection at %p messaging object path %s",
94 conn_obj, PyString_AS_STRING((PyObject *)user_data));
95 DBG_DUMP_MESSAGE(message);
96 tuple = DBusPyConnection_GetObjectPathHandlers((PyObject *)conn_obj, (PyObject *)user_data);
97 if (!tuple || tuple == Py_None) {
98 ret = DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
99 goto out;
102 DBG("%s", "... yes we have handlers for that object path");
104 /* 1st item (0-based) is the message callback */
105 callable = PyTuple_GetItem(tuple, 1);
106 if (!callable) {
107 DBG("%s", "... error getting message handler from tuple");
108 ret = DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
110 else if (callable == Py_None) {
111 /* there was actually no handler after all */
112 DBG("%s", "... but those handlers don't do messages");
113 ret = DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
115 else {
116 DBG("%s", "... and we have a message handler for that object path");
117 ret = DBusPyConnection_HandleMessage(conn_obj, msg_obj, callable);
120 out:
121 Py_XDECREF(msg_obj);
122 Py_XDECREF(conn_obj);
123 Py_XDECREF(tuple);
124 if (PyErr_Occurred()) {
125 PyErr_Print();
127 PyGILState_Release(gil);
128 return ret;
131 static const DBusObjectPathVTable _object_path_vtable = {
132 _object_path_unregister,
133 _object_path_message,
136 static DBusHandlerResult
137 _filter_message(DBusConnection *conn, DBusMessage *message, void *user_data)
139 DBusHandlerResult ret;
140 PyGILState_STATE gil = PyGILState_Ensure();
141 Connection *conn_obj = NULL;
142 PyObject *callable = NULL;
143 PyObject *msg_obj;
144 #ifndef DBUS_PYTHON_DISABLE_CHECKS
145 Py_ssize_t i, size;
146 #endif
148 dbus_message_ref(message);
149 msg_obj = DBusPyMessage_ConsumeDBusMessage(message);
150 if (!msg_obj) {
151 DBG("%s", "OOM while trying to construct Message");
152 ret = DBUS_HANDLER_RESULT_NEED_MEMORY;
153 goto out;
156 conn_obj = (Connection *)DBusPyConnection_ExistingFromDBusConnection(conn);
157 if (!conn_obj) {
158 DBG("%s", "failed to traverse DBusConnection -> Connection weakref");
159 ret = DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
160 goto out;
162 TRACE(conn_obj);
164 /* The user_data is a pointer to a Python object. To avoid
165 * cross-library reference cycles, the DBusConnection isn't allowed
166 * to reference it. However, as long as the Connection is still
167 * alive, its ->filters list owns a reference to the same Python
168 * object, so the object should also still be alive.
170 * To ensure that this works, be careful whenever manipulating the
171 * filters list! (always put things in the list *before* giving
172 * them to libdbus, etc.)
174 #ifdef DBUS_PYTHON_DISABLE_CHECKS
175 callable = (PyObject *)user_data;
176 #else
177 size = PyList_GET_SIZE(conn_obj->filters);
178 for (i = 0; i < size; i++) {
179 callable = PyList_GET_ITEM(conn_obj->filters, i);
180 if (callable == user_data) {
181 Py_INCREF(callable);
182 break;
184 else {
185 callable = NULL;
189 if (!callable) {
190 DBG("... filter %p has vanished from ->filters, so not calling it",
191 user_data);
192 ret = DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
193 goto out;
195 #endif
197 ret = DBusPyConnection_HandleMessage(conn_obj, msg_obj, callable);
198 out:
199 Py_XDECREF(msg_obj);
200 Py_XDECREF(conn_obj);
201 Py_XDECREF(callable);
202 PyGILState_Release(gil);
203 return ret;
206 PyDoc_STRVAR(Connection__require_main_loop__doc__,
207 "_require_main_loop()\n\n"
208 "Raise an exception if this Connection is not bound to any main loop -\n"
209 "in this state, asynchronous calls, receiving signals and exporting objects\n"
210 "will not work.\n"
211 "\n"
212 "`dbus.mainloop.NULL_MAIN_LOOP` is treated like a valid main loop - if you're\n"
213 "using that, you presumably know what you're doing.\n");
214 static PyObject *
215 Connection__require_main_loop (Connection *self, PyObject *args UNUSED)
217 if (!self->has_mainloop) {
218 PyErr_SetString(PyExc_RuntimeError,
219 "To make asynchronous calls, receive signals or "
220 "export objects, D-Bus connections must be attached "
221 "to a main loop by passing mainloop=... to the "
222 "constructor or calling "
223 "dbus.set_default_main_loop(...)");
224 return NULL;
226 Py_RETURN_NONE;
229 PyDoc_STRVAR(Connection_close__doc__,
230 "close()\n\n"
231 "Close the connection.");
232 static PyObject *
233 Connection_close (Connection *self, PyObject *args UNUSED)
235 TRACE(self);
236 /* Because the user explicitly asked to close the connection, we'll even
237 let them close shared connections. */
238 if (self->conn) {
239 Py_BEGIN_ALLOW_THREADS
240 dbus_connection_close(self->conn);
241 Py_END_ALLOW_THREADS
243 Py_RETURN_NONE;
246 PyDoc_STRVAR(Connection_get_is_connected__doc__,
247 "get_is_connected() -> bool\n\n"
248 "Return true if this Connection is connected.\n");
249 static PyObject *
250 Connection_get_is_connected (Connection *self, PyObject *args UNUSED)
252 dbus_bool_t ret;
254 TRACE(self);
255 DBUS_PY_RAISE_VIA_NULL_IF_FAIL(self->conn);
256 Py_BEGIN_ALLOW_THREADS
257 ret = dbus_connection_get_is_connected(self->conn);
258 Py_END_ALLOW_THREADS
259 return PyBool_FromLong(ret);
262 PyDoc_STRVAR(Connection_get_is_authenticated__doc__,
263 "get_is_authenticated() -> bool\n\n"
264 "Return true if this Connection was ever authenticated.\n");
265 static PyObject *
266 Connection_get_is_authenticated (Connection *self, PyObject *args UNUSED)
268 dbus_bool_t ret;
270 TRACE(self);
271 DBUS_PY_RAISE_VIA_NULL_IF_FAIL(self->conn);
272 Py_BEGIN_ALLOW_THREADS
273 ret = dbus_connection_get_is_authenticated(self->conn);
274 Py_END_ALLOW_THREADS
275 return PyBool_FromLong(ret);
278 PyDoc_STRVAR(Connection_set_exit_on_disconnect__doc__,
279 "set_exit_on_disconnect(bool)\n\n"
280 "Set whether the C function ``_exit`` will be called when this Connection\n"
281 "becomes disconnected. This will cause the program to exit without calling\n"
282 "any cleanup code or exit handlers.\n"
283 "\n"
284 "The default is for this feature to be disabled for Connections and enabled\n"
285 "for Buses.\n");
286 static PyObject *
287 Connection_set_exit_on_disconnect (Connection *self, PyObject *args)
289 int exit_on_disconnect;
291 TRACE(self);
292 DBUS_PY_RAISE_VIA_NULL_IF_FAIL(self->conn);
293 if (!PyArg_ParseTuple(args, "i:set_exit_on_disconnect",
294 &exit_on_disconnect)) {
295 return NULL;
297 Py_BEGIN_ALLOW_THREADS
298 dbus_connection_set_exit_on_disconnect(self->conn,
299 exit_on_disconnect ? 1 : 0);
300 Py_END_ALLOW_THREADS
301 Py_RETURN_NONE;
304 PyDoc_STRVAR(Connection_send_message__doc__,
305 "send_message(msg) -> long\n\n"
306 "Queue the given message for sending, and return the message serial number.\n"
307 "\n"
308 ":Parameters:\n"
309 " `msg` : dbus.lowlevel.Message\n"
310 " The message to be sent.\n"
312 static PyObject *
313 Connection_send_message(Connection *self, PyObject *args)
315 dbus_bool_t ok;
316 PyObject *obj;
317 DBusMessage *msg;
318 dbus_uint32_t serial;
320 TRACE(self);
321 DBUS_PY_RAISE_VIA_NULL_IF_FAIL(self->conn);
322 if (!PyArg_ParseTuple(args, "O", &obj)) return NULL;
324 msg = DBusPyMessage_BorrowDBusMessage(obj);
325 if (!msg) return NULL;
327 Py_BEGIN_ALLOW_THREADS
328 ok = dbus_connection_send(self->conn, msg, &serial);
329 Py_END_ALLOW_THREADS
331 if (!ok) {
332 return PyErr_NoMemory();
335 return PyLong_FromUnsignedLong(serial);
338 /* The timeout is in seconds here, since that's conventional in Python. */
339 PyDoc_STRVAR(Connection_send_message_with_reply__doc__,
340 "send_message_with_reply(msg, reply_handler, timeout_s=-1, "
341 "require_main_loop=False) -> dbus.lowlevel.PendingCall\n\n"
342 "Queue the message for sending; expect a reply via the returned PendingCall,\n"
343 "which can also be used to cancel the pending call.\n"
344 "\n"
345 ":Parameters:\n"
346 " `msg` : dbus.lowlevel.Message\n"
347 " The message to be sent\n"
348 " `reply_handler` : callable\n"
349 " Asynchronous reply handler: will be called with one positional\n"
350 " parameter, a Message instance representing the reply.\n"
351 " `timeout_s` : float\n"
352 " If the reply takes more than this many seconds, a timeout error\n"
353 " will be created locally and raised instead. If this timeout is\n"
354 " negative (default), a sane default (supplied by libdbus) is used.\n"
355 " `require_main_loop` : bool\n"
356 " If True, raise RuntimeError if this Connection does not have a main\n"
357 " loop configured. If False (default) and there is no main loop, you are\n"
358 " responsible for calling block() on the PendingCall.\n"
359 "\n"
361 static PyObject *
362 Connection_send_message_with_reply(Connection *self, PyObject *args, PyObject *kw)
364 dbus_bool_t ok;
365 double timeout_s = -1.0;
366 int timeout_ms;
367 PyObject *obj, *callable;
368 DBusMessage *msg;
369 DBusPendingCall *pending;
370 int require_main_loop = 0;
371 static char *argnames[] = {"msg", "reply_handler", "timeout_s",
372 "require_main_loop", NULL};
374 TRACE(self);
375 DBUS_PY_RAISE_VIA_NULL_IF_FAIL(self->conn);
376 if (!PyArg_ParseTupleAndKeywords(args, kw,
377 "OO|di:send_message_with_reply",
378 argnames,
379 &obj, &callable, &timeout_s,
380 &require_main_loop)) {
381 return NULL;
383 if (require_main_loop && !Connection__require_main_loop(self, NULL)) {
384 return NULL;
387 msg = DBusPyMessage_BorrowDBusMessage(obj);
388 if (!msg) return NULL;
390 if (timeout_s < 0) {
391 timeout_ms = -1;
393 else {
394 if (timeout_s > ((double)INT_MAX) / 1000.0) {
395 PyErr_SetString(PyExc_ValueError, "Timeout too long");
396 return NULL;
398 timeout_ms = (int)(timeout_s * 1000.0);
401 Py_BEGIN_ALLOW_THREADS
402 ok = dbus_connection_send_with_reply(self->conn, msg, &pending,
403 timeout_ms);
404 Py_END_ALLOW_THREADS
406 if (!ok) {
407 return PyErr_NoMemory();
410 if (!pending) {
411 /* connection is disconnected (doesn't return FALSE!) */
412 return DBusPyException_SetString ("Connection is disconnected - "
413 "unable to make method call");
416 return DBusPyPendingCall_ConsumeDBusPendingCall(pending, callable);
419 /* Again, the timeout is in seconds, since that's conventional in Python. */
420 PyDoc_STRVAR(Connection_send_message_with_reply_and_block__doc__,
421 "send_message_with_reply_and_block(msg, timeout_s=-1)"
422 " -> dbus.lowlevel.Message\n\n"
423 "Send the message and block while waiting for a reply.\n"
424 "\n"
425 "This does not re-enter the main loop, so it can lead to a deadlock, if\n"
426 "the called method tries to make a synchronous call to a method in this\n"
427 "application. As such, it's probably a bad idea.\n"
428 "\n"
429 ":Parameters:\n"
430 " `msg` : dbus.lowlevel.Message\n"
431 " The message to be sent\n"
432 " `timeout_s` : float\n"
433 " If the reply takes more than this many seconds, a timeout error\n"
434 " will be created locally and raised instead. If this timeout is\n"
435 " negative (default), a sane default (supplied by libdbus) is used.\n"
436 ":Returns:\n"
437 " A `dbus.lowlevel.Message` instance (probably a `dbus.lowlevel.MethodReturnMessage`) on success\n"
438 ":Raises dbus.DBusException:\n"
439 " On error (including if the reply arrives but is an\n"
440 " error message)\n"
441 "\n"
443 static PyObject *
444 Connection_send_message_with_reply_and_block(Connection *self, PyObject *args)
446 double timeout_s = -1.0;
447 int timeout_ms;
448 PyObject *obj;
449 DBusMessage *msg, *reply;
450 DBusError error;
452 TRACE(self);
453 DBUS_PY_RAISE_VIA_NULL_IF_FAIL(self->conn);
454 if (!PyArg_ParseTuple(args, "O|d:send_message_with_reply_and_block", &obj,
455 &timeout_s)) {
456 return NULL;
459 msg = DBusPyMessage_BorrowDBusMessage(obj);
460 if (!msg) return NULL;
462 if (timeout_s < 0) {
463 timeout_ms = -1;
465 else {
466 if (timeout_s > ((double)INT_MAX) / 1000.0) {
467 PyErr_SetString(PyExc_ValueError, "Timeout too long");
468 return NULL;
470 timeout_ms = (int)(timeout_s * 1000.0);
473 dbus_error_init(&error);
474 Py_BEGIN_ALLOW_THREADS
475 reply = dbus_connection_send_with_reply_and_block(self->conn, msg,
476 timeout_ms, &error);
477 Py_END_ALLOW_THREADS
479 /* FIXME: if we instead used send_with_reply and blocked on the resulting
480 * PendingCall, then we could get all args from the error, not just
481 * the first */
482 if (!reply) {
483 return DBusPyException_ConsumeError(&error);
485 return DBusPyMessage_ConsumeDBusMessage(reply);
488 PyDoc_STRVAR(Connection_flush__doc__,
489 "flush()\n\n"
490 "Block until the outgoing message queue is empty.\n");
491 static PyObject *
492 Connection_flush (Connection *self, PyObject *args UNUSED)
494 TRACE(self);
495 DBUS_PY_RAISE_VIA_NULL_IF_FAIL(self->conn);
496 Py_BEGIN_ALLOW_THREADS
497 dbus_connection_flush (self->conn);
498 Py_END_ALLOW_THREADS
499 Py_RETURN_NONE;
502 /* Unsupported:
503 * dbus_connection_preallocate_send
504 * dbus_connection_free_preallocated_send
505 * dbus_connection_send_preallocated
506 * dbus_connection_borrow_message
507 * dbus_connection_return_message
508 * dbus_connection_steal_borrowed_message
509 * dbus_connection_pop_message
512 /* Non-main-loop handling not yet implemented: */
513 /* dbus_connection_read_write_dispatch */
514 /* dbus_connection_read_write */
516 /* Main loop handling not yet implemented: */
517 /* dbus_connection_get_dispatch_status */
518 /* dbus_connection_dispatch */
519 /* dbus_connection_set_watch_functions */
520 /* dbus_connection_set_timeout_functions */
521 /* dbus_connection_set_wakeup_main_function */
522 /* dbus_connection_set_dispatch_status_function */
524 /* Normally in Python this would be called fileno(), but I don't want to
525 * encourage people to select() on it */
526 PyDoc_STRVAR(Connection_get_unix_fd__doc__,
527 "get_unix_fd() -> int or None\n\n"
528 "Get the connection's UNIX file descriptor, if any.\n\n"
529 "This can be used for SELinux access control checks with ``getpeercon()``\n"
530 "for example. **Do not** read or write to the file descriptor, or try to\n"
531 "``select()`` on it.\n");
532 static PyObject *
533 Connection_get_unix_fd (Connection *self, PyObject *unused UNUSED)
535 int fd;
536 dbus_bool_t ok;
538 TRACE(self);
539 DBUS_PY_RAISE_VIA_NULL_IF_FAIL(self->conn);
540 Py_BEGIN_ALLOW_THREADS
541 ok = dbus_connection_get_unix_fd (self->conn, &fd);
542 Py_END_ALLOW_THREADS
543 if (!ok) Py_RETURN_NONE;
544 return PyInt_FromLong(fd);
547 PyDoc_STRVAR(Connection_get_peer_unix_user__doc__,
548 "get_peer_unix_user() -> long or None\n\n"
549 "Get the UNIX user ID at the other end of the connection, if it has been\n"
550 "authenticated. Return None if this is a non-UNIX platform or the\n"
551 "connection has not been authenticated.\n");
552 static PyObject *
553 Connection_get_peer_unix_user (Connection *self, PyObject *unused UNUSED)
555 unsigned long uid;
556 dbus_bool_t ok;
558 TRACE(self);
559 DBUS_PY_RAISE_VIA_NULL_IF_FAIL(self->conn);
560 Py_BEGIN_ALLOW_THREADS
561 ok = dbus_connection_get_unix_user (self->conn, &uid);
562 Py_END_ALLOW_THREADS
563 if (!ok) Py_RETURN_NONE;
564 return PyLong_FromUnsignedLong (uid);
567 PyDoc_STRVAR(Connection_get_peer_unix_process_id__doc__,
568 "get_peer_unix_process_id() -> long or None\n\n"
569 "Get the UNIX process ID at the other end of the connection, if it has been\n"
570 "authenticated. Return None if this is a non-UNIX platform or the\n"
571 "connection has not been authenticated.\n");
572 static PyObject *
573 Connection_get_peer_unix_process_id (Connection *self, PyObject *unused UNUSED)
575 unsigned long pid;
576 dbus_bool_t ok;
578 TRACE(self);
579 DBUS_PY_RAISE_VIA_NULL_IF_FAIL(self->conn);
580 Py_BEGIN_ALLOW_THREADS
581 ok = dbus_connection_get_unix_process_id (self->conn, &pid);
582 Py_END_ALLOW_THREADS
583 if (!ok) Py_RETURN_NONE;
584 return PyLong_FromUnsignedLong (pid);
587 /* TODO: wrap dbus_connection_set_unix_user_function Pythonically */
589 PyDoc_STRVAR(Connection_add_message_filter__doc__,
590 "add_message_filter(callable)\n\n"
591 "Add the given message filter to the internal list.\n\n"
592 "Filters are handlers that are run on all incoming messages, prior to the\n"
593 "objects registered to handle object paths.\n"
594 "\n"
595 "Filters are run in the order that they were added. The same handler can\n"
596 "be added as a filter more than once, in which case it will be run more\n"
597 "than once. Filters added during a filter callback won't be run on the\n"
598 "message being processed.\n"
600 static PyObject *
601 Connection_add_message_filter(Connection *self, PyObject *callable)
603 dbus_bool_t ok;
605 TRACE(self);
606 DBUS_PY_RAISE_VIA_NULL_IF_FAIL(self->conn);
607 /* The callable must be referenced by ->filters *before* it is
608 * given to libdbus, which does not own a reference to it.
610 if (PyList_Append(self->filters, callable) < 0) {
611 return NULL;
614 Py_BEGIN_ALLOW_THREADS
615 ok = dbus_connection_add_filter(self->conn, _filter_message, callable,
616 NULL);
617 Py_END_ALLOW_THREADS
619 if (!ok) {
620 Py_XDECREF(PyObject_CallMethod(self->filters, "remove", "(O)",
621 callable));
622 PyErr_NoMemory();
623 return NULL;
625 Py_RETURN_NONE;
628 PyDoc_STRVAR(Connection_remove_message_filter__doc__,
629 "remove_message_filter(callable)\n\n"
630 "Remove the given message filter (see `add_message_filter` for details).\n"
631 "\n"
632 ":Raises LookupError:\n"
633 " The given callable is not among the registered filters\n");
634 static PyObject *
635 Connection_remove_message_filter(Connection *self, PyObject *callable)
637 PyObject *obj;
639 TRACE(self);
640 DBUS_PY_RAISE_VIA_NULL_IF_FAIL(self->conn);
641 /* It's safe to do this before removing it from libdbus, because
642 * the presence of callable in our arguments means we have a ref
643 * to it. */
644 obj = PyObject_CallMethod(self->filters, "remove", "(O)", callable);
645 if (!obj) return NULL;
646 Py_DECREF(obj);
648 Py_BEGIN_ALLOW_THREADS
649 dbus_connection_remove_filter(self->conn, _filter_message, callable);
650 Py_END_ALLOW_THREADS
652 Py_RETURN_NONE;
655 PyDoc_STRVAR(Connection__register_object_path__doc__,
656 "register_object_path(path, on_message, on_unregister=None, fallback=False)\n"
657 "\n"
658 "Register a callback to be called when messages arrive at the given\n"
659 "object-path. Used to export objects' methods on the bus in a low-level\n"
660 "way. For the high-level interface to this functionality (usually\n"
661 "recommended) see the `dbus.service.Object` base class.\n"
662 "\n"
663 ":Parameters:\n"
664 " `path` : str\n"
665 " Object path to be acted on\n"
666 " `on_message` : callable\n"
667 " Called when a message arrives at the given object-path, with\n"
668 " two positional parameters: the first is this Connection,\n"
669 " the second is the incoming `dbus.lowlevel.Message`.\n"
670 " `on_unregister` : callable or None\n"
671 " If not None, called when the callback is unregistered.\n"
672 " `fallback` : bool\n"
673 " If True (the default is False), when a message arrives for a\n"
674 " 'subdirectory' of the given path and there is no more specific\n"
675 " handler, use this handler. Normally this handler is only run if\n"
676 " the paths match exactly.\n"
678 static PyObject *
679 Connection__register_object_path(Connection *self, PyObject *args,
680 PyObject *kwargs)
682 dbus_bool_t ok;
683 int fallback = 0;
684 PyObject *callbacks, *path, *tuple, *on_message, *on_unregister = Py_None;
685 static char *argnames[] = {"path", "on_message", "on_unregister",
686 "fallback", NULL};
688 TRACE(self);
689 DBUS_PY_RAISE_VIA_NULL_IF_FAIL(self->conn);
690 if (!Connection__require_main_loop(self, NULL)) {
691 return NULL;
693 if (!PyArg_ParseTupleAndKeywords(args, kwargs,
694 "OO|Oi:_register_object_path",
695 argnames,
696 &path,
697 &on_message, &on_unregister,
698 &fallback)) return NULL;
700 /* Take a reference to path, which we give away to libdbus in a moment.
702 Also, path needs to be a string (not a subclass which could do something
703 mad) to preserve the desirable property that the DBusConnection can
704 never strongly reference the Connection, even indirectly.
706 if (PyString_CheckExact(path)) {
707 Py_INCREF(path);
709 else if (PyUnicode_Check(path)) {
710 path = PyUnicode_AsUTF8String(path);
711 if (!path) return NULL;
713 else if (PyString_Check(path)) {
714 path = PyString_FromString(PyString_AS_STRING(path));
715 if (!path) return NULL;
717 else {
718 PyErr_SetString(PyExc_TypeError, "path must be a str or unicode object");
719 return NULL;
722 if (!dbus_py_validate_object_path(PyString_AS_STRING(path))) {
723 Py_DECREF(path);
724 return NULL;
727 tuple = Py_BuildValue("(OO)", on_unregister, on_message);
728 if (!tuple) {
729 Py_DECREF(path);
730 return NULL;
733 /* Guard against registering a handler that already exists. */
734 callbacks = PyDict_GetItem(self->object_paths, path);
735 if (callbacks && callbacks != Py_None) {
736 PyErr_Format(PyExc_KeyError, "Can't register the object-path "
737 "handler for '%s': there is already a handler",
738 PyString_AS_STRING(path));
739 Py_DECREF(tuple);
740 Py_DECREF(path);
741 return NULL;
744 /* Pre-allocate a slot in the dictionary, so we know we'll be able
745 * to replace it with the callbacks without OOM.
746 * This ensures we can keep libdbus' opinion of whether those
747 * paths are handled in sync with our own. */
748 if (PyDict_SetItem(self->object_paths, path, Py_None) < 0) {
749 Py_DECREF(tuple);
750 Py_DECREF(path);
751 return NULL;
754 Py_BEGIN_ALLOW_THREADS
755 if (fallback) {
756 ok = dbus_connection_register_fallback(self->conn,
757 PyString_AS_STRING(path),
758 &_object_path_vtable,
759 path);
761 else {
762 ok = dbus_connection_register_object_path(self->conn,
763 PyString_AS_STRING(path),
764 &_object_path_vtable,
765 path);
767 Py_END_ALLOW_THREADS
769 if (ok) {
770 if (PyDict_SetItem(self->object_paths, path, tuple) < 0) {
771 /* That shouldn't have happened, we already allocated enough
772 memory for it. Oh well, try to undo the registration to keep
773 things in sync. If this fails too, we've leaked a bit of
774 memory in libdbus, but tbh we should never get here anyway. */
775 Py_BEGIN_ALLOW_THREADS
776 ok = dbus_connection_unregister_object_path(self->conn,
777 PyString_AS_STRING(path));
778 Py_END_ALLOW_THREADS
779 return NULL;
781 /* don't DECREF path: libdbus owns a ref now */
782 Py_DECREF(tuple);
783 Py_RETURN_NONE;
785 else {
786 /* Oops, OOM. Tidy up, if we can, ignoring any error. */
787 PyDict_DelItem(self->object_paths, path);
788 PyErr_Clear();
789 Py_DECREF(tuple);
790 Py_DECREF(path);
791 PyErr_NoMemory();
792 return NULL;
796 PyDoc_STRVAR(Connection__unregister_object_path__doc__,
797 "unregister_object_path(path)\n\n"
798 "Remove a previously registered handler for the given object path.\n"
799 "\n"
800 ":Parameters:\n"
801 " `path` : str\n"
802 " The object path whose handler is to be removed\n"
803 ":Raises KeyError: if there is no handler registered for exactly that\n"
804 " object path.\n"
806 static PyObject *
807 Connection__unregister_object_path(Connection *self, PyObject *args,
808 PyObject *kwargs)
810 dbus_bool_t ok;
811 PyObject *path;
812 PyObject *callbacks;
813 static char *argnames[] = {"path", NULL};
815 TRACE(self);
816 DBUS_PY_RAISE_VIA_NULL_IF_FAIL(self->conn);
817 if (!PyArg_ParseTupleAndKeywords(args, kwargs,
818 "O:_unregister_object_path",
819 argnames, &path)) return NULL;
821 /* Take a ref to the path. Same comments as for _register_object_path. */
822 if (PyString_CheckExact(path)) {
823 Py_INCREF(path);
825 else if (PyUnicode_Check(path)) {
826 path = PyUnicode_AsUTF8String(path);
827 if (!path) return NULL;
829 else if (PyString_Check(path)) {
830 path = PyString_FromString(PyString_AS_STRING(path));
831 if (!path) return NULL;
833 else {
834 PyErr_SetString(PyExc_TypeError, "path must be a str or unicode object");
835 return NULL;
838 /* Guard against unregistering a handler that doesn't, in fact, exist,
839 or whose unregistration is already in progress. */
840 callbacks = PyDict_GetItem(self->object_paths, path);
841 if (!callbacks || callbacks == Py_None) {
842 PyErr_Format(PyExc_KeyError, "Can't unregister the object-path "
843 "handler for '%s': there is no such handler",
844 PyString_AS_STRING(path));
845 Py_DECREF(path);
846 return NULL;
849 /* Hang on to a reference to the callbacks for the moment. */
850 Py_INCREF(callbacks);
852 /* Get rid of the object-path while we still have the GIL, to
853 guard against unregistering twice from different threads (which
854 causes undefined behaviour in libdbus).
856 Because deletion would make it possible for the re-insertion below
857 to fail, we instead set the handler to None as a placeholder.
859 if (PyDict_SetItem(self->object_paths, path, Py_None) < 0) {
860 /* If that failed, there's no need to be paranoid as below - the
861 callbacks are still set, so we failed, but at least everything
862 is in sync. */
863 Py_DECREF(callbacks);
864 Py_DECREF(path);
865 return NULL;
868 /* BEGIN PARANOIA
869 This is something of a critical section - the dict of object-paths
870 and libdbus' internal structures are out of sync for a bit. We have
871 to be able to cope with that.
873 It's really annoying that dbus_connection_unregister_object_path
874 can fail, *and* has undefined behaviour if the object path has
875 already been unregistered. Either/or would be fine.
878 Py_BEGIN_ALLOW_THREADS
879 ok = dbus_connection_unregister_object_path(self->conn,
880 PyString_AS_STRING(path));
881 Py_END_ALLOW_THREADS
883 if (ok) {
884 Py_DECREF(callbacks);
885 PyDict_DelItem(self->object_paths, path);
886 /* END PARANOIA on successful code path */
887 /* The above can't fail unless by some strange trickery the key is no
888 longer present. Ignore any errors. */
889 Py_DECREF(path);
890 PyErr_Clear();
891 Py_RETURN_NONE;
893 else {
894 /* Oops, OOM. Put the callbacks back in the dict so
895 * we'll have another go if/when the user frees some memory
896 * and tries calling this method again. */
897 PyDict_SetItem(self->object_paths, path, callbacks);
898 /* END PARANOIA on failing code path */
899 /* If the SetItem failed, there's nothing we can do about it - but
900 since we know it's an existing entry, it shouldn't be able to fail
901 anyway. */
902 Py_DECREF(path);
903 Py_DECREF(callbacks);
904 return PyErr_NoMemory();
908 PyDoc_STRVAR(Connection_list_exported_child_objects__doc__,
909 "list_exported_child_objects(path: str) -> list of str\n\n"
910 "Return a list of the names of objects exported on this Connection as\n"
911 "direct children of the given object path.\n"
912 "\n"
913 "Each name returned may be converted to a valid object path using\n"
914 "``dbus.ObjectPath('%s%s%s' % (path, (path != '/' and '/' or ''), name))``.\n"
915 "For the purposes of this function, every parent or ancestor of an exported\n"
916 "object is considered to be an exported object, even if it's only an object\n"
917 "synthesized by the library to support introspection.\n");
918 static PyObject *
919 Connection_list_exported_child_objects (Connection *self, PyObject *args,
920 PyObject *kwargs)
922 const char *path;
923 char **kids, **kid_ptr;
924 dbus_bool_t ok;
925 PyObject *ret;
926 static char *argnames[] = {"path", NULL};
928 DBUS_PY_RAISE_VIA_NULL_IF_FAIL(self->conn);
929 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s", argnames, &path)) {
930 return NULL;
933 if (!dbus_py_validate_object_path(path)) {
934 return NULL;
937 Py_BEGIN_ALLOW_THREADS
938 ok = dbus_connection_list_registered(self->conn, path, &kids);
939 Py_END_ALLOW_THREADS
941 if (!ok) {
942 return PyErr_NoMemory();
945 ret = PyList_New(0);
946 if (!ret) {
947 return NULL;
949 for (kid_ptr = kids; *kid_ptr; kid_ptr++) {
950 PyObject *tmp = PyString_FromString(*kid_ptr);
952 if (!tmp) {
953 Py_DECREF(ret);
954 return NULL;
956 if (PyList_Append(ret, tmp) < 0) {
957 Py_DECREF(tmp);
958 Py_DECREF(ret);
959 return NULL;
961 Py_DECREF(tmp);
964 dbus_free_string_array(kids);
966 return ret;
969 /* dbus_connection_get_object_path_data - not useful to Python,
970 * the object path data is just a PyString containing the path */
971 /* dbus_connection_list_registered could be useful, though */
973 /* dbus_connection_set_change_sigpipe - sets global state */
975 /* Maxima. Does Python code ever need to manipulate these?
976 * OTOH they're easy to wrap */
977 /* dbus_connection_set_max_message_size */
978 /* dbus_connection_get_max_message_size */
979 /* dbus_connection_set_max_received_size */
980 /* dbus_connection_get_max_received_size */
982 /* dbus_connection_get_outgoing_size - almost certainly unneeded */
984 PyDoc_STRVAR(new_for_bus__doc__,
985 "Connection._new_for_bus([address: str or int]) -> Connection\n"
986 "\n"
987 "If the address is an int it must be one of the constants BUS_SESSION,\n"
988 "BUS_SYSTEM, BUS_STARTER; if a string, it must be a D-Bus address.\n"
989 "The default is BUS_SESSION.\n"
992 PyDoc_STRVAR(get_unique_name__doc__,
993 "get_unique_name() -> str\n\n"
994 "Return this application's unique name on this bus.\n"
995 "\n"
996 ":Raises DBusException: if the connection has no unique name yet\n"
997 " (for Bus objects this can't happen, for peer-to-peer connections\n"
998 " this means you haven't called `set_unique_name`)\n");
1000 PyDoc_STRVAR(set_unique_name__doc__,
1001 "set_unique_name(str)\n\n"
1002 "Set this application's unique name on this bus. Raise ValueError if it has\n"
1003 "already been set.\n");
1005 struct PyMethodDef DBusPyConnection_tp_methods[] = {
1006 #define ENTRY(name, flags) {#name, (PyCFunction)Connection_##name, flags, Connection_##name##__doc__}
1007 ENTRY(_require_main_loop, METH_NOARGS),
1008 ENTRY(close, METH_NOARGS),
1009 ENTRY(flush, METH_NOARGS),
1010 ENTRY(get_is_connected, METH_NOARGS),
1011 ENTRY(get_is_authenticated, METH_NOARGS),
1012 ENTRY(set_exit_on_disconnect, METH_VARARGS),
1013 ENTRY(get_unix_fd, METH_NOARGS),
1014 ENTRY(get_peer_unix_user, METH_NOARGS),
1015 ENTRY(get_peer_unix_process_id, METH_NOARGS),
1016 ENTRY(add_message_filter, METH_O),
1017 ENTRY(_register_object_path, METH_VARARGS|METH_KEYWORDS),
1018 ENTRY(remove_message_filter, METH_O),
1019 ENTRY(send_message, METH_VARARGS),
1020 ENTRY(send_message_with_reply, METH_VARARGS|METH_KEYWORDS),
1021 ENTRY(send_message_with_reply_and_block, METH_VARARGS),
1022 ENTRY(_unregister_object_path, METH_VARARGS|METH_KEYWORDS),
1023 ENTRY(list_exported_child_objects, METH_VARARGS|METH_KEYWORDS),
1024 {"_new_for_bus", (PyCFunction)DBusPyConnection_NewForBus,
1025 METH_CLASS|METH_VARARGS|METH_KEYWORDS,
1026 new_for_bus__doc__},
1027 {"get_unique_name", (PyCFunction)DBusPyConnection_GetUniqueName,
1028 METH_NOARGS,
1029 get_unique_name__doc__},
1030 {"set_unique_name", (PyCFunction)DBusPyConnection_SetUniqueName,
1031 METH_VARARGS,
1032 set_unique_name__doc__},
1033 {NULL},
1034 #undef ENTRY
1037 /* vim:set ft=c cino< sw=4 sts=4 et: */