Update NEWS, README for 0.80.0
[dbus-python-phuang.git] / _dbus_bindings / conn-methods.c
blob16a0102c54ec0f25f1dba8d576a8eb03ff389180
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 program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * This program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation; either version 2 of the License, or
13 * (at your option) any later version.
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
20 * You should have received a copy of the GNU General Public License
21 * along with this program; if not, write to the Free Software
22 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
26 #include "dbus_bindings-internal.h"
27 #include "conn-internal.h"
29 static void
30 _object_path_unregister(DBusConnection *conn, void *user_data)
32 PyGILState_STATE gil = PyGILState_Ensure();
33 PyObject *tuple = NULL;
34 Connection *conn_obj = NULL;
35 PyObject *callable;
37 conn_obj = (Connection *)DBusPyConnection_ExistingFromDBusConnection(conn);
38 if (!conn_obj) goto out;
39 TRACE(conn_obj);
41 DBG("Connection at %p unregistering object path %s",
42 conn_obj, PyString_AS_STRING((PyObject *)user_data));
43 tuple = DBusPyConnection_GetObjectPathHandlers((PyObject *)conn_obj, (PyObject *)user_data);
44 if (!tuple) goto out;
45 if (tuple == Py_None) goto out;
47 DBG("%s", "... yes we have handlers for that object path");
49 /* 0'th item is the unregisterer (if that's a word) */
50 callable = PyTuple_GetItem(tuple, 0);
51 if (callable && callable != Py_None) {
52 DBG("%s", "... and we even have an unregisterer");
53 /* any return from the unregisterer is ignored */
54 Py_XDECREF(PyObject_CallFunctionObjArgs(callable, conn_obj, NULL));
56 out:
57 Py_XDECREF(conn_obj);
58 Py_XDECREF(tuple);
59 /* the user_data (a Python str) is no longer ref'd by the DBusConnection */
60 Py_XDECREF((PyObject *)user_data);
61 if (PyErr_Occurred()) {
62 PyErr_Print();
64 PyGILState_Release(gil);
67 static DBusHandlerResult
68 _object_path_message(DBusConnection *conn, DBusMessage *message,
69 void *user_data)
71 DBusHandlerResult ret;
72 PyGILState_STATE gil = PyGILState_Ensure();
73 Connection *conn_obj = NULL;
74 PyObject *tuple = NULL;
75 PyObject *msg_obj;
76 PyObject *callable; /* borrowed */
78 dbus_message_ref(message);
79 msg_obj = DBusPyMessage_ConsumeDBusMessage(message);
80 if (!msg_obj) {
81 ret = DBUS_HANDLER_RESULT_NEED_MEMORY;
82 goto out;
85 conn_obj = (Connection *)DBusPyConnection_ExistingFromDBusConnection(conn);
86 if (!conn_obj) {
87 ret = DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
88 goto out;
90 TRACE(conn_obj);
92 DBG("Connection at %p messaging object path %s",
93 conn_obj, PyString_AS_STRING((PyObject *)user_data));
94 DBG_DUMP_MESSAGE(message);
95 tuple = DBusPyConnection_GetObjectPathHandlers((PyObject *)conn_obj, (PyObject *)user_data);
96 if (!tuple || tuple == Py_None) {
97 ret = DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
98 goto out;
101 DBG("%s", "... yes we have handlers for that object path");
103 /* 1st item (0-based) is the message callback */
104 callable = PyTuple_GetItem(tuple, 1);
105 if (!callable) {
106 DBG("%s", "... error getting message handler from tuple");
107 ret = DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
109 else if (callable == Py_None) {
110 /* there was actually no handler after all */
111 DBG("%s", "... but those handlers don't do messages");
112 ret = DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
114 else {
115 DBG("%s", "... and we have a message handler for that object path");
116 ret = DBusPyConnection_HandleMessage(conn_obj, msg_obj, callable);
119 out:
120 Py_XDECREF(msg_obj);
121 Py_XDECREF(conn_obj);
122 Py_XDECREF(tuple);
123 if (PyErr_Occurred()) {
124 PyErr_Print();
126 PyGILState_Release(gil);
127 return ret;
130 static const DBusObjectPathVTable _object_path_vtable = {
131 _object_path_unregister,
132 _object_path_message,
135 static DBusHandlerResult
136 _filter_message(DBusConnection *conn, DBusMessage *message, void *user_data)
138 DBusHandlerResult ret;
139 PyGILState_STATE gil = PyGILState_Ensure();
140 Connection *conn_obj = NULL;
141 PyObject *callable = NULL;
142 PyObject *msg_obj;
143 #ifndef DBUS_PYTHON_DISABLE_CHECKS
144 Py_ssize_t i, size;
145 #endif
147 dbus_message_ref(message);
148 msg_obj = DBusPyMessage_ConsumeDBusMessage(message);
149 if (!msg_obj) {
150 DBG("%s", "OOM while trying to construct Message");
151 ret = DBUS_HANDLER_RESULT_NEED_MEMORY;
152 goto out;
155 conn_obj = (Connection *)DBusPyConnection_ExistingFromDBusConnection(conn);
156 if (!conn_obj) {
157 DBG("%s", "failed to traverse DBusConnection -> Connection weakref");
158 ret = DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
159 goto out;
161 TRACE(conn_obj);
163 /* The user_data is a pointer to a Python object. To avoid
164 * cross-library reference cycles, the DBusConnection isn't allowed
165 * to reference it. However, as long as the Connection is still
166 * alive, its ->filters list owns a reference to the same Python
167 * object, so the object should also still be alive.
169 * To ensure that this works, be careful whenever manipulating the
170 * filters list! (always put things in the list *before* giving
171 * them to libdbus, etc.)
173 #ifdef DBUS_PYTHON_DISABLE_CHECKS
174 callable = (PyObject *)user_data;
175 #else
176 size = PyList_GET_SIZE(conn_obj->filters);
177 for (i = 0; i < size; i++) {
178 callable = PyList_GET_ITEM(conn_obj->filters, i);
179 if (callable == user_data) {
180 Py_INCREF(callable);
182 else {
183 callable = NULL;
187 if (!callable) {
188 DBG("... filter %p has vanished from ->filters, so not calling it",
189 user_data);
190 ret = DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
191 goto out;
193 #endif
195 ret = DBusPyConnection_HandleMessage(conn_obj, msg_obj, callable);
196 out:
197 Py_XDECREF(msg_obj);
198 Py_XDECREF(conn_obj);
199 Py_XDECREF(callable);
200 PyGILState_Release(gil);
201 return ret;
204 PyDoc_STRVAR(Connection__require_main_loop__doc__,
205 "_require_main_loop()\n\n"
206 "Raise an exception if this Connection is not bound to any main loop -\n"
207 "in this state, asynchronous calls, receiving signals and exporting objects\n"
208 "will not work.\n"
209 "\n"
210 "`dbus.mainloop.NULL_MAIN_LOOP` is treated like a valid main loop - if you're\n"
211 "using that, you presumably know what you're doing.\n");
212 static PyObject *
213 Connection__require_main_loop (Connection *self, PyObject *args UNUSED)
215 if (!self->has_mainloop) {
216 PyErr_SetString(PyExc_RuntimeError,
217 "To make asynchronous calls, receive signals or "
218 "export objects, D-Bus connections must be attached "
219 "to a main loop by passing mainloop=... to the "
220 "constructor or calling "
221 "dbus.set_default_main_loop(...)");
222 return NULL;
224 Py_RETURN_NONE;
227 PyDoc_STRVAR(Connection_close__doc__,
228 "close()\n\n"
229 "Close the connection.");
230 static PyObject *
231 Connection_close (Connection *self, PyObject *args)
233 TRACE(self);
234 if (!PyArg_ParseTuple(args, ":close")) return NULL;
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)
251 dbus_bool_t ret;
253 TRACE(self);
254 DBUS_PY_RAISE_VIA_NULL_IF_FAIL(self->conn);
255 if (!PyArg_ParseTuple(args, ":get_is_connected")) return NULL;
256 Py_BEGIN_ALLOW_THREADS
257 ret = dbus_connection_get_is_connected(self->conn);
258 Py_END_ALLOW_THREADS
259 return PyBool_FromLong(ret);
262 PyDoc_STRVAR(Connection_get_is_authenticated__doc__,
263 "get_is_authenticated() -> bool\n\n"
264 "Return true if this Connection was ever authenticated.\n");
265 static PyObject *
266 Connection_get_is_authenticated (Connection *self, PyObject *args)
268 dbus_bool_t ret;
270 TRACE(self);
271 DBUS_PY_RAISE_VIA_NULL_IF_FAIL(self->conn);
272 if (!PyArg_ParseTuple(args, ":get_is_authenticated")) return NULL;
273 Py_BEGIN_ALLOW_THREADS
274 ret = dbus_connection_get_is_authenticated(self->conn);
275 Py_END_ALLOW_THREADS
276 return PyBool_FromLong(ret);
279 PyDoc_STRVAR(Connection_set_exit_on_disconnect__doc__,
280 "set_exit_on_disconnect(bool)\n\n"
281 "Set whether the C function ``_exit`` will be called when this Connection\n"
282 "becomes disconnected. This will cause the program to exit without calling\n"
283 "any cleanup code or exit handlers.\n"
284 "\n"
285 "The default is for this feature to be disabled for Connections and enabled\n"
286 "for Buses.\n");
287 static PyObject *
288 Connection_set_exit_on_disconnect (Connection *self, PyObject *args)
290 int exit_on_disconnect;
292 TRACE(self);
293 DBUS_PY_RAISE_VIA_NULL_IF_FAIL(self->conn);
294 if (!PyArg_ParseTuple(args, "i:set_exit_on_disconnect",
295 &exit_on_disconnect)) {
296 return NULL;
298 Py_BEGIN_ALLOW_THREADS
299 dbus_connection_set_exit_on_disconnect(self->conn,
300 exit_on_disconnect ? 1 : 0);
301 Py_END_ALLOW_THREADS
302 Py_RETURN_NONE;
305 PyDoc_STRVAR(Connection_send_message__doc__,
306 "send_message(msg) -> long\n\n"
307 "Queue the given message for sending, and return the message serial number.\n"
308 "\n"
309 ":Parameters:\n"
310 " `msg` : dbus.lowlevel.Message\n"
311 " The message to be sent.\n"
313 static PyObject *
314 Connection_send_message(Connection *self, PyObject *args)
316 dbus_bool_t ok;
317 PyObject *obj;
318 DBusMessage *msg;
319 dbus_uint32_t serial;
321 TRACE(self);
322 DBUS_PY_RAISE_VIA_NULL_IF_FAIL(self->conn);
323 if (!PyArg_ParseTuple(args, "O", &obj)) return NULL;
325 msg = DBusPyMessage_BorrowDBusMessage(obj);
326 if (!msg) return NULL;
328 Py_BEGIN_ALLOW_THREADS
329 ok = dbus_connection_send(self->conn, msg, &serial);
330 Py_END_ALLOW_THREADS
332 if (!ok) {
333 return PyErr_NoMemory();
336 return PyLong_FromUnsignedLong(serial);
339 /* The timeout is in seconds here, since that's conventional in Python. */
340 PyDoc_STRVAR(Connection_send_message_with_reply__doc__,
341 "send_message_with_reply(msg, reply_handler, timeout_s=-1, "
342 "require_main_loop=False) -> dbus.lowlevel.PendingCall\n\n"
343 "Queue the message for sending; expect a reply via the returned PendingCall,\n"
344 "which can also be used to cancel the pending call.\n"
345 "\n"
346 ":Parameters:\n"
347 " `msg` : dbus.lowlevel.Message\n"
348 " The message to be sent\n"
349 " `reply_handler` : callable\n"
350 " Asynchronous reply handler: will be called with one positional\n"
351 " parameter, a Message instance representing the reply.\n"
352 " `timeout_s` : float\n"
353 " If the reply takes more than this many seconds, a timeout error\n"
354 " will be created locally and raised instead. If this timeout is\n"
355 " negative (default), a sane default (supplied by libdbus) is used.\n"
356 " `require_main_loop` : bool\n"
357 " If True, raise RuntimeError if this Connection does not have a main\n"
358 " loop configured. If False (default) and there is no main loop, you are\n"
359 " responsible for calling block() on the PendingCall.\n"
360 "\n"
362 static PyObject *
363 Connection_send_message_with_reply(Connection *self, PyObject *args, PyObject *kw)
365 dbus_bool_t ok;
366 double timeout_s = -1.0;
367 int timeout_ms;
368 PyObject *obj, *callable;
369 DBusMessage *msg;
370 DBusPendingCall *pending;
371 int require_main_loop = 0;
372 static char *argnames[] = {"msg", "reply_handler", "timeout_s",
373 "require_main_loop", NULL};
375 TRACE(self);
376 DBUS_PY_RAISE_VIA_NULL_IF_FAIL(self->conn);
377 if (!PyArg_ParseTupleAndKeywords(args, kw,
378 "OO|fi:send_message_with_reply",
379 argnames,
380 &obj, &callable, &timeout_s,
381 &require_main_loop)) {
382 return NULL;
384 if (require_main_loop && !Connection__require_main_loop(self, NULL)) {
385 return NULL;
388 msg = DBusPyMessage_BorrowDBusMessage(obj);
389 if (!msg) return NULL;
391 if (timeout_s < 0) {
392 timeout_ms = -1;
394 else {
395 if (timeout_s > ((double)INT_MAX) / 1000.0) {
396 PyErr_SetString(PyExc_ValueError, "Timeout too long");
397 return NULL;
399 timeout_ms = (int)(timeout_s * 1000.0);
402 Py_BEGIN_ALLOW_THREADS
403 ok = dbus_connection_send_with_reply(self->conn, msg, &pending,
404 timeout_ms);
405 Py_END_ALLOW_THREADS
407 if (!ok) {
408 return PyErr_NoMemory();
411 return DBusPyPendingCall_ConsumeDBusPendingCall(pending, callable);
414 /* Again, the timeout is in seconds, since that's conventional in Python. */
415 PyDoc_STRVAR(Connection_send_message_with_reply_and_block__doc__,
416 "send_message_with_reply_and_block(msg, timeout_s=-1)"
417 " -> dbus.lowlevel.Message\n\n"
418 "Send the message and block while waiting for a reply.\n"
419 "\n"
420 "This does not re-enter the main loop, so it can lead to a deadlock, if\n"
421 "the called method tries to make a synchronous call to a method in this\n"
422 "application. As such, it's probably a bad idea.\n"
423 "\n"
424 ":Parameters:\n"
425 " `msg` : dbus.lowlevel.Message\n"
426 " The message to be sent\n"
427 " `timeout_s` : float\n"
428 " If the reply takes more than this many seconds, a timeout error\n"
429 " will be created locally and raised instead. If this timeout is\n"
430 " negative (default), a sane default (supplied by libdbus) is used.\n"
431 ":Returns:\n"
432 " A `dbus.lowlevel.Message` instance (probably a `dbus.lowlevel.MethodReturnMessage`) on success\n"
433 ":Raises dbus.DBusException:\n"
434 " On error (including if the reply arrives but is an\n"
435 " error message)\n"
436 "\n"
438 static PyObject *
439 Connection_send_message_with_reply_and_block(Connection *self, PyObject *args)
441 double timeout_s = -1.0;
442 int timeout_ms;
443 PyObject *obj;
444 DBusMessage *msg, *reply;
445 DBusError error;
447 TRACE(self);
448 DBUS_PY_RAISE_VIA_NULL_IF_FAIL(self->conn);
449 if (!PyArg_ParseTuple(args, "O|f:send_message_with_reply_and_block", &obj,
450 &timeout_s)) {
451 return NULL;
454 msg = DBusPyMessage_BorrowDBusMessage(obj);
455 if (!msg) return NULL;
457 if (timeout_s < 0) {
458 timeout_ms = -1;
460 else {
461 if (timeout_s > ((double)INT_MAX) / 1000.0) {
462 PyErr_SetString(PyExc_ValueError, "Timeout too long");
463 return NULL;
465 timeout_ms = (int)(timeout_s * 1000.0);
468 dbus_error_init(&error);
469 Py_BEGIN_ALLOW_THREADS
470 reply = dbus_connection_send_with_reply_and_block(self->conn, msg,
471 timeout_ms, &error);
472 Py_END_ALLOW_THREADS
474 if (!reply) {
475 return DBusPyException_ConsumeError(&error);
477 return DBusPyMessage_ConsumeDBusMessage(reply);
480 PyDoc_STRVAR(Connection_flush__doc__,
481 "flush()\n\n"
482 "Block until the outgoing message queue is empty.\n");
483 static PyObject *
484 Connection_flush (Connection *self, PyObject *args UNUSED)
486 TRACE(self);
487 DBUS_PY_RAISE_VIA_NULL_IF_FAIL(self->conn);
488 Py_BEGIN_ALLOW_THREADS
489 dbus_connection_flush (self->conn);
490 Py_END_ALLOW_THREADS
491 Py_RETURN_NONE;
494 /* Unsupported:
495 * dbus_connection_preallocate_send
496 * dbus_connection_free_preallocated_send
497 * dbus_connection_send_preallocated
498 * dbus_connection_borrow_message
499 * dbus_connection_return_message
500 * dbus_connection_steal_borrowed_message
501 * dbus_connection_pop_message
504 /* Non-main-loop handling not yet implemented: */
505 /* dbus_connection_read_write_dispatch */
506 /* dbus_connection_read_write */
508 /* Main loop handling not yet implemented: */
509 /* dbus_connection_get_dispatch_status */
510 /* dbus_connection_dispatch */
511 /* dbus_connection_set_watch_functions */
512 /* dbus_connection_set_timeout_functions */
513 /* dbus_connection_set_wakeup_main_function */
514 /* dbus_connection_set_dispatch_status_function */
516 /* Normally in Python this would be called fileno(), but I don't want to
517 * encourage people to select() on it */
518 PyDoc_STRVAR(Connection_get_unix_fd__doc__,
519 "get_unix_fd() -> int or None\n\n"
520 "Get the connection's UNIX file descriptor, if any.\n\n"
521 "This can be used for SELinux access control checks with ``getpeercon()``\n"
522 "for example. **Do not** read or write to the file descriptor, or try to\n"
523 "``select()`` on it.\n");
524 static PyObject *
525 Connection_get_unix_fd (Connection *self, PyObject *unused UNUSED)
527 int fd;
528 dbus_bool_t ok;
530 TRACE(self);
531 DBUS_PY_RAISE_VIA_NULL_IF_FAIL(self->conn);
532 Py_BEGIN_ALLOW_THREADS
533 ok = dbus_connection_get_unix_fd (self->conn, &fd);
534 Py_END_ALLOW_THREADS
535 if (!ok) Py_RETURN_NONE;
536 return PyInt_FromLong(fd);
539 PyDoc_STRVAR(Connection_get_peer_unix_user__doc__,
540 "get_peer_unix_user() -> long or None\n\n"
541 "Get the UNIX user ID at the other end of the connection, if it has been\n"
542 "authenticated. Return None if this is a non-UNIX platform or the\n"
543 "connection has not been authenticated.\n");
544 static PyObject *
545 Connection_get_peer_unix_user (Connection *self, PyObject *unused UNUSED)
547 unsigned long uid;
548 dbus_bool_t ok;
550 TRACE(self);
551 DBUS_PY_RAISE_VIA_NULL_IF_FAIL(self->conn);
552 Py_BEGIN_ALLOW_THREADS
553 ok = dbus_connection_get_unix_user (self->conn, &uid);
554 Py_END_ALLOW_THREADS
555 if (!ok) Py_RETURN_NONE;
556 return PyLong_FromUnsignedLong (uid);
559 PyDoc_STRVAR(Connection_get_peer_unix_process_id__doc__,
560 "get_peer_unix_process_id() -> long or None\n\n"
561 "Get the UNIX process ID at the other end of the connection, if it has been\n"
562 "authenticated. Return None if this is a non-UNIX platform or the\n"
563 "connection has not been authenticated.\n");
564 static PyObject *
565 Connection_get_peer_unix_process_id (Connection *self, PyObject *unused UNUSED)
567 unsigned long pid;
568 dbus_bool_t ok;
570 TRACE(self);
571 DBUS_PY_RAISE_VIA_NULL_IF_FAIL(self->conn);
572 Py_BEGIN_ALLOW_THREADS
573 ok = dbus_connection_get_unix_process_id (self->conn, &pid);
574 Py_END_ALLOW_THREADS
575 if (!ok) Py_RETURN_NONE;
576 return PyLong_FromUnsignedLong (pid);
579 /* TODO: wrap dbus_connection_set_unix_user_function Pythonically */
581 PyDoc_STRVAR(Connection_add_message_filter__doc__,
582 "add_message_filter(callable)\n\n"
583 "Add the given message filter to the internal list.\n\n"
584 "Filters are handlers that are run on all incoming messages, prior to the\n"
585 "objects registered to handle object paths.\n"
586 "\n"
587 "Filters are run in the order that they were added. The same handler can\n"
588 "be added as a filter more than once, in which case it will be run more\n"
589 "than once. Filters added during a filter callback won't be run on the\n"
590 "message being processed.\n"
592 static PyObject *
593 Connection_add_message_filter(Connection *self, PyObject *callable)
595 dbus_bool_t ok;
597 TRACE(self);
598 DBUS_PY_RAISE_VIA_NULL_IF_FAIL(self->conn);
599 /* The callable must be referenced by ->filters *before* it is
600 * given to libdbus, which does not own a reference to it.
602 if (PyList_Append(self->filters, callable) < 0) {
603 return NULL;
606 Py_BEGIN_ALLOW_THREADS
607 ok = dbus_connection_add_filter(self->conn, _filter_message, callable,
608 NULL);
609 Py_END_ALLOW_THREADS
611 if (!ok) {
612 Py_XDECREF(PyObject_CallMethod(self->filters, "remove", "(O)",
613 callable));
614 PyErr_NoMemory();
615 return NULL;
617 Py_RETURN_NONE;
620 PyDoc_STRVAR(Connection_remove_message_filter__doc__,
621 "remove_message_filter(callable)\n\n"
622 "Remove the given message filter (see `add_message_filter` for details).\n"
623 "\n"
624 ":Raises LookupError:\n"
625 " The given callable is not among the registered filters\n");
626 static PyObject *
627 Connection_remove_message_filter(Connection *self, PyObject *callable)
629 PyObject *obj;
631 TRACE(self);
632 DBUS_PY_RAISE_VIA_NULL_IF_FAIL(self->conn);
633 /* It's safe to do this before removing it from libdbus, because
634 * the presence of callable in our arguments means we have a ref
635 * to it. */
636 obj = PyObject_CallMethod(self->filters, "remove", "(O)", callable);
637 if (!obj) return NULL;
638 Py_DECREF(obj);
640 Py_BEGIN_ALLOW_THREADS
641 dbus_connection_remove_filter(self->conn, _filter_message, callable);
642 Py_END_ALLOW_THREADS
644 Py_RETURN_NONE;
647 PyDoc_STRVAR(Connection__register_object_path__doc__,
648 "register_object_path(path, on_message, on_unregister=None, fallback=False)\n"
649 "\n"
650 "Register a callback to be called when messages arrive at the given\n"
651 "object-path. Used to export objects' methods on the bus in a low-level\n"
652 "way. For the high-level interface to this functionality (usually\n"
653 "recommended) see the `dbus.service.Object` base class.\n"
654 "\n"
655 ":Parameters:\n"
656 " `path` : str\n"
657 " Object path to be acted on\n"
658 " `on_message` : callable\n"
659 " Called when a message arrives at the given object-path, with\n"
660 " two positional parameters: the first is this Connection,\n"
661 " the second is the incoming `dbus.lowlevel.Message`.\n"
662 " `on_unregister` : callable or None\n"
663 " If not None, called when the callback is unregistered.\n"
664 " `fallback` : bool\n"
665 " If True (the default is False), when a message arrives for a\n"
666 " 'subdirectory' of the given path and there is no more specific\n"
667 " handler, use this handler. Normally this handler is only run if\n"
668 " the paths match exactly.\n"
670 static PyObject *
671 Connection__register_object_path(Connection *self, PyObject *args,
672 PyObject *kwargs)
674 dbus_bool_t ok;
675 int fallback = 0;
676 PyObject *callbacks, *path, *tuple, *on_message, *on_unregister = Py_None;
677 static char *argnames[] = {"path", "on_message", "on_unregister",
678 "fallback", NULL};
680 TRACE(self);
681 DBUS_PY_RAISE_VIA_NULL_IF_FAIL(self->conn);
682 if (!Connection__require_main_loop(self, NULL)) {
683 return NULL;
685 if (!PyArg_ParseTupleAndKeywords(args, kwargs,
686 "OO|Oi:_register_object_path",
687 argnames,
688 &path,
689 &on_message, &on_unregister,
690 &fallback)) return NULL;
692 /* Take a reference to path, which we give away to libdbus in a moment.
694 Also, path needs to be a string (not a subclass which could do something
695 mad) to preserve the desirable property that the DBusConnection can
696 never strongly reference the Connection, even indirectly.
698 if (PyString_CheckExact(path)) {
699 Py_INCREF(path);
701 else if (PyUnicode_Check(path)) {
702 path = PyUnicode_AsUTF8String(path);
703 if (!path) return NULL;
705 else if (PyString_Check(path)) {
706 path = PyString_FromString(PyString_AS_STRING(path));
707 if (!path) return NULL;
709 else {
710 PyErr_SetString(PyExc_TypeError, "path must be a str or unicode object");
711 return NULL;
714 if (!dbus_py_validate_object_path(PyString_AS_STRING(path))) {
715 Py_DECREF(path);
716 return NULL;
719 tuple = Py_BuildValue("(OO)", on_unregister, on_message);
720 if (!tuple) {
721 Py_DECREF(path);
722 return NULL;
725 /* Guard against registering a handler that already exists. */
726 callbacks = PyDict_GetItem(self->object_paths, path);
727 if (callbacks && callbacks != Py_None) {
728 PyErr_Format(PyExc_KeyError, "Can't register the object-path "
729 "handler for '%s': there is already a handler",
730 PyString_AS_STRING(path));
731 Py_DECREF(tuple);
732 Py_DECREF(path);
733 return NULL;
736 /* Pre-allocate a slot in the dictionary, so we know we'll be able
737 * to replace it with the callbacks without OOM.
738 * This ensures we can keep libdbus' opinion of whether those
739 * paths are handled in sync with our own. */
740 if (PyDict_SetItem(self->object_paths, path, Py_None) < 0) {
741 Py_DECREF(tuple);
742 Py_DECREF(path);
743 return NULL;
746 Py_BEGIN_ALLOW_THREADS
747 if (fallback) {
748 ok = dbus_connection_register_fallback(self->conn,
749 PyString_AS_STRING(path),
750 &_object_path_vtable,
751 path);
753 else {
754 ok = dbus_connection_register_object_path(self->conn,
755 PyString_AS_STRING(path),
756 &_object_path_vtable,
757 path);
759 Py_END_ALLOW_THREADS
761 if (ok) {
762 if (PyDict_SetItem(self->object_paths, path, tuple) < 0) {
763 /* That shouldn't have happened, we already allocated enough
764 memory for it. Oh well, try to undo the registration to keep
765 things in sync. If this fails too, we've leaked a bit of
766 memory in libdbus, but tbh we should never get here anyway. */
767 Py_BEGIN_ALLOW_THREADS
768 ok = dbus_connection_unregister_object_path(self->conn,
769 PyString_AS_STRING(path));
770 Py_END_ALLOW_THREADS
771 return NULL;
773 /* don't DECREF path: libdbus owns a ref now */
774 Py_DECREF(tuple);
775 Py_RETURN_NONE;
777 else {
778 /* Oops, OOM. Tidy up, if we can, ignoring any error. */
779 PyDict_DelItem(self->object_paths, path);
780 PyErr_Clear();
781 Py_DECREF(tuple);
782 Py_DECREF(path);
783 PyErr_NoMemory();
784 return NULL;
788 PyDoc_STRVAR(Connection__unregister_object_path__doc__,
789 "unregister_object_path(path)\n\n"
790 "Remove a previously registered handler for the given object path.\n"
791 "\n"
792 ":Parameters:\n"
793 " `path` : str\n"
794 " The object path whose handler is to be removed\n"
795 ":Raises KeyError: if there is no handler registered for exactly that\n"
796 " object path.\n"
798 static PyObject *
799 Connection__unregister_object_path(Connection *self, PyObject *args,
800 PyObject *kwargs)
802 dbus_bool_t ok;
803 PyObject *path;
804 PyObject *callbacks;
805 static char *argnames[] = {"path", NULL};
807 TRACE(self);
808 DBUS_PY_RAISE_VIA_NULL_IF_FAIL(self->conn);
809 if (!PyArg_ParseTupleAndKeywords(args, kwargs,
810 "O:_unregister_object_path",
811 argnames, &path)) return NULL;
813 /* Take a ref to the path. Same comments as for _register_object_path. */
814 if (PyString_CheckExact(path)) {
815 Py_INCREF(path);
817 else if (PyUnicode_Check(path)) {
818 path = PyUnicode_AsUTF8String(path);
819 if (!path) return NULL;
821 else if (PyString_Check(path)) {
822 path = PyString_FromString(PyString_AS_STRING(path));
823 if (!path) return NULL;
825 else {
826 PyErr_SetString(PyExc_TypeError, "path must be a str or unicode object");
827 return NULL;
830 /* Guard against unregistering a handler that doesn't, in fact, exist,
831 or whose unregistration is already in progress. */
832 callbacks = PyDict_GetItem(self->object_paths, path);
833 if (!callbacks || callbacks == Py_None) {
834 PyErr_Format(PyExc_KeyError, "Can't unregister the object-path "
835 "handler for '%s': there is no such handler",
836 PyString_AS_STRING(path));
837 Py_DECREF(path);
838 return NULL;
841 /* Hang on to a reference to the callbacks for the moment. */
842 Py_INCREF(callbacks);
844 /* Get rid of the object-path while we still have the GIL, to
845 guard against unregistering twice from different threads (which
846 causes undefined behaviour in libdbus).
848 Because deletion would make it possible for the re-insertion below
849 to fail, we instead set the handler to None as a placeholder.
851 if (PyDict_SetItem(self->object_paths, path, Py_None) < 0) {
852 /* If that failed, there's no need to be paranoid as below - the
853 callbacks are still set, so we failed, but at least everything
854 is in sync. */
855 Py_DECREF(callbacks);
856 Py_DECREF(path);
857 return NULL;
860 /* BEGIN PARANOIA
861 This is something of a critical section - the dict of object-paths
862 and libdbus' internal structures are out of sync for a bit. We have
863 to be able to cope with that.
865 It's really annoying that dbus_connection_unregister_object_path
866 can fail, *and* has undefined behaviour if the object path has
867 already been unregistered. Either/or would be fine.
870 Py_BEGIN_ALLOW_THREADS
871 ok = dbus_connection_unregister_object_path(self->conn,
872 PyString_AS_STRING(path));
873 Py_END_ALLOW_THREADS
875 if (ok) {
876 Py_DECREF(callbacks);
877 PyDict_DelItem(self->object_paths, path);
878 /* END PARANOIA on successful code path */
879 /* The above can't fail unless by some strange trickery the key is no
880 longer present. Ignore any errors. */
881 Py_DECREF(path);
882 PyErr_Clear();
883 Py_RETURN_NONE;
885 else {
886 /* Oops, OOM. Put the callbacks back in the dict so
887 * we'll have another go if/when the user frees some memory
888 * and tries calling this method again. */
889 PyDict_SetItem(self->object_paths, path, callbacks);
890 /* END PARANOIA on failing code path */
891 /* If the SetItem failed, there's nothing we can do about it - but
892 since we know it's an existing entry, it shouldn't be able to fail
893 anyway. */
894 Py_DECREF(path);
895 Py_DECREF(callbacks);
896 return PyErr_NoMemory();
900 /* dbus_connection_get_object_path_data - not useful to Python,
901 * the object path data is just a PyString containing the path */
902 /* dbus_connection_list_registered could be useful, though */
904 /* dbus_connection_set_change_sigpipe - sets global state */
906 /* Maxima. Does Python code ever need to manipulate these?
907 * OTOH they're easy to wrap */
908 /* dbus_connection_set_max_message_size */
909 /* dbus_connection_get_max_message_size */
910 /* dbus_connection_set_max_received_size */
911 /* dbus_connection_get_max_received_size */
913 /* dbus_connection_get_outgoing_size - almost certainly unneeded */
915 struct PyMethodDef DBusPyConnection_tp_methods[] = {
916 #define ENTRY(name, flags) {#name, (PyCFunction)Connection_##name, flags, Connection_##name##__doc__}
917 ENTRY(_require_main_loop, METH_NOARGS),
918 ENTRY(close, METH_NOARGS),
919 ENTRY(flush, METH_NOARGS),
920 ENTRY(get_is_connected, METH_NOARGS),
921 ENTRY(get_is_authenticated, METH_NOARGS),
922 ENTRY(set_exit_on_disconnect, METH_VARARGS),
923 ENTRY(get_unix_fd, METH_NOARGS),
924 ENTRY(get_peer_unix_user, METH_NOARGS),
925 ENTRY(get_peer_unix_process_id, METH_NOARGS),
926 ENTRY(add_message_filter, METH_O),
927 ENTRY(_register_object_path, METH_VARARGS|METH_KEYWORDS),
928 ENTRY(remove_message_filter, METH_O),
929 ENTRY(send_message, METH_VARARGS),
930 ENTRY(send_message_with_reply, METH_VARARGS|METH_KEYWORDS),
931 ENTRY(send_message_with_reply_and_block, METH_VARARGS),
932 ENTRY(_unregister_object_path, METH_VARARGS|METH_KEYWORDS),
933 {NULL},
934 #undef ENTRY
937 /* vim:set ft=c cino< sw=4 sts=4 et: */