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"
31 _object_path_unregister(DBusConnection
*conn
, void *user_data
)
33 PyGILState_STATE gil
= PyGILState_Ensure();
34 PyObject
*tuple
= NULL
;
35 Connection
*conn_obj
= NULL
;
38 conn_obj
= (Connection
*)DBusPyConnection_ExistingFromDBusConnection(conn
);
39 if (!conn_obj
) goto out
;
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
);
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
));
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()) {
65 PyGILState_Release(gil
);
68 static DBusHandlerResult
69 _object_path_message(DBusConnection
*conn
, DBusMessage
*message
,
72 DBusHandlerResult ret
;
73 PyGILState_STATE gil
= PyGILState_Ensure();
74 Connection
*conn_obj
= NULL
;
75 PyObject
*tuple
= NULL
;
77 PyObject
*callable
; /* borrowed */
79 dbus_message_ref(message
);
80 msg_obj
= DBusPyMessage_ConsumeDBusMessage(message
);
82 ret
= DBUS_HANDLER_RESULT_NEED_MEMORY
;
86 conn_obj
= (Connection
*)DBusPyConnection_ExistingFromDBusConnection(conn
);
88 ret
= DBUS_HANDLER_RESULT_NOT_YET_HANDLED
;
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
;
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);
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
;
116 DBG("%s", "... and we have a message handler for that object path");
117 ret
= DBusPyConnection_HandleMessage(conn_obj
, msg_obj
, callable
);
122 Py_XDECREF(conn_obj
);
124 if (PyErr_Occurred()) {
127 PyGILState_Release(gil
);
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
;
144 #ifndef DBUS_PYTHON_DISABLE_CHECKS
148 dbus_message_ref(message
);
149 msg_obj
= DBusPyMessage_ConsumeDBusMessage(message
);
151 DBG("%s", "OOM while trying to construct Message");
152 ret
= DBUS_HANDLER_RESULT_NEED_MEMORY
;
156 conn_obj
= (Connection
*)DBusPyConnection_ExistingFromDBusConnection(conn
);
158 DBG("%s", "failed to traverse DBusConnection -> Connection weakref");
159 ret
= DBUS_HANDLER_RESULT_NOT_YET_HANDLED
;
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
;
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
) {
189 DBG("... filter %p has vanished from ->filters, so not calling it",
191 ret
= DBUS_HANDLER_RESULT_NOT_YET_HANDLED
;
196 ret
= DBusPyConnection_HandleMessage(conn_obj
, msg_obj
, callable
);
199 Py_XDECREF(conn_obj
);
200 Py_XDECREF(callable
);
201 PyGILState_Release(gil
);
205 PyDoc_STRVAR(Connection__require_main_loop__doc__
,
206 "_require_main_loop()\n\n"
207 "Raise an exception if this Connection is not bound to any main loop -\n"
208 "in this state, asynchronous calls, receiving signals and exporting objects\n"
211 "`dbus.mainloop.NULL_MAIN_LOOP` is treated like a valid main loop - if you're\n"
212 "using that, you presumably know what you're doing.\n");
214 Connection__require_main_loop (Connection
*self
, PyObject
*args UNUSED
)
216 if (!self
->has_mainloop
) {
217 PyErr_SetString(PyExc_RuntimeError
,
218 "To make asynchronous calls, receive signals or "
219 "export objects, D-Bus connections must be attached "
220 "to a main loop by passing mainloop=... to the "
221 "constructor or calling "
222 "dbus.set_default_main_loop(...)");
228 PyDoc_STRVAR(Connection_close__doc__
,
230 "Close the connection.");
232 Connection_close (Connection
*self
, PyObject
*args UNUSED
)
235 /* Because the user explicitly asked to close the connection, we'll even
236 let them close shared connections. */
238 Py_BEGIN_ALLOW_THREADS
239 dbus_connection_close(self
->conn
);
245 PyDoc_STRVAR(Connection_get_is_connected__doc__
,
246 "get_is_connected() -> bool\n\n"
247 "Return true if this Connection is connected.\n");
249 Connection_get_is_connected (Connection
*self
, PyObject
*args UNUSED
)
254 DBUS_PY_RAISE_VIA_NULL_IF_FAIL(self
->conn
);
255 Py_BEGIN_ALLOW_THREADS
256 ret
= dbus_connection_get_is_connected(self
->conn
);
258 return PyBool_FromLong(ret
);
261 PyDoc_STRVAR(Connection_get_is_authenticated__doc__
,
262 "get_is_authenticated() -> bool\n\n"
263 "Return true if this Connection was ever authenticated.\n");
265 Connection_get_is_authenticated (Connection
*self
, PyObject
*args UNUSED
)
270 DBUS_PY_RAISE_VIA_NULL_IF_FAIL(self
->conn
);
271 Py_BEGIN_ALLOW_THREADS
272 ret
= dbus_connection_get_is_authenticated(self
->conn
);
274 return PyBool_FromLong(ret
);
277 PyDoc_STRVAR(Connection_set_exit_on_disconnect__doc__
,
278 "set_exit_on_disconnect(bool)\n\n"
279 "Set whether the C function ``_exit`` will be called when this Connection\n"
280 "becomes disconnected. This will cause the program to exit without calling\n"
281 "any cleanup code or exit handlers.\n"
283 "The default is for this feature to be disabled for Connections and enabled\n"
286 Connection_set_exit_on_disconnect (Connection
*self
, PyObject
*args
)
288 int exit_on_disconnect
;
291 DBUS_PY_RAISE_VIA_NULL_IF_FAIL(self
->conn
);
292 if (!PyArg_ParseTuple(args
, "i:set_exit_on_disconnect",
293 &exit_on_disconnect
)) {
296 Py_BEGIN_ALLOW_THREADS
297 dbus_connection_set_exit_on_disconnect(self
->conn
,
298 exit_on_disconnect
? 1 : 0);
303 PyDoc_STRVAR(Connection_send_message__doc__
,
304 "send_message(msg) -> long\n\n"
305 "Queue the given message for sending, and return the message serial number.\n"
308 " `msg` : dbus.lowlevel.Message\n"
309 " The message to be sent.\n"
312 Connection_send_message(Connection
*self
, PyObject
*args
)
317 dbus_uint32_t serial
;
320 DBUS_PY_RAISE_VIA_NULL_IF_FAIL(self
->conn
);
321 if (!PyArg_ParseTuple(args
, "O", &obj
)) return NULL
;
323 msg
= DBusPyMessage_BorrowDBusMessage(obj
);
324 if (!msg
) return NULL
;
326 Py_BEGIN_ALLOW_THREADS
327 ok
= dbus_connection_send(self
->conn
, msg
, &serial
);
331 return PyErr_NoMemory();
334 return PyLong_FromUnsignedLong(serial
);
337 /* The timeout is in seconds here, since that's conventional in Python. */
338 PyDoc_STRVAR(Connection_send_message_with_reply__doc__
,
339 "send_message_with_reply(msg, reply_handler, timeout_s=-1, "
340 "require_main_loop=False) -> dbus.lowlevel.PendingCall\n\n"
341 "Queue the message for sending; expect a reply via the returned PendingCall,\n"
342 "which can also be used to cancel the pending call.\n"
345 " `msg` : dbus.lowlevel.Message\n"
346 " The message to be sent\n"
347 " `reply_handler` : callable\n"
348 " Asynchronous reply handler: will be called with one positional\n"
349 " parameter, a Message instance representing the reply.\n"
350 " `timeout_s` : float\n"
351 " If the reply takes more than this many seconds, a timeout error\n"
352 " will be created locally and raised instead. If this timeout is\n"
353 " negative (default), a sane default (supplied by libdbus) is used.\n"
354 " `require_main_loop` : bool\n"
355 " If True, raise RuntimeError if this Connection does not have a main\n"
356 " loop configured. If False (default) and there is no main loop, you are\n"
357 " responsible for calling block() on the PendingCall.\n"
361 Connection_send_message_with_reply(Connection
*self
, PyObject
*args
, PyObject
*kw
)
364 double timeout_s
= -1.0;
366 PyObject
*obj
, *callable
;
368 DBusPendingCall
*pending
;
369 int require_main_loop
= 0;
370 static char *argnames
[] = {"msg", "reply_handler", "timeout_s",
371 "require_main_loop", NULL
};
374 DBUS_PY_RAISE_VIA_NULL_IF_FAIL(self
->conn
);
375 if (!PyArg_ParseTupleAndKeywords(args
, kw
,
376 "OO|di:send_message_with_reply",
378 &obj
, &callable
, &timeout_s
,
379 &require_main_loop
)) {
382 if (require_main_loop
&& !Connection__require_main_loop(self
, NULL
)) {
386 msg
= DBusPyMessage_BorrowDBusMessage(obj
);
387 if (!msg
) return NULL
;
393 if (timeout_s
> ((double)INT_MAX
) / 1000.0) {
394 PyErr_SetString(PyExc_ValueError
, "Timeout too long");
397 timeout_ms
= (int)(timeout_s
* 1000.0);
400 Py_BEGIN_ALLOW_THREADS
401 ok
= dbus_connection_send_with_reply(self
->conn
, msg
, &pending
,
406 return PyErr_NoMemory();
410 /* connection is disconnected (doesn't return FALSE!) */
411 return DBusPyException_SetString ("Connection is disconnected - "
412 "unable to make method call");
415 return DBusPyPendingCall_ConsumeDBusPendingCall(pending
, callable
);
418 /* Again, the timeout is in seconds, since that's conventional in Python. */
419 PyDoc_STRVAR(Connection_send_message_with_reply_and_block__doc__
,
420 "send_message_with_reply_and_block(msg, timeout_s=-1)"
421 " -> dbus.lowlevel.Message\n\n"
422 "Send the message and block while waiting for a reply.\n"
424 "This does not re-enter the main loop, so it can lead to a deadlock, if\n"
425 "the called method tries to make a synchronous call to a method in this\n"
426 "application. As such, it's probably a bad idea.\n"
429 " `msg` : dbus.lowlevel.Message\n"
430 " The message to be sent\n"
431 " `timeout_s` : float\n"
432 " If the reply takes more than this many seconds, a timeout error\n"
433 " will be created locally and raised instead. If this timeout is\n"
434 " negative (default), a sane default (supplied by libdbus) is used.\n"
436 " A `dbus.lowlevel.Message` instance (probably a `dbus.lowlevel.MethodReturnMessage`) on success\n"
437 ":Raises dbus.DBusException:\n"
438 " On error (including if the reply arrives but is an\n"
443 Connection_send_message_with_reply_and_block(Connection
*self
, PyObject
*args
)
445 double timeout_s
= -1.0;
448 DBusMessage
*msg
, *reply
;
452 DBUS_PY_RAISE_VIA_NULL_IF_FAIL(self
->conn
);
453 if (!PyArg_ParseTuple(args
, "O|d:send_message_with_reply_and_block", &obj
,
458 msg
= DBusPyMessage_BorrowDBusMessage(obj
);
459 if (!msg
) return NULL
;
465 if (timeout_s
> ((double)INT_MAX
) / 1000.0) {
466 PyErr_SetString(PyExc_ValueError
, "Timeout too long");
469 timeout_ms
= (int)(timeout_s
* 1000.0);
472 dbus_error_init(&error
);
473 Py_BEGIN_ALLOW_THREADS
474 reply
= dbus_connection_send_with_reply_and_block(self
->conn
, msg
,
478 /* FIXME: if we instead used send_with_reply and blocked on the resulting
479 * PendingCall, then we could get all args from the error, not just
482 return DBusPyException_ConsumeError(&error
);
484 return DBusPyMessage_ConsumeDBusMessage(reply
);
487 PyDoc_STRVAR(Connection_flush__doc__
,
489 "Block until the outgoing message queue is empty.\n");
491 Connection_flush (Connection
*self
, PyObject
*args UNUSED
)
494 DBUS_PY_RAISE_VIA_NULL_IF_FAIL(self
->conn
);
495 Py_BEGIN_ALLOW_THREADS
496 dbus_connection_flush (self
->conn
);
502 * dbus_connection_preallocate_send
503 * dbus_connection_free_preallocated_send
504 * dbus_connection_send_preallocated
505 * dbus_connection_borrow_message
506 * dbus_connection_return_message
507 * dbus_connection_steal_borrowed_message
508 * dbus_connection_pop_message
511 /* Non-main-loop handling not yet implemented: */
512 /* dbus_connection_read_write_dispatch */
513 /* dbus_connection_read_write */
515 /* Main loop handling not yet implemented: */
516 /* dbus_connection_get_dispatch_status */
517 /* dbus_connection_dispatch */
518 /* dbus_connection_set_watch_functions */
519 /* dbus_connection_set_timeout_functions */
520 /* dbus_connection_set_wakeup_main_function */
521 /* dbus_connection_set_dispatch_status_function */
523 /* Normally in Python this would be called fileno(), but I don't want to
524 * encourage people to select() on it */
525 PyDoc_STRVAR(Connection_get_unix_fd__doc__
,
526 "get_unix_fd() -> int or None\n\n"
527 "Get the connection's UNIX file descriptor, if any.\n\n"
528 "This can be used for SELinux access control checks with ``getpeercon()``\n"
529 "for example. **Do not** read or write to the file descriptor, or try to\n"
530 "``select()`` on it.\n");
532 Connection_get_unix_fd (Connection
*self
, PyObject
*unused UNUSED
)
538 DBUS_PY_RAISE_VIA_NULL_IF_FAIL(self
->conn
);
539 Py_BEGIN_ALLOW_THREADS
540 ok
= dbus_connection_get_unix_fd (self
->conn
, &fd
);
542 if (!ok
) Py_RETURN_NONE
;
543 return PyInt_FromLong(fd
);
546 PyDoc_STRVAR(Connection_get_peer_unix_user__doc__
,
547 "get_peer_unix_user() -> long or None\n\n"
548 "Get the UNIX user ID at the other end of the connection, if it has been\n"
549 "authenticated. Return None if this is a non-UNIX platform or the\n"
550 "connection has not been authenticated.\n");
552 Connection_get_peer_unix_user (Connection
*self
, PyObject
*unused UNUSED
)
558 DBUS_PY_RAISE_VIA_NULL_IF_FAIL(self
->conn
);
559 Py_BEGIN_ALLOW_THREADS
560 ok
= dbus_connection_get_unix_user (self
->conn
, &uid
);
562 if (!ok
) Py_RETURN_NONE
;
563 return PyLong_FromUnsignedLong (uid
);
566 PyDoc_STRVAR(Connection_get_peer_unix_process_id__doc__
,
567 "get_peer_unix_process_id() -> long or None\n\n"
568 "Get the UNIX process ID at the other end of the connection, if it has been\n"
569 "authenticated. Return None if this is a non-UNIX platform or the\n"
570 "connection has not been authenticated.\n");
572 Connection_get_peer_unix_process_id (Connection
*self
, PyObject
*unused UNUSED
)
578 DBUS_PY_RAISE_VIA_NULL_IF_FAIL(self
->conn
);
579 Py_BEGIN_ALLOW_THREADS
580 ok
= dbus_connection_get_unix_process_id (self
->conn
, &pid
);
582 if (!ok
) Py_RETURN_NONE
;
583 return PyLong_FromUnsignedLong (pid
);
586 /* TODO: wrap dbus_connection_set_unix_user_function Pythonically */
588 PyDoc_STRVAR(Connection_add_message_filter__doc__
,
589 "add_message_filter(callable)\n\n"
590 "Add the given message filter to the internal list.\n\n"
591 "Filters are handlers that are run on all incoming messages, prior to the\n"
592 "objects registered to handle object paths.\n"
594 "Filters are run in the order that they were added. The same handler can\n"
595 "be added as a filter more than once, in which case it will be run more\n"
596 "than once. Filters added during a filter callback won't be run on the\n"
597 "message being processed.\n"
600 Connection_add_message_filter(Connection
*self
, PyObject
*callable
)
605 DBUS_PY_RAISE_VIA_NULL_IF_FAIL(self
->conn
);
606 /* The callable must be referenced by ->filters *before* it is
607 * given to libdbus, which does not own a reference to it.
609 if (PyList_Append(self
->filters
, callable
) < 0) {
613 Py_BEGIN_ALLOW_THREADS
614 ok
= dbus_connection_add_filter(self
->conn
, _filter_message
, callable
,
619 Py_XDECREF(PyObject_CallMethod(self
->filters
, "remove", "(O)",
627 PyDoc_STRVAR(Connection_remove_message_filter__doc__
,
628 "remove_message_filter(callable)\n\n"
629 "Remove the given message filter (see `add_message_filter` for details).\n"
631 ":Raises LookupError:\n"
632 " The given callable is not among the registered filters\n");
634 Connection_remove_message_filter(Connection
*self
, PyObject
*callable
)
639 DBUS_PY_RAISE_VIA_NULL_IF_FAIL(self
->conn
);
640 /* It's safe to do this before removing it from libdbus, because
641 * the presence of callable in our arguments means we have a ref
643 obj
= PyObject_CallMethod(self
->filters
, "remove", "(O)", callable
);
644 if (!obj
) return NULL
;
647 Py_BEGIN_ALLOW_THREADS
648 dbus_connection_remove_filter(self
->conn
, _filter_message
, callable
);
654 PyDoc_STRVAR(Connection__register_object_path__doc__
,
655 "register_object_path(path, on_message, on_unregister=None, fallback=False)\n"
657 "Register a callback to be called when messages arrive at the given\n"
658 "object-path. Used to export objects' methods on the bus in a low-level\n"
659 "way. For the high-level interface to this functionality (usually\n"
660 "recommended) see the `dbus.service.Object` base class.\n"
664 " Object path to be acted on\n"
665 " `on_message` : callable\n"
666 " Called when a message arrives at the given object-path, with\n"
667 " two positional parameters: the first is this Connection,\n"
668 " the second is the incoming `dbus.lowlevel.Message`.\n"
669 " `on_unregister` : callable or None\n"
670 " If not None, called when the callback is unregistered.\n"
671 " `fallback` : bool\n"
672 " If True (the default is False), when a message arrives for a\n"
673 " 'subdirectory' of the given path and there is no more specific\n"
674 " handler, use this handler. Normally this handler is only run if\n"
675 " the paths match exactly.\n"
678 Connection__register_object_path(Connection
*self
, PyObject
*args
,
683 PyObject
*callbacks
, *path
, *tuple
, *on_message
, *on_unregister
= Py_None
;
684 static char *argnames
[] = {"path", "on_message", "on_unregister",
688 DBUS_PY_RAISE_VIA_NULL_IF_FAIL(self
->conn
);
689 if (!Connection__require_main_loop(self
, NULL
)) {
692 if (!PyArg_ParseTupleAndKeywords(args
, kwargs
,
693 "OO|Oi:_register_object_path",
696 &on_message
, &on_unregister
,
697 &fallback
)) return NULL
;
699 /* Take a reference to path, which we give away to libdbus in a moment.
701 Also, path needs to be a string (not a subclass which could do something
702 mad) to preserve the desirable property that the DBusConnection can
703 never strongly reference the Connection, even indirectly.
705 if (PyString_CheckExact(path
)) {
708 else if (PyUnicode_Check(path
)) {
709 path
= PyUnicode_AsUTF8String(path
);
710 if (!path
) return NULL
;
712 else if (PyString_Check(path
)) {
713 path
= PyString_FromString(PyString_AS_STRING(path
));
714 if (!path
) return NULL
;
717 PyErr_SetString(PyExc_TypeError
, "path must be a str or unicode object");
721 if (!dbus_py_validate_object_path(PyString_AS_STRING(path
))) {
726 tuple
= Py_BuildValue("(OO)", on_unregister
, on_message
);
732 /* Guard against registering a handler that already exists. */
733 callbacks
= PyDict_GetItem(self
->object_paths
, path
);
734 if (callbacks
&& callbacks
!= Py_None
) {
735 PyErr_Format(PyExc_KeyError
, "Can't register the object-path "
736 "handler for '%s': there is already a handler",
737 PyString_AS_STRING(path
));
743 /* Pre-allocate a slot in the dictionary, so we know we'll be able
744 * to replace it with the callbacks without OOM.
745 * This ensures we can keep libdbus' opinion of whether those
746 * paths are handled in sync with our own. */
747 if (PyDict_SetItem(self
->object_paths
, path
, Py_None
) < 0) {
753 Py_BEGIN_ALLOW_THREADS
755 ok
= dbus_connection_register_fallback(self
->conn
,
756 PyString_AS_STRING(path
),
757 &_object_path_vtable
,
761 ok
= dbus_connection_register_object_path(self
->conn
,
762 PyString_AS_STRING(path
),
763 &_object_path_vtable
,
769 if (PyDict_SetItem(self
->object_paths
, path
, tuple
) < 0) {
770 /* That shouldn't have happened, we already allocated enough
771 memory for it. Oh well, try to undo the registration to keep
772 things in sync. If this fails too, we've leaked a bit of
773 memory in libdbus, but tbh we should never get here anyway. */
774 Py_BEGIN_ALLOW_THREADS
775 ok
= dbus_connection_unregister_object_path(self
->conn
,
776 PyString_AS_STRING(path
));
780 /* don't DECREF path: libdbus owns a ref now */
785 /* Oops, OOM. Tidy up, if we can, ignoring any error. */
786 PyDict_DelItem(self
->object_paths
, path
);
795 PyDoc_STRVAR(Connection__unregister_object_path__doc__
,
796 "unregister_object_path(path)\n\n"
797 "Remove a previously registered handler for the given object path.\n"
801 " The object path whose handler is to be removed\n"
802 ":Raises KeyError: if there is no handler registered for exactly that\n"
806 Connection__unregister_object_path(Connection
*self
, PyObject
*args
,
812 static char *argnames
[] = {"path", NULL
};
815 DBUS_PY_RAISE_VIA_NULL_IF_FAIL(self
->conn
);
816 if (!PyArg_ParseTupleAndKeywords(args
, kwargs
,
817 "O:_unregister_object_path",
818 argnames
, &path
)) return NULL
;
820 /* Take a ref to the path. Same comments as for _register_object_path. */
821 if (PyString_CheckExact(path
)) {
824 else if (PyUnicode_Check(path
)) {
825 path
= PyUnicode_AsUTF8String(path
);
826 if (!path
) return NULL
;
828 else if (PyString_Check(path
)) {
829 path
= PyString_FromString(PyString_AS_STRING(path
));
830 if (!path
) return NULL
;
833 PyErr_SetString(PyExc_TypeError
, "path must be a str or unicode object");
837 /* Guard against unregistering a handler that doesn't, in fact, exist,
838 or whose unregistration is already in progress. */
839 callbacks
= PyDict_GetItem(self
->object_paths
, path
);
840 if (!callbacks
|| callbacks
== Py_None
) {
841 PyErr_Format(PyExc_KeyError
, "Can't unregister the object-path "
842 "handler for '%s': there is no such handler",
843 PyString_AS_STRING(path
));
848 /* Hang on to a reference to the callbacks for the moment. */
849 Py_INCREF(callbacks
);
851 /* Get rid of the object-path while we still have the GIL, to
852 guard against unregistering twice from different threads (which
853 causes undefined behaviour in libdbus).
855 Because deletion would make it possible for the re-insertion below
856 to fail, we instead set the handler to None as a placeholder.
858 if (PyDict_SetItem(self
->object_paths
, path
, Py_None
) < 0) {
859 /* If that failed, there's no need to be paranoid as below - the
860 callbacks are still set, so we failed, but at least everything
862 Py_DECREF(callbacks
);
868 This is something of a critical section - the dict of object-paths
869 and libdbus' internal structures are out of sync for a bit. We have
870 to be able to cope with that.
872 It's really annoying that dbus_connection_unregister_object_path
873 can fail, *and* has undefined behaviour if the object path has
874 already been unregistered. Either/or would be fine.
877 Py_BEGIN_ALLOW_THREADS
878 ok
= dbus_connection_unregister_object_path(self
->conn
,
879 PyString_AS_STRING(path
));
883 Py_DECREF(callbacks
);
884 PyDict_DelItem(self
->object_paths
, path
);
885 /* END PARANOIA on successful code path */
886 /* The above can't fail unless by some strange trickery the key is no
887 longer present. Ignore any errors. */
893 /* Oops, OOM. Put the callbacks back in the dict so
894 * we'll have another go if/when the user frees some memory
895 * and tries calling this method again. */
896 PyDict_SetItem(self
->object_paths
, path
, callbacks
);
897 /* END PARANOIA on failing code path */
898 /* If the SetItem failed, there's nothing we can do about it - but
899 since we know it's an existing entry, it shouldn't be able to fail
902 Py_DECREF(callbacks
);
903 return PyErr_NoMemory();
907 PyDoc_STRVAR(Connection_list_exported_child_objects__doc__
,
908 "list_exported_child_objects(path: str) -> list of str\n\n"
909 "Return a list of the names of objects exported on this Connection as\n"
910 "direct children of the given object path.\n"
912 "Each name returned may be converted to a valid object path using\n"
913 "``dbus.ObjectPath('%s%s%s' % (path, (path != '/' and '/' or ''), name))``.\n"
914 "For the purposes of this function, every parent or ancestor of an exported\n"
915 "object is considered to be an exported object, even if it's only an object\n"
916 "synthesized by the library to support introspection.\n");
918 Connection_list_exported_child_objects (Connection
*self
, PyObject
*args
,
922 char **kids
, **kid_ptr
;
925 static char *argnames
[] = {"path", NULL
};
927 DBUS_PY_RAISE_VIA_NULL_IF_FAIL(self
->conn
);
928 if (!PyArg_ParseTupleAndKeywords(args
, kwargs
, "s", argnames
, &path
)) {
932 if (!dbus_py_validate_object_path(path
)) {
936 Py_BEGIN_ALLOW_THREADS
937 ok
= dbus_connection_list_registered(self
->conn
, path
, &kids
);
941 return PyErr_NoMemory();
948 for (kid_ptr
= kids
; *kid_ptr
; kid_ptr
++) {
949 PyObject
*tmp
= PyString_FromString(*kid_ptr
);
955 if (PyList_Append(ret
, tmp
) < 0) {
963 dbus_free_string_array(kids
);
968 /* dbus_connection_get_object_path_data - not useful to Python,
969 * the object path data is just a PyString containing the path */
970 /* dbus_connection_list_registered could be useful, though */
972 /* dbus_connection_set_change_sigpipe - sets global state */
974 /* Maxima. Does Python code ever need to manipulate these?
975 * OTOH they're easy to wrap */
976 /* dbus_connection_set_max_message_size */
977 /* dbus_connection_get_max_message_size */
978 /* dbus_connection_set_max_received_size */
979 /* dbus_connection_get_max_received_size */
981 /* dbus_connection_get_outgoing_size - almost certainly unneeded */
983 PyDoc_STRVAR(new_for_bus__doc__
,
984 "Connection._new_for_bus([address: str or int]) -> Connection\n"
986 "If the address is an int it must be one of the constants BUS_SESSION,\n"
987 "BUS_SYSTEM, BUS_STARTER; if a string, it must be a D-Bus address.\n"
988 "The default is BUS_SESSION.\n"
991 PyDoc_STRVAR(get_unique_name__doc__
,
992 "get_unique_name() -> str\n\n"
993 "Return this application's unique name on this bus.\n"
995 ":Raises DBusException: if the connection has no unique name yet\n"
996 " (for Bus objects this can't happen, for peer-to-peer connections\n"
997 " this means you haven't called `set_unique_name`)\n");
999 PyDoc_STRVAR(set_unique_name__doc__
,
1000 "set_unique_name(str)\n\n"
1001 "Set this application's unique name on this bus. Raise ValueError if it has\n"
1002 "already been set.\n");
1004 struct PyMethodDef DBusPyConnection_tp_methods
[] = {
1005 #define ENTRY(name, flags) {#name, (PyCFunction)Connection_##name, flags, Connection_##name##__doc__}
1006 ENTRY(_require_main_loop
, METH_NOARGS
),
1007 ENTRY(close
, METH_NOARGS
),
1008 ENTRY(flush
, METH_NOARGS
),
1009 ENTRY(get_is_connected
, METH_NOARGS
),
1010 ENTRY(get_is_authenticated
, METH_NOARGS
),
1011 ENTRY(set_exit_on_disconnect
, METH_VARARGS
),
1012 ENTRY(get_unix_fd
, METH_NOARGS
),
1013 ENTRY(get_peer_unix_user
, METH_NOARGS
),
1014 ENTRY(get_peer_unix_process_id
, METH_NOARGS
),
1015 ENTRY(add_message_filter
, METH_O
),
1016 ENTRY(_register_object_path
, METH_VARARGS
|METH_KEYWORDS
),
1017 ENTRY(remove_message_filter
, METH_O
),
1018 ENTRY(send_message
, METH_VARARGS
),
1019 ENTRY(send_message_with_reply
, METH_VARARGS
|METH_KEYWORDS
),
1020 ENTRY(send_message_with_reply_and_block
, METH_VARARGS
),
1021 ENTRY(_unregister_object_path
, METH_VARARGS
|METH_KEYWORDS
),
1022 ENTRY(list_exported_child_objects
, METH_VARARGS
|METH_KEYWORDS
),
1023 {"_new_for_bus", (PyCFunction
)DBusPyConnection_NewForBus
,
1024 METH_CLASS
|METH_VARARGS
|METH_KEYWORDS
,
1025 new_for_bus__doc__
},
1026 {"get_unique_name", (PyCFunction
)DBusPyConnection_GetUniqueName
,
1028 get_unique_name__doc__
},
1029 {"set_unique_name", (PyCFunction
)DBusPyConnection_SetUniqueName
,
1031 set_unique_name__doc__
},
1036 /* vim:set ft=c cino< sw=4 sts=4 et: */