Revert "Make sure extensions are built before docs; get rid of strange inter-director...
[dbus-python-phuang.git] / _dbus_bindings / conn-methods.c
blob6fadc31629e4aec236b488ae0791a2369d3000d1
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);
183 else {
184 callable = NULL;
188 if (!callable) {
189 DBG("... filter %p has vanished from ->filters, so not calling it",
190 user_data);
191 ret = DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
192 goto out;
194 #endif
196 ret = DBusPyConnection_HandleMessage(conn_obj, msg_obj, callable);
197 out:
198 Py_XDECREF(msg_obj);
199 Py_XDECREF(conn_obj);
200 Py_XDECREF(callable);
201 PyGILState_Release(gil);
202 return ret;
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"
209 "will not work.\n"
210 "\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");
213 static PyObject *
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(...)");
223 return NULL;
225 Py_RETURN_NONE;
228 PyDoc_STRVAR(Connection_close__doc__,
229 "close()\n\n"
230 "Close the connection.");
231 static PyObject *
232 Connection_close (Connection *self, PyObject *args UNUSED)
234 TRACE(self);
235 /* Because the user explicitly asked to close the connection, we'll even
236 let them close shared connections. */
237 if (self->conn) {
238 Py_BEGIN_ALLOW_THREADS
239 dbus_connection_close(self->conn);
240 Py_END_ALLOW_THREADS
242 Py_RETURN_NONE;
245 PyDoc_STRVAR(Connection_get_is_connected__doc__,
246 "get_is_connected() -> bool\n\n"
247 "Return true if this Connection is connected.\n");
248 static PyObject *
249 Connection_get_is_connected (Connection *self, PyObject *args UNUSED)
251 dbus_bool_t ret;
253 TRACE(self);
254 DBUS_PY_RAISE_VIA_NULL_IF_FAIL(self->conn);
255 Py_BEGIN_ALLOW_THREADS
256 ret = dbus_connection_get_is_connected(self->conn);
257 Py_END_ALLOW_THREADS
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");
264 static PyObject *
265 Connection_get_is_authenticated (Connection *self, PyObject *args UNUSED)
267 dbus_bool_t ret;
269 TRACE(self);
270 DBUS_PY_RAISE_VIA_NULL_IF_FAIL(self->conn);
271 Py_BEGIN_ALLOW_THREADS
272 ret = dbus_connection_get_is_authenticated(self->conn);
273 Py_END_ALLOW_THREADS
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"
282 "\n"
283 "The default is for this feature to be disabled for Connections and enabled\n"
284 "for Buses.\n");
285 static PyObject *
286 Connection_set_exit_on_disconnect (Connection *self, PyObject *args)
288 int exit_on_disconnect;
290 TRACE(self);
291 DBUS_PY_RAISE_VIA_NULL_IF_FAIL(self->conn);
292 if (!PyArg_ParseTuple(args, "i:set_exit_on_disconnect",
293 &exit_on_disconnect)) {
294 return NULL;
296 Py_BEGIN_ALLOW_THREADS
297 dbus_connection_set_exit_on_disconnect(self->conn,
298 exit_on_disconnect ? 1 : 0);
299 Py_END_ALLOW_THREADS
300 Py_RETURN_NONE;
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"
306 "\n"
307 ":Parameters:\n"
308 " `msg` : dbus.lowlevel.Message\n"
309 " The message to be sent.\n"
311 static PyObject *
312 Connection_send_message(Connection *self, PyObject *args)
314 dbus_bool_t ok;
315 PyObject *obj;
316 DBusMessage *msg;
317 dbus_uint32_t serial;
319 TRACE(self);
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);
328 Py_END_ALLOW_THREADS
330 if (!ok) {
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"
343 "\n"
344 ":Parameters:\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"
358 "\n"
360 static PyObject *
361 Connection_send_message_with_reply(Connection *self, PyObject *args, PyObject *kw)
363 dbus_bool_t ok;
364 double timeout_s = -1.0;
365 int timeout_ms;
366 PyObject *obj, *callable;
367 DBusMessage *msg;
368 DBusPendingCall *pending;
369 int require_main_loop = 0;
370 static char *argnames[] = {"msg", "reply_handler", "timeout_s",
371 "require_main_loop", NULL};
373 TRACE(self);
374 DBUS_PY_RAISE_VIA_NULL_IF_FAIL(self->conn);
375 if (!PyArg_ParseTupleAndKeywords(args, kw,
376 "OO|di:send_message_with_reply",
377 argnames,
378 &obj, &callable, &timeout_s,
379 &require_main_loop)) {
380 return NULL;
382 if (require_main_loop && !Connection__require_main_loop(self, NULL)) {
383 return NULL;
386 msg = DBusPyMessage_BorrowDBusMessage(obj);
387 if (!msg) return NULL;
389 if (timeout_s < 0) {
390 timeout_ms = -1;
392 else {
393 if (timeout_s > ((double)INT_MAX) / 1000.0) {
394 PyErr_SetString(PyExc_ValueError, "Timeout too long");
395 return NULL;
397 timeout_ms = (int)(timeout_s * 1000.0);
400 Py_BEGIN_ALLOW_THREADS
401 ok = dbus_connection_send_with_reply(self->conn, msg, &pending,
402 timeout_ms);
403 Py_END_ALLOW_THREADS
405 if (!ok) {
406 return PyErr_NoMemory();
409 if (!pending) {
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"
423 "\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"
427 "\n"
428 ":Parameters:\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"
435 ":Returns:\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"
439 " error message)\n"
440 "\n"
442 static PyObject *
443 Connection_send_message_with_reply_and_block(Connection *self, PyObject *args)
445 double timeout_s = -1.0;
446 int timeout_ms;
447 PyObject *obj;
448 DBusMessage *msg, *reply;
449 DBusError error;
451 TRACE(self);
452 DBUS_PY_RAISE_VIA_NULL_IF_FAIL(self->conn);
453 if (!PyArg_ParseTuple(args, "O|d:send_message_with_reply_and_block", &obj,
454 &timeout_s)) {
455 return NULL;
458 msg = DBusPyMessage_BorrowDBusMessage(obj);
459 if (!msg) return NULL;
461 if (timeout_s < 0) {
462 timeout_ms = -1;
464 else {
465 if (timeout_s > ((double)INT_MAX) / 1000.0) {
466 PyErr_SetString(PyExc_ValueError, "Timeout too long");
467 return NULL;
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,
475 timeout_ms, &error);
476 Py_END_ALLOW_THREADS
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
480 * the first */
481 if (!reply) {
482 return DBusPyException_ConsumeError(&error);
484 return DBusPyMessage_ConsumeDBusMessage(reply);
487 PyDoc_STRVAR(Connection_flush__doc__,
488 "flush()\n\n"
489 "Block until the outgoing message queue is empty.\n");
490 static PyObject *
491 Connection_flush (Connection *self, PyObject *args UNUSED)
493 TRACE(self);
494 DBUS_PY_RAISE_VIA_NULL_IF_FAIL(self->conn);
495 Py_BEGIN_ALLOW_THREADS
496 dbus_connection_flush (self->conn);
497 Py_END_ALLOW_THREADS
498 Py_RETURN_NONE;
501 /* Unsupported:
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");
531 static PyObject *
532 Connection_get_unix_fd (Connection *self, PyObject *unused UNUSED)
534 int fd;
535 dbus_bool_t ok;
537 TRACE(self);
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);
541 Py_END_ALLOW_THREADS
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");
551 static PyObject *
552 Connection_get_peer_unix_user (Connection *self, PyObject *unused UNUSED)
554 unsigned long uid;
555 dbus_bool_t ok;
557 TRACE(self);
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);
561 Py_END_ALLOW_THREADS
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");
571 static PyObject *
572 Connection_get_peer_unix_process_id (Connection *self, PyObject *unused UNUSED)
574 unsigned long pid;
575 dbus_bool_t ok;
577 TRACE(self);
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);
581 Py_END_ALLOW_THREADS
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"
593 "\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"
599 static PyObject *
600 Connection_add_message_filter(Connection *self, PyObject *callable)
602 dbus_bool_t ok;
604 TRACE(self);
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) {
610 return NULL;
613 Py_BEGIN_ALLOW_THREADS
614 ok = dbus_connection_add_filter(self->conn, _filter_message, callable,
615 NULL);
616 Py_END_ALLOW_THREADS
618 if (!ok) {
619 Py_XDECREF(PyObject_CallMethod(self->filters, "remove", "(O)",
620 callable));
621 PyErr_NoMemory();
622 return NULL;
624 Py_RETURN_NONE;
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"
630 "\n"
631 ":Raises LookupError:\n"
632 " The given callable is not among the registered filters\n");
633 static PyObject *
634 Connection_remove_message_filter(Connection *self, PyObject *callable)
636 PyObject *obj;
638 TRACE(self);
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
642 * to it. */
643 obj = PyObject_CallMethod(self->filters, "remove", "(O)", callable);
644 if (!obj) return NULL;
645 Py_DECREF(obj);
647 Py_BEGIN_ALLOW_THREADS
648 dbus_connection_remove_filter(self->conn, _filter_message, callable);
649 Py_END_ALLOW_THREADS
651 Py_RETURN_NONE;
654 PyDoc_STRVAR(Connection__register_object_path__doc__,
655 "register_object_path(path, on_message, on_unregister=None, fallback=False)\n"
656 "\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"
661 "\n"
662 ":Parameters:\n"
663 " `path` : str\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"
677 static PyObject *
678 Connection__register_object_path(Connection *self, PyObject *args,
679 PyObject *kwargs)
681 dbus_bool_t ok;
682 int fallback = 0;
683 PyObject *callbacks, *path, *tuple, *on_message, *on_unregister = Py_None;
684 static char *argnames[] = {"path", "on_message", "on_unregister",
685 "fallback", NULL};
687 TRACE(self);
688 DBUS_PY_RAISE_VIA_NULL_IF_FAIL(self->conn);
689 if (!Connection__require_main_loop(self, NULL)) {
690 return NULL;
692 if (!PyArg_ParseTupleAndKeywords(args, kwargs,
693 "OO|Oi:_register_object_path",
694 argnames,
695 &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)) {
706 Py_INCREF(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;
716 else {
717 PyErr_SetString(PyExc_TypeError, "path must be a str or unicode object");
718 return NULL;
721 if (!dbus_py_validate_object_path(PyString_AS_STRING(path))) {
722 Py_DECREF(path);
723 return NULL;
726 tuple = Py_BuildValue("(OO)", on_unregister, on_message);
727 if (!tuple) {
728 Py_DECREF(path);
729 return NULL;
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));
738 Py_DECREF(tuple);
739 Py_DECREF(path);
740 return NULL;
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) {
748 Py_DECREF(tuple);
749 Py_DECREF(path);
750 return NULL;
753 Py_BEGIN_ALLOW_THREADS
754 if (fallback) {
755 ok = dbus_connection_register_fallback(self->conn,
756 PyString_AS_STRING(path),
757 &_object_path_vtable,
758 path);
760 else {
761 ok = dbus_connection_register_object_path(self->conn,
762 PyString_AS_STRING(path),
763 &_object_path_vtable,
764 path);
766 Py_END_ALLOW_THREADS
768 if (ok) {
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));
777 Py_END_ALLOW_THREADS
778 return NULL;
780 /* don't DECREF path: libdbus owns a ref now */
781 Py_DECREF(tuple);
782 Py_RETURN_NONE;
784 else {
785 /* Oops, OOM. Tidy up, if we can, ignoring any error. */
786 PyDict_DelItem(self->object_paths, path);
787 PyErr_Clear();
788 Py_DECREF(tuple);
789 Py_DECREF(path);
790 PyErr_NoMemory();
791 return NULL;
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"
798 "\n"
799 ":Parameters:\n"
800 " `path` : str\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"
803 " object path.\n"
805 static PyObject *
806 Connection__unregister_object_path(Connection *self, PyObject *args,
807 PyObject *kwargs)
809 dbus_bool_t ok;
810 PyObject *path;
811 PyObject *callbacks;
812 static char *argnames[] = {"path", NULL};
814 TRACE(self);
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)) {
822 Py_INCREF(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;
832 else {
833 PyErr_SetString(PyExc_TypeError, "path must be a str or unicode object");
834 return NULL;
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));
844 Py_DECREF(path);
845 return NULL;
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
861 is in sync. */
862 Py_DECREF(callbacks);
863 Py_DECREF(path);
864 return NULL;
867 /* BEGIN PARANOIA
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));
880 Py_END_ALLOW_THREADS
882 if (ok) {
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. */
888 Py_DECREF(path);
889 PyErr_Clear();
890 Py_RETURN_NONE;
892 else {
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
900 anyway. */
901 Py_DECREF(path);
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"
911 "\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");
917 static PyObject *
918 Connection_list_exported_child_objects (Connection *self, PyObject *args,
919 PyObject *kwargs)
921 const char *path;
922 char **kids, **kid_ptr;
923 dbus_bool_t ok;
924 PyObject *ret;
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)) {
929 return NULL;
932 if (!dbus_py_validate_object_path(path)) {
933 return NULL;
936 Py_BEGIN_ALLOW_THREADS
937 ok = dbus_connection_list_registered(self->conn, path, &kids);
938 Py_END_ALLOW_THREADS
940 if (!ok) {
941 return PyErr_NoMemory();
944 ret = PyList_New(0);
945 if (!ret) {
946 return NULL;
948 for (kid_ptr = kids; *kid_ptr; kid_ptr++) {
949 PyObject *tmp = PyString_FromString(*kid_ptr);
951 if (!tmp) {
952 Py_DECREF(ret);
953 return NULL;
955 if (PyList_Append(ret, tmp) < 0) {
956 Py_DECREF(tmp);
957 Py_DECREF(ret);
958 return NULL;
960 Py_DECREF(tmp);
963 dbus_free_string_array(kids);
965 return ret;
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"
985 "\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"
994 "\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,
1027 METH_NOARGS,
1028 get_unique_name__doc__},
1029 {"set_unique_name", (PyCFunction)DBusPyConnection_SetUniqueName,
1030 METH_VARARGS,
1031 set_unique_name__doc__},
1032 {NULL},
1033 #undef ENTRY
1036 /* vim:set ft=c cino< sw=4 sts=4 et: */