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 * Licensed under the Academic Free License version 2.1
8 * This library is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU Lesser General Public License as published by
10 * the Free Software Foundation; either version 2.1 of the License, or
11 * (at your option) any later version.
13 * This library 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 Lesser General Public License for more details.
18 * You should have received a copy of the GNU Lesser General Public License
19 * along with this library; if not, write to the Free Software
20 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
24 #include "dbus_bindings-internal.h"
25 #include "conn-internal.h"
28 _object_path_unregister(DBusConnection
*conn
, void *user_data
)
30 PyGILState_STATE gil
= PyGILState_Ensure();
31 PyObject
*tuple
= NULL
;
32 Connection
*conn_obj
= NULL
;
35 conn_obj
= (Connection
*)DBusPyConnection_ExistingFromDBusConnection(conn
);
36 if (!conn_obj
) goto out
;
39 DBG("Connection at %p unregistering object path %s",
40 conn_obj
, PyString_AS_STRING((PyObject
*)user_data
));
41 tuple
= DBusPyConnection_GetObjectPathHandlers((PyObject
*)conn_obj
, (PyObject
*)user_data
);
43 if (tuple
== Py_None
) goto out
;
45 DBG("%s", "... yes we have handlers for that object path");
47 /* 0'th item is the unregisterer (if that's a word) */
48 callable
= PyTuple_GetItem(tuple
, 0);
49 if (callable
&& callable
!= Py_None
) {
50 DBG("%s", "... and we even have an unregisterer");
51 /* any return from the unregisterer is ignored */
52 Py_XDECREF(PyObject_CallFunctionObjArgs(callable
, conn_obj
, NULL
));
57 /* the user_data (a Python str) is no longer ref'd by the DBusConnection */
58 Py_XDECREF((PyObject
*)user_data
);
59 if (PyErr_Occurred()) {
62 PyGILState_Release(gil
);
65 static DBusHandlerResult
66 _object_path_message(DBusConnection
*conn
, DBusMessage
*message
,
69 DBusHandlerResult ret
;
70 PyGILState_STATE gil
= PyGILState_Ensure();
71 Connection
*conn_obj
= NULL
;
72 PyObject
*tuple
= NULL
;
74 PyObject
*callable
; /* borrowed */
76 dbus_message_ref(message
);
77 msg_obj
= DBusPyMessage_ConsumeDBusMessage(message
);
79 ret
= DBUS_HANDLER_RESULT_NEED_MEMORY
;
83 conn_obj
= (Connection
*)DBusPyConnection_ExistingFromDBusConnection(conn
);
85 ret
= DBUS_HANDLER_RESULT_NOT_YET_HANDLED
;
90 DBG("Connection at %p messaging object path %s",
91 conn_obj
, PyString_AS_STRING((PyObject
*)user_data
));
92 DBG_DUMP_MESSAGE(message
);
93 tuple
= DBusPyConnection_GetObjectPathHandlers((PyObject
*)conn_obj
, (PyObject
*)user_data
);
94 if (!tuple
|| tuple
== Py_None
) {
95 ret
= DBUS_HANDLER_RESULT_NOT_YET_HANDLED
;
99 DBG("%s", "... yes we have handlers for that object path");
101 /* 1st item (0-based) is the message callback */
102 callable
= PyTuple_GetItem(tuple
, 1);
104 DBG("%s", "... error getting message handler from tuple");
105 ret
= DBUS_HANDLER_RESULT_NOT_YET_HANDLED
;
107 else if (callable
== Py_None
) {
108 /* there was actually no handler after all */
109 DBG("%s", "... but those handlers don't do messages");
110 ret
= DBUS_HANDLER_RESULT_NOT_YET_HANDLED
;
113 DBG("%s", "... and we have a message handler for that object path");
114 ret
= DBusPyConnection_HandleMessage(conn_obj
, msg_obj
, callable
);
119 Py_XDECREF(conn_obj
);
121 if (PyErr_Occurred()) {
124 PyGILState_Release(gil
);
128 static const DBusObjectPathVTable _object_path_vtable
= {
129 _object_path_unregister
,
130 _object_path_message
,
133 static DBusHandlerResult
134 _filter_message(DBusConnection
*conn
, DBusMessage
*message
, void *user_data
)
136 DBusHandlerResult ret
;
137 PyGILState_STATE gil
= PyGILState_Ensure();
138 Connection
*conn_obj
= NULL
;
139 PyObject
*callable
= NULL
;
141 #ifndef DBUS_PYTHON_DISABLE_CHECKS
145 dbus_message_ref(message
);
146 msg_obj
= DBusPyMessage_ConsumeDBusMessage(message
);
148 DBG("%s", "OOM while trying to construct Message");
149 ret
= DBUS_HANDLER_RESULT_NEED_MEMORY
;
153 conn_obj
= (Connection
*)DBusPyConnection_ExistingFromDBusConnection(conn
);
155 DBG("%s", "failed to traverse DBusConnection -> Connection weakref");
156 ret
= DBUS_HANDLER_RESULT_NOT_YET_HANDLED
;
161 /* The user_data is a pointer to a Python object. To avoid
162 * cross-library reference cycles, the DBusConnection isn't allowed
163 * to reference it. However, as long as the Connection is still
164 * alive, its ->filters list owns a reference to the same Python
165 * object, so the object should also still be alive.
167 * To ensure that this works, be careful whenever manipulating the
168 * filters list! (always put things in the list *before* giving
169 * them to libdbus, etc.)
171 #ifdef DBUS_PYTHON_DISABLE_CHECKS
172 callable
= (PyObject
*)user_data
;
174 size
= PyList_GET_SIZE(conn_obj
->filters
);
175 for (i
= 0; i
< size
; i
++) {
176 callable
= PyList_GET_ITEM(conn_obj
->filters
, i
);
177 if (callable
== user_data
) {
186 DBG("... filter %p has vanished from ->filters, so not calling it",
188 ret
= DBUS_HANDLER_RESULT_NOT_YET_HANDLED
;
193 ret
= DBusPyConnection_HandleMessage(conn_obj
, msg_obj
, callable
);
196 Py_XDECREF(conn_obj
);
197 Py_XDECREF(callable
);
198 PyGILState_Release(gil
);
202 PyDoc_STRVAR(Connection__require_main_loop__doc__
,
203 "_require_main_loop()\n\n"
204 "Raise an exception if this Connection is not bound to any main loop -\n"
205 "in this state, asynchronous calls, receiving signals and exporting objects\n"
208 "`dbus.mainloop.NULL_MAIN_LOOP` is treated like a valid main loop - if you're\n"
209 "using that, you presumably know what you're doing.\n");
211 Connection__require_main_loop (Connection
*self
, PyObject
*args UNUSED
)
213 if (!self
->has_mainloop
) {
214 PyErr_SetString(PyExc_RuntimeError
,
215 "To make asynchronous calls, receive signals or "
216 "export objects, D-Bus connections must be attached "
217 "to a main loop by passing mainloop=... to the "
218 "constructor or calling "
219 "dbus.set_default_main_loop(...)");
225 PyDoc_STRVAR(Connection_close__doc__
,
227 "Close the connection.");
229 Connection_close (Connection
*self
, PyObject
*args UNUSED
)
232 /* Because the user explicitly asked to close the connection, we'll even
233 let them close shared connections. */
235 Py_BEGIN_ALLOW_THREADS
236 dbus_connection_close(self
->conn
);
242 PyDoc_STRVAR(Connection_get_is_connected__doc__
,
243 "get_is_connected() -> bool\n\n"
244 "Return true if this Connection is connected.\n");
246 Connection_get_is_connected (Connection
*self
, PyObject
*args UNUSED
)
251 DBUS_PY_RAISE_VIA_NULL_IF_FAIL(self
->conn
);
252 Py_BEGIN_ALLOW_THREADS
253 ret
= dbus_connection_get_is_connected(self
->conn
);
255 return PyBool_FromLong(ret
);
258 PyDoc_STRVAR(Connection_get_is_authenticated__doc__
,
259 "get_is_authenticated() -> bool\n\n"
260 "Return true if this Connection was ever authenticated.\n");
262 Connection_get_is_authenticated (Connection
*self
, PyObject
*args UNUSED
)
267 DBUS_PY_RAISE_VIA_NULL_IF_FAIL(self
->conn
);
268 Py_BEGIN_ALLOW_THREADS
269 ret
= dbus_connection_get_is_authenticated(self
->conn
);
271 return PyBool_FromLong(ret
);
274 PyDoc_STRVAR(Connection_set_exit_on_disconnect__doc__
,
275 "set_exit_on_disconnect(bool)\n\n"
276 "Set whether the C function ``_exit`` will be called when this Connection\n"
277 "becomes disconnected. This will cause the program to exit without calling\n"
278 "any cleanup code or exit handlers.\n"
280 "The default is for this feature to be disabled for Connections and enabled\n"
283 Connection_set_exit_on_disconnect (Connection
*self
, PyObject
*args
)
285 int exit_on_disconnect
;
288 DBUS_PY_RAISE_VIA_NULL_IF_FAIL(self
->conn
);
289 if (!PyArg_ParseTuple(args
, "i:set_exit_on_disconnect",
290 &exit_on_disconnect
)) {
293 Py_BEGIN_ALLOW_THREADS
294 dbus_connection_set_exit_on_disconnect(self
->conn
,
295 exit_on_disconnect
? 1 : 0);
300 PyDoc_STRVAR(Connection_send_message__doc__
,
301 "send_message(msg) -> long\n\n"
302 "Queue the given message for sending, and return the message serial number.\n"
305 " `msg` : dbus.lowlevel.Message\n"
306 " The message to be sent.\n"
309 Connection_send_message(Connection
*self
, PyObject
*args
)
314 dbus_uint32_t serial
;
317 DBUS_PY_RAISE_VIA_NULL_IF_FAIL(self
->conn
);
318 if (!PyArg_ParseTuple(args
, "O", &obj
)) return NULL
;
320 msg
= DBusPyMessage_BorrowDBusMessage(obj
);
321 if (!msg
) return NULL
;
323 Py_BEGIN_ALLOW_THREADS
324 ok
= dbus_connection_send(self
->conn
, msg
, &serial
);
328 return PyErr_NoMemory();
331 return PyLong_FromUnsignedLong(serial
);
334 /* The timeout is in seconds here, since that's conventional in Python. */
335 PyDoc_STRVAR(Connection_send_message_with_reply__doc__
,
336 "send_message_with_reply(msg, reply_handler, timeout_s=-1, "
337 "require_main_loop=False) -> dbus.lowlevel.PendingCall\n\n"
338 "Queue the message for sending; expect a reply via the returned PendingCall,\n"
339 "which can also be used to cancel the pending call.\n"
342 " `msg` : dbus.lowlevel.Message\n"
343 " The message to be sent\n"
344 " `reply_handler` : callable\n"
345 " Asynchronous reply handler: will be called with one positional\n"
346 " parameter, a Message instance representing the reply.\n"
347 " `timeout_s` : float\n"
348 " If the reply takes more than this many seconds, a timeout error\n"
349 " will be created locally and raised instead. If this timeout is\n"
350 " negative (default), a sane default (supplied by libdbus) is used.\n"
351 " `require_main_loop` : bool\n"
352 " If True, raise RuntimeError if this Connection does not have a main\n"
353 " loop configured. If False (default) and there is no main loop, you are\n"
354 " responsible for calling block() on the PendingCall.\n"
358 Connection_send_message_with_reply(Connection
*self
, PyObject
*args
, PyObject
*kw
)
361 double timeout_s
= -1.0;
363 PyObject
*obj
, *callable
;
365 DBusPendingCall
*pending
;
366 int require_main_loop
= 0;
367 static char *argnames
[] = {"msg", "reply_handler", "timeout_s",
368 "require_main_loop", NULL
};
371 DBUS_PY_RAISE_VIA_NULL_IF_FAIL(self
->conn
);
372 if (!PyArg_ParseTupleAndKeywords(args
, kw
,
373 "OO|di:send_message_with_reply",
375 &obj
, &callable
, &timeout_s
,
376 &require_main_loop
)) {
379 if (require_main_loop
&& !Connection__require_main_loop(self
, NULL
)) {
383 msg
= DBusPyMessage_BorrowDBusMessage(obj
);
384 if (!msg
) return NULL
;
390 if (timeout_s
> ((double)INT_MAX
) / 1000.0) {
391 PyErr_SetString(PyExc_ValueError
, "Timeout too long");
394 timeout_ms
= (int)(timeout_s
* 1000.0);
397 Py_BEGIN_ALLOW_THREADS
398 ok
= dbus_connection_send_with_reply(self
->conn
, msg
, &pending
,
403 return PyErr_NoMemory();
407 /* connection is disconnected (doesn't return FALSE!) */
408 return DBusPyException_SetString ("Connection is disconnected - "
409 "unable to make method call");
412 return DBusPyPendingCall_ConsumeDBusPendingCall(pending
, callable
);
415 /* Again, the timeout is in seconds, since that's conventional in Python. */
416 PyDoc_STRVAR(Connection_send_message_with_reply_and_block__doc__
,
417 "send_message_with_reply_and_block(msg, timeout_s=-1)"
418 " -> dbus.lowlevel.Message\n\n"
419 "Send the message and block while waiting for a reply.\n"
421 "This does not re-enter the main loop, so it can lead to a deadlock, if\n"
422 "the called method tries to make a synchronous call to a method in this\n"
423 "application. As such, it's probably a bad idea.\n"
426 " `msg` : dbus.lowlevel.Message\n"
427 " The message to be sent\n"
428 " `timeout_s` : float\n"
429 " If the reply takes more than this many seconds, a timeout error\n"
430 " will be created locally and raised instead. If this timeout is\n"
431 " negative (default), a sane default (supplied by libdbus) is used.\n"
433 " A `dbus.lowlevel.Message` instance (probably a `dbus.lowlevel.MethodReturnMessage`) on success\n"
434 ":Raises dbus.DBusException:\n"
435 " On error (including if the reply arrives but is an\n"
440 Connection_send_message_with_reply_and_block(Connection
*self
, PyObject
*args
)
442 double timeout_s
= -1.0;
445 DBusMessage
*msg
, *reply
;
449 DBUS_PY_RAISE_VIA_NULL_IF_FAIL(self
->conn
);
450 if (!PyArg_ParseTuple(args
, "O|d:send_message_with_reply_and_block", &obj
,
455 msg
= DBusPyMessage_BorrowDBusMessage(obj
);
456 if (!msg
) return NULL
;
462 if (timeout_s
> ((double)INT_MAX
) / 1000.0) {
463 PyErr_SetString(PyExc_ValueError
, "Timeout too long");
466 timeout_ms
= (int)(timeout_s
* 1000.0);
469 dbus_error_init(&error
);
470 Py_BEGIN_ALLOW_THREADS
471 reply
= dbus_connection_send_with_reply_and_block(self
->conn
, msg
,
475 /* FIXME: if we instead used send_with_reply and blocked on the resulting
476 * PendingCall, then we could get all args from the error, not just
479 return DBusPyException_ConsumeError(&error
);
481 return DBusPyMessage_ConsumeDBusMessage(reply
);
484 PyDoc_STRVAR(Connection_flush__doc__
,
486 "Block until the outgoing message queue is empty.\n");
488 Connection_flush (Connection
*self
, PyObject
*args UNUSED
)
491 DBUS_PY_RAISE_VIA_NULL_IF_FAIL(self
->conn
);
492 Py_BEGIN_ALLOW_THREADS
493 dbus_connection_flush (self
->conn
);
499 * dbus_connection_preallocate_send
500 * dbus_connection_free_preallocated_send
501 * dbus_connection_send_preallocated
502 * dbus_connection_borrow_message
503 * dbus_connection_return_message
504 * dbus_connection_steal_borrowed_message
505 * dbus_connection_pop_message
508 /* Non-main-loop handling not yet implemented: */
509 /* dbus_connection_read_write_dispatch */
510 /* dbus_connection_read_write */
512 /* Main loop handling not yet implemented: */
513 /* dbus_connection_get_dispatch_status */
514 /* dbus_connection_dispatch */
515 /* dbus_connection_set_watch_functions */
516 /* dbus_connection_set_timeout_functions */
517 /* dbus_connection_set_wakeup_main_function */
518 /* dbus_connection_set_dispatch_status_function */
520 /* Normally in Python this would be called fileno(), but I don't want to
521 * encourage people to select() on it */
522 PyDoc_STRVAR(Connection_get_unix_fd__doc__
,
523 "get_unix_fd() -> int or None\n\n"
524 "Get the connection's UNIX file descriptor, if any.\n\n"
525 "This can be used for SELinux access control checks with ``getpeercon()``\n"
526 "for example. **Do not** read or write to the file descriptor, or try to\n"
527 "``select()`` on it.\n");
529 Connection_get_unix_fd (Connection
*self
, PyObject
*unused UNUSED
)
535 DBUS_PY_RAISE_VIA_NULL_IF_FAIL(self
->conn
);
536 Py_BEGIN_ALLOW_THREADS
537 ok
= dbus_connection_get_unix_fd (self
->conn
, &fd
);
539 if (!ok
) Py_RETURN_NONE
;
540 return PyInt_FromLong(fd
);
543 PyDoc_STRVAR(Connection_get_peer_unix_user__doc__
,
544 "get_peer_unix_user() -> long or None\n\n"
545 "Get the UNIX user ID at the other end of the connection, if it has been\n"
546 "authenticated. Return None if this is a non-UNIX platform or the\n"
547 "connection has not been authenticated.\n");
549 Connection_get_peer_unix_user (Connection
*self
, PyObject
*unused UNUSED
)
555 DBUS_PY_RAISE_VIA_NULL_IF_FAIL(self
->conn
);
556 Py_BEGIN_ALLOW_THREADS
557 ok
= dbus_connection_get_unix_user (self
->conn
, &uid
);
559 if (!ok
) Py_RETURN_NONE
;
560 return PyLong_FromUnsignedLong (uid
);
563 PyDoc_STRVAR(Connection_get_peer_unix_process_id__doc__
,
564 "get_peer_unix_process_id() -> long or None\n\n"
565 "Get the UNIX process ID at the other end of the connection, if it has been\n"
566 "authenticated. Return None if this is a non-UNIX platform or the\n"
567 "connection has not been authenticated.\n");
569 Connection_get_peer_unix_process_id (Connection
*self
, PyObject
*unused UNUSED
)
575 DBUS_PY_RAISE_VIA_NULL_IF_FAIL(self
->conn
);
576 Py_BEGIN_ALLOW_THREADS
577 ok
= dbus_connection_get_unix_process_id (self
->conn
, &pid
);
579 if (!ok
) Py_RETURN_NONE
;
580 return PyLong_FromUnsignedLong (pid
);
583 /* TODO: wrap dbus_connection_set_unix_user_function Pythonically */
585 PyDoc_STRVAR(Connection_add_message_filter__doc__
,
586 "add_message_filter(callable)\n\n"
587 "Add the given message filter to the internal list.\n\n"
588 "Filters are handlers that are run on all incoming messages, prior to the\n"
589 "objects registered to handle object paths.\n"
591 "Filters are run in the order that they were added. The same handler can\n"
592 "be added as a filter more than once, in which case it will be run more\n"
593 "than once. Filters added during a filter callback won't be run on the\n"
594 "message being processed.\n"
597 Connection_add_message_filter(Connection
*self
, PyObject
*callable
)
602 DBUS_PY_RAISE_VIA_NULL_IF_FAIL(self
->conn
);
603 /* The callable must be referenced by ->filters *before* it is
604 * given to libdbus, which does not own a reference to it.
606 if (PyList_Append(self
->filters
, callable
) < 0) {
610 Py_BEGIN_ALLOW_THREADS
611 ok
= dbus_connection_add_filter(self
->conn
, _filter_message
, callable
,
616 Py_XDECREF(PyObject_CallMethod(self
->filters
, "remove", "(O)",
624 PyDoc_STRVAR(Connection_remove_message_filter__doc__
,
625 "remove_message_filter(callable)\n\n"
626 "Remove the given message filter (see `add_message_filter` for details).\n"
628 ":Raises LookupError:\n"
629 " The given callable is not among the registered filters\n");
631 Connection_remove_message_filter(Connection
*self
, PyObject
*callable
)
636 DBUS_PY_RAISE_VIA_NULL_IF_FAIL(self
->conn
);
637 /* It's safe to do this before removing it from libdbus, because
638 * the presence of callable in our arguments means we have a ref
640 obj
= PyObject_CallMethod(self
->filters
, "remove", "(O)", callable
);
641 if (!obj
) return NULL
;
644 Py_BEGIN_ALLOW_THREADS
645 dbus_connection_remove_filter(self
->conn
, _filter_message
, callable
);
651 PyDoc_STRVAR(Connection__register_object_path__doc__
,
652 "register_object_path(path, on_message, on_unregister=None, fallback=False)\n"
654 "Register a callback to be called when messages arrive at the given\n"
655 "object-path. Used to export objects' methods on the bus in a low-level\n"
656 "way. For the high-level interface to this functionality (usually\n"
657 "recommended) see the `dbus.service.Object` base class.\n"
661 " Object path to be acted on\n"
662 " `on_message` : callable\n"
663 " Called when a message arrives at the given object-path, with\n"
664 " two positional parameters: the first is this Connection,\n"
665 " the second is the incoming `dbus.lowlevel.Message`.\n"
666 " `on_unregister` : callable or None\n"
667 " If not None, called when the callback is unregistered.\n"
668 " `fallback` : bool\n"
669 " If True (the default is False), when a message arrives for a\n"
670 " 'subdirectory' of the given path and there is no more specific\n"
671 " handler, use this handler. Normally this handler is only run if\n"
672 " the paths match exactly.\n"
675 Connection__register_object_path(Connection
*self
, PyObject
*args
,
680 PyObject
*callbacks
, *path
, *tuple
, *on_message
, *on_unregister
= Py_None
;
681 static char *argnames
[] = {"path", "on_message", "on_unregister",
685 DBUS_PY_RAISE_VIA_NULL_IF_FAIL(self
->conn
);
686 if (!Connection__require_main_loop(self
, NULL
)) {
689 if (!PyArg_ParseTupleAndKeywords(args
, kwargs
,
690 "OO|Oi:_register_object_path",
693 &on_message
, &on_unregister
,
694 &fallback
)) return NULL
;
696 /* Take a reference to path, which we give away to libdbus in a moment.
698 Also, path needs to be a string (not a subclass which could do something
699 mad) to preserve the desirable property that the DBusConnection can
700 never strongly reference the Connection, even indirectly.
702 if (PyString_CheckExact(path
)) {
705 else if (PyUnicode_Check(path
)) {
706 path
= PyUnicode_AsUTF8String(path
);
707 if (!path
) return NULL
;
709 else if (PyString_Check(path
)) {
710 path
= PyString_FromString(PyString_AS_STRING(path
));
711 if (!path
) return NULL
;
714 PyErr_SetString(PyExc_TypeError
, "path must be a str or unicode object");
718 if (!dbus_py_validate_object_path(PyString_AS_STRING(path
))) {
723 tuple
= Py_BuildValue("(OO)", on_unregister
, on_message
);
729 /* Guard against registering a handler that already exists. */
730 callbacks
= PyDict_GetItem(self
->object_paths
, path
);
731 if (callbacks
&& callbacks
!= Py_None
) {
732 PyErr_Format(PyExc_KeyError
, "Can't register the object-path "
733 "handler for '%s': there is already a handler",
734 PyString_AS_STRING(path
));
740 /* Pre-allocate a slot in the dictionary, so we know we'll be able
741 * to replace it with the callbacks without OOM.
742 * This ensures we can keep libdbus' opinion of whether those
743 * paths are handled in sync with our own. */
744 if (PyDict_SetItem(self
->object_paths
, path
, Py_None
) < 0) {
750 Py_BEGIN_ALLOW_THREADS
752 ok
= dbus_connection_register_fallback(self
->conn
,
753 PyString_AS_STRING(path
),
754 &_object_path_vtable
,
758 ok
= dbus_connection_register_object_path(self
->conn
,
759 PyString_AS_STRING(path
),
760 &_object_path_vtable
,
766 if (PyDict_SetItem(self
->object_paths
, path
, tuple
) < 0) {
767 /* That shouldn't have happened, we already allocated enough
768 memory for it. Oh well, try to undo the registration to keep
769 things in sync. If this fails too, we've leaked a bit of
770 memory in libdbus, but tbh we should never get here anyway. */
771 Py_BEGIN_ALLOW_THREADS
772 ok
= dbus_connection_unregister_object_path(self
->conn
,
773 PyString_AS_STRING(path
));
777 /* don't DECREF path: libdbus owns a ref now */
782 /* Oops, OOM. Tidy up, if we can, ignoring any error. */
783 PyDict_DelItem(self
->object_paths
, path
);
792 PyDoc_STRVAR(Connection__unregister_object_path__doc__
,
793 "unregister_object_path(path)\n\n"
794 "Remove a previously registered handler for the given object path.\n"
798 " The object path whose handler is to be removed\n"
799 ":Raises KeyError: if there is no handler registered for exactly that\n"
803 Connection__unregister_object_path(Connection
*self
, PyObject
*args
,
809 static char *argnames
[] = {"path", NULL
};
812 DBUS_PY_RAISE_VIA_NULL_IF_FAIL(self
->conn
);
813 if (!PyArg_ParseTupleAndKeywords(args
, kwargs
,
814 "O:_unregister_object_path",
815 argnames
, &path
)) return NULL
;
817 /* Take a ref to the path. Same comments as for _register_object_path. */
818 if (PyString_CheckExact(path
)) {
821 else if (PyUnicode_Check(path
)) {
822 path
= PyUnicode_AsUTF8String(path
);
823 if (!path
) return NULL
;
825 else if (PyString_Check(path
)) {
826 path
= PyString_FromString(PyString_AS_STRING(path
));
827 if (!path
) return NULL
;
830 PyErr_SetString(PyExc_TypeError
, "path must be a str or unicode object");
834 /* Guard against unregistering a handler that doesn't, in fact, exist,
835 or whose unregistration is already in progress. */
836 callbacks
= PyDict_GetItem(self
->object_paths
, path
);
837 if (!callbacks
|| callbacks
== Py_None
) {
838 PyErr_Format(PyExc_KeyError
, "Can't unregister the object-path "
839 "handler for '%s': there is no such handler",
840 PyString_AS_STRING(path
));
845 /* Hang on to a reference to the callbacks for the moment. */
846 Py_INCREF(callbacks
);
848 /* Get rid of the object-path while we still have the GIL, to
849 guard against unregistering twice from different threads (which
850 causes undefined behaviour in libdbus).
852 Because deletion would make it possible for the re-insertion below
853 to fail, we instead set the handler to None as a placeholder.
855 if (PyDict_SetItem(self
->object_paths
, path
, Py_None
) < 0) {
856 /* If that failed, there's no need to be paranoid as below - the
857 callbacks are still set, so we failed, but at least everything
859 Py_DECREF(callbacks
);
865 This is something of a critical section - the dict of object-paths
866 and libdbus' internal structures are out of sync for a bit. We have
867 to be able to cope with that.
869 It's really annoying that dbus_connection_unregister_object_path
870 can fail, *and* has undefined behaviour if the object path has
871 already been unregistered. Either/or would be fine.
874 Py_BEGIN_ALLOW_THREADS
875 ok
= dbus_connection_unregister_object_path(self
->conn
,
876 PyString_AS_STRING(path
));
880 Py_DECREF(callbacks
);
881 PyDict_DelItem(self
->object_paths
, path
);
882 /* END PARANOIA on successful code path */
883 /* The above can't fail unless by some strange trickery the key is no
884 longer present. Ignore any errors. */
890 /* Oops, OOM. Put the callbacks back in the dict so
891 * we'll have another go if/when the user frees some memory
892 * and tries calling this method again. */
893 PyDict_SetItem(self
->object_paths
, path
, callbacks
);
894 /* END PARANOIA on failing code path */
895 /* If the SetItem failed, there's nothing we can do about it - but
896 since we know it's an existing entry, it shouldn't be able to fail
899 Py_DECREF(callbacks
);
900 return PyErr_NoMemory();
904 PyDoc_STRVAR(Connection_list_exported_child_objects__doc__
,
905 "list_exported_child_objects(path: str) -> list of str\n\n"
906 "Return a list of the names of objects exported on this Connection as\n"
907 "direct children of the given object path.\n"
909 "Each name returned may be converted to a valid object path using\n"
910 "``dbus.ObjectPath('%s%s%s' % (path, (path != '/' and '/' or ''), name))``.\n"
911 "For the purposes of this function, every parent or ancestor of an exported\n"
912 "object is considered to be an exported object, even if it's only an object\n"
913 "synthesized by the library to support introspection.\n");
915 Connection_list_exported_child_objects (Connection
*self
, PyObject
*args
,
919 char **kids
, **kid_ptr
;
922 static char *argnames
[] = {"path", NULL
};
924 DBUS_PY_RAISE_VIA_NULL_IF_FAIL(self
->conn
);
925 if (!PyArg_ParseTupleAndKeywords(args
, kwargs
, "s", argnames
, &path
)) {
929 if (!dbus_py_validate_object_path(path
)) {
933 Py_BEGIN_ALLOW_THREADS
934 ok
= dbus_connection_list_registered(self
->conn
, path
, &kids
);
938 return PyErr_NoMemory();
945 for (kid_ptr
= kids
; *kid_ptr
; kid_ptr
++) {
946 PyObject
*tmp
= PyString_FromString(*kid_ptr
);
952 if (PyList_Append(ret
, tmp
) < 0) {
960 dbus_free_string_array(kids
);
965 /* dbus_connection_get_object_path_data - not useful to Python,
966 * the object path data is just a PyString containing the path */
967 /* dbus_connection_list_registered could be useful, though */
969 /* dbus_connection_set_change_sigpipe - sets global state */
971 /* Maxima. Does Python code ever need to manipulate these?
972 * OTOH they're easy to wrap */
973 /* dbus_connection_set_max_message_size */
974 /* dbus_connection_get_max_message_size */
975 /* dbus_connection_set_max_received_size */
976 /* dbus_connection_get_max_received_size */
978 /* dbus_connection_get_outgoing_size - almost certainly unneeded */
980 PyDoc_STRVAR(new_for_bus__doc__
,
981 "Connection._new_for_bus([address: str or int]) -> Connection\n"
983 "If the address is an int it must be one of the constants BUS_SESSION,\n"
984 "BUS_SYSTEM, BUS_STARTER; if a string, it must be a D-Bus address.\n"
985 "The default is BUS_SESSION.\n"
988 PyDoc_STRVAR(get_unique_name__doc__
,
989 "get_unique_name() -> str\n\n"
990 "Return this application's unique name on this bus.\n"
992 ":Raises DBusException: if the connection has no unique name yet\n"
993 " (for Bus objects this can't happen, for peer-to-peer connections\n"
994 " this means you haven't called `set_unique_name`)\n");
996 PyDoc_STRVAR(set_unique_name__doc__
,
997 "set_unique_name(str)\n\n"
998 "Set this application's unique name on this bus. Raise ValueError if it has\n"
999 "already been set.\n");
1001 struct PyMethodDef DBusPyConnection_tp_methods
[] = {
1002 #define ENTRY(name, flags) {#name, (PyCFunction)Connection_##name, flags, Connection_##name##__doc__}
1003 ENTRY(_require_main_loop
, METH_NOARGS
),
1004 ENTRY(close
, METH_NOARGS
),
1005 ENTRY(flush
, METH_NOARGS
),
1006 ENTRY(get_is_connected
, METH_NOARGS
),
1007 ENTRY(get_is_authenticated
, METH_NOARGS
),
1008 ENTRY(set_exit_on_disconnect
, METH_VARARGS
),
1009 ENTRY(get_unix_fd
, METH_NOARGS
),
1010 ENTRY(get_peer_unix_user
, METH_NOARGS
),
1011 ENTRY(get_peer_unix_process_id
, METH_NOARGS
),
1012 ENTRY(add_message_filter
, METH_O
),
1013 ENTRY(_register_object_path
, METH_VARARGS
|METH_KEYWORDS
),
1014 ENTRY(remove_message_filter
, METH_O
),
1015 ENTRY(send_message
, METH_VARARGS
),
1016 ENTRY(send_message_with_reply
, METH_VARARGS
|METH_KEYWORDS
),
1017 ENTRY(send_message_with_reply_and_block
, METH_VARARGS
),
1018 ENTRY(_unregister_object_path
, METH_VARARGS
|METH_KEYWORDS
),
1019 ENTRY(list_exported_child_objects
, METH_VARARGS
|METH_KEYWORDS
),
1020 {"_new_for_bus", (PyCFunction
)DBusPyConnection_NewForBus
,
1021 METH_CLASS
|METH_VARARGS
|METH_KEYWORDS
,
1022 new_for_bus__doc__
},
1023 {"get_unique_name", (PyCFunction
)DBusPyConnection_GetUniqueName
,
1025 get_unique_name__doc__
},
1026 {"set_unique_name", (PyCFunction
)DBusPyConnection_SetUniqueName
,
1028 set_unique_name__doc__
},
1033 /* vim:set ft=c cino< sw=4 sts=4 et: */