_dbus_bindings: split out conn, conn-methods into separate translation units
[dbus-python-phuang.git] / _dbus_bindings / conn-methods.c
blob47f2ae0e614c27639247f7d29ac05ad90a52751d
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;
40 DBG("Connection at %p unregistering object path %s",
41 conn_obj, PyString_AS_STRING((PyObject *)user_data));
42 tuple = DBusPyConnection_GetObjectPathHandlers((PyObject *)conn_obj, (PyObject *)user_data);
43 if (!tuple) goto out;
44 if (tuple == Py_None) goto out;
46 DBG("%s", "... yes we have handlers for that object path");
48 /* 0'th item is the unregisterer (if that's a word) */
49 callable = PyTuple_GetItem(tuple, 0);
50 if (callable && callable != Py_None) {
51 DBG("%s", "... and we even have an unregisterer");
52 /* any return from the unregisterer is ignored */
53 Py_XDECREF(PyObject_CallFunctionObjArgs(callable, conn_obj, NULL));
55 out:
56 Py_XDECREF(conn_obj);
57 Py_XDECREF(tuple);
58 /* the user_data (a Python str) is no longer ref'd by the DBusConnection */
59 Py_XDECREF((PyObject *)user_data);
60 if (PyErr_Occurred()) {
61 PyErr_Print();
63 PyGILState_Release(gil);
66 static DBusHandlerResult
67 _object_path_message(DBusConnection *conn, DBusMessage *message,
68 void *user_data)
70 DBusHandlerResult ret;
71 PyGILState_STATE gil = PyGILState_Ensure();
72 Connection *conn_obj = NULL;
73 PyObject *tuple = NULL;
74 PyObject *msg_obj;
75 PyObject *callable; /* borrowed */
77 dbus_message_ref(message);
78 msg_obj = DBusPyMessage_ConsumeDBusMessage(message);
79 if (!msg_obj) {
80 ret = DBUS_HANDLER_RESULT_NEED_MEMORY;
81 goto out;
84 conn_obj = (Connection *)DBusPyConnection_ExistingFromDBusConnection(conn);
85 if (!conn_obj) {
86 ret = DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
87 goto out;
90 DBG("Connection at %p messaging object path %s",
91 conn_obj, PyString_AS_STRING((PyObject *)user_data));
92 DBG_DUMP_MESSAGE(message);
93 tuple = DBusPyConnection_GetObjectPathHandlers((PyObject *)conn_obj, (PyObject *)user_data);
94 if (!tuple || tuple == Py_None) {
95 ret = DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
96 goto out;
99 DBG("%s", "... yes we have handlers for that object path");
101 /* 1st item (0-based) is the message callback */
102 callable = PyTuple_GetItem(tuple, 1);
103 if (!callable) {
104 DBG("%s", "... error getting message handler from tuple");
105 ret = DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
107 else if (callable == Py_None) {
108 /* there was actually no handler after all */
109 DBG("%s", "... but those handlers don't do messages");
110 ret = DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
112 else {
113 DBG("%s", "... and we have a message handler for that object path");
114 ret = DBusPyConnection_HandleMessage(conn_obj, msg_obj, callable);
117 out:
118 Py_XDECREF(msg_obj);
119 Py_XDECREF(conn_obj);
120 Py_XDECREF(tuple);
121 if (PyErr_Occurred()) {
122 PyErr_Print();
124 PyGILState_Release(gil);
125 return ret;
128 static const DBusObjectPathVTable _object_path_vtable = {
129 _object_path_unregister,
130 _object_path_message,
133 static DBusHandlerResult
134 _filter_message(DBusConnection *conn, DBusMessage *message, void *user_data)
136 DBusHandlerResult ret;
137 PyGILState_STATE gil = PyGILState_Ensure();
138 Connection *conn_obj = NULL;
139 PyObject *callable = NULL;
140 PyObject *msg_obj;
141 #ifndef DBUS_PYTHON_DISABLE_CHECKS
142 int i, size;
143 #endif
145 dbus_message_ref(message);
146 msg_obj = DBusPyMessage_ConsumeDBusMessage(message);
147 if (!msg_obj) {
148 DBG("%s", "OOM while trying to construct Message");
149 ret = DBUS_HANDLER_RESULT_NEED_MEMORY;
150 goto out;
153 conn_obj = (Connection *)DBusPyConnection_ExistingFromDBusConnection(conn);
154 if (!conn_obj) {
155 DBG("%s", "failed to traverse DBusConnection -> Connection weakref");
156 ret = DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
157 goto out;
160 /* The user_data is a pointer to a Python object. To avoid
161 * cross-library reference cycles, the DBusConnection isn't allowed
162 * to reference it. However, as long as the Connection is still
163 * alive, its ->filters list owns a reference to the same Python
164 * object, so the object should also still be alive.
166 * To ensure that this works, be careful whenever manipulating the
167 * filters list! (always put things in the list *before* giving
168 * them to libdbus, etc.)
170 #ifdef DBUS_PYTHON_DISABLE_CHECKS
171 callable = (PyObject *)user_data;
172 #else
173 size = PyList_GET_SIZE(conn_obj->filters);
174 for (i = 0; i < size; i++) {
175 callable = PyList_GET_ITEM(conn_obj->filters, i);
176 if (callable == user_data) {
177 Py_INCREF(callable);
179 else {
180 callable = NULL;
184 if (!callable) {
185 DBG("... filter %p has vanished from ->filters, so not calling it",
186 user_data);
187 ret = DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
188 goto out;
190 #endif
192 ret = DBusPyConnection_HandleMessage(conn_obj, msg_obj, callable);
193 out:
194 Py_XDECREF(msg_obj);
195 Py_XDECREF(conn_obj);
196 Py_XDECREF(callable);
197 PyGILState_Release(gil);
198 return ret;
201 PyDoc_STRVAR(Connection_close__doc__,
202 "close()\n\n"
203 "Close the connection.");
204 static PyObject *
205 Connection_close (Connection *self, PyObject *args)
207 if (!PyArg_ParseTuple(args, ":close")) return NULL;
208 /* Because the user explicitly asked to close the connection, we'll even
209 let them close shared connections. */
210 if (self->conn) {
211 Py_BEGIN_ALLOW_THREADS
212 dbus_connection_close (self->conn);
213 Py_END_ALLOW_THREADS
215 Py_RETURN_NONE;
218 PyDoc_STRVAR(Connection_get_is_connected__doc__,
219 "get_is_connected() -> bool\n\n"
220 "Return true if this Connection is connected.\n");
221 static PyObject *
222 Connection_get_is_connected (Connection *self, PyObject *args)
224 dbus_bool_t ret;
225 if (!PyArg_ParseTuple(args, ":get_is_connected")) return NULL;
226 Py_BEGIN_ALLOW_THREADS
227 ret = dbus_connection_get_is_connected (self->conn);
228 Py_END_ALLOW_THREADS
229 return PyBool_FromLong (ret);
232 PyDoc_STRVAR(Connection_get_is_authenticated__doc__,
233 "get_is_authenticated() -> bool\n\n"
234 "Return true if this Connection was ever authenticated.\n");
235 static PyObject *
236 Connection_get_is_authenticated (Connection *self, PyObject *args)
238 dbus_bool_t ret;
239 if (!PyArg_ParseTuple(args, ":get_is_authenticated")) return NULL;
240 Py_BEGIN_ALLOW_THREADS
241 ret = dbus_connection_get_is_authenticated (self->conn);
242 Py_END_ALLOW_THREADS
243 return PyBool_FromLong (ret);
246 PyDoc_STRVAR(Connection_set_exit_on_disconnect__doc__,
247 "set_exit_on_disconnect(bool)\n\n"
248 "Set whether the C function ``_exit`` will be called when this Connection\n"
249 "becomes disconnected. This will cause the program to exit without calling\n"
250 "any cleanup code or exit handlers.\n"
251 "\n"
252 "The default is for this feature to be disabled for Connections and enabled\n"
253 "for Buses.\n");
254 static PyObject *
255 Connection_set_exit_on_disconnect (Connection *self, PyObject *args)
257 int exit_on_disconnect;
258 if (!PyArg_ParseTuple(args, "i:set_exit_on_disconnect",
259 &exit_on_disconnect)) {
260 return NULL;
262 Py_BEGIN_ALLOW_THREADS
263 dbus_connection_set_exit_on_disconnect (self->conn,
264 exit_on_disconnect ? 1 : 0);
265 Py_END_ALLOW_THREADS
266 Py_RETURN_NONE;
269 PyDoc_STRVAR(Connection_send_message__doc__,
270 "send_message(msg) -> long\n\n"
271 "Queue the given message for sending, and return the message serial number.\n"
272 "\n"
273 ":Parameters:\n"
274 " `msg` : dbus.lowlevel.Message\n"
275 " The message to be sent.\n"
277 static PyObject *
278 Connection_send_message(Connection *self, PyObject *args)
280 dbus_bool_t ok;
281 PyObject *obj;
282 DBusMessage *msg;
283 dbus_uint32_t serial;
285 if (!PyArg_ParseTuple(args, "O", &obj)) return NULL;
287 msg = DBusPyMessage_BorrowDBusMessage(obj);
288 if (!msg) return NULL;
290 Py_BEGIN_ALLOW_THREADS
291 ok = dbus_connection_send(self->conn, msg, &serial);
292 Py_END_ALLOW_THREADS
294 if (!ok) {
295 return PyErr_NoMemory();
298 return PyLong_FromUnsignedLong(serial);
301 /* The timeout is in seconds here, since that's conventional in Python. */
302 PyDoc_STRVAR(Connection_send_message_with_reply__doc__,
303 "send_message_with_reply(msg: Message, reply_handler: callable[, timeout_s: float])"
304 " -> dbus.lowlevel.PendingCall\n\n"
305 "Queue the message for sending; expect a reply via the returned PendingCall.\n"
306 "\n"
307 ":Parameters:\n"
308 " `msg` : dbus.lowlevel.Message\n"
309 " The message to be sent\n"
310 " `reply_handler` : callable\n"
311 " Asynchronous reply handler: will be called with one positional\n"
312 " parameter, a Message instance representing the reply.\n"
313 " `timeout_s` : float\n"
314 " If the reply takes more than this many seconds, a timeout error\n"
315 " will be created locally and raised instead. If this timeout is\n"
316 " negative (default), a sane default (supplied by libdbus) is used.\n"
317 ":Returns:\n"
318 " A `dbus.lowlevel.PendingCall` instance which can be used to cancel the pending call.\n"
319 "\n"
321 static PyObject *
322 Connection_send_message_with_reply(Connection *self, PyObject *args)
324 dbus_bool_t ok;
325 double timeout_s = -1.0;
326 int timeout_ms;
327 PyObject *obj, *callable;
328 DBusMessage *msg;
329 DBusPendingCall *pending;
331 if (!PyArg_ParseTuple(args, "OO|f:send_message_with_reply", &obj, &callable,
332 &timeout_s)) {
333 return NULL;
336 msg = DBusPyMessage_BorrowDBusMessage(obj);
337 if (!msg) return NULL;
339 if (timeout_s < 0) {
340 timeout_ms = -1;
342 else {
343 if (timeout_s > ((double)INT_MAX) / 1000.0) {
344 PyErr_SetString(PyExc_ValueError, "Timeout too long");
345 return NULL;
347 timeout_ms = (int)(timeout_s * 1000.0);
350 Py_BEGIN_ALLOW_THREADS
351 ok = dbus_connection_send_with_reply(self->conn, msg, &pending,
352 timeout_ms);
353 Py_END_ALLOW_THREADS
355 if (!ok) {
356 return PyErr_NoMemory();
359 return DBusPyPendingCall_ConsumeDBusPendingCall(pending, callable);
362 /* Again, the timeout is in seconds, since that's conventional in Python. */
363 PyDoc_STRVAR(Connection_send_message_with_reply_and_block__doc__,
364 "send_message_with_reply_and_block(msg: dbus.lowlevel.Message, [, timeout_s: float])"
365 " -> dbus.lowlevel.Message\n\n"
366 "Send the message and block while waiting for a reply.\n"
367 "\n"
368 "This does not re-enter the main loop, so it can lead to a deadlock, if\n"
369 "the called method tries to make a synchronous call to a method in this\n"
370 "application. As such, it's probably a bad idea.\n"
371 "\n"
372 ":Parameters:\n"
373 " `msg` : dbus.lowlevel.Message\n"
374 " The message to be sent\n"
375 " `timeout_s` : float\n"
376 " If the reply takes more than this many seconds, a timeout error\n"
377 " will be created locally and raised instead. If this timeout is\n"
378 " negative (default), a sane default (supplied by libdbus) is used.\n"
379 ":Returns:\n"
380 " A `dbus.lowlevel.Message` instance (probably a `dbus.lowlevel.MethodReturnMessage`) on success\n"
381 ":Raises dbus.DBusException:\n"
382 " On error (including if the reply arrives but is an\n"
383 " error message)\n"
384 "\n"
386 static PyObject *
387 Connection_send_message_with_reply_and_block(Connection *self, PyObject *args)
389 double timeout_s = -1.0;
390 int timeout_ms;
391 PyObject *obj;
392 DBusMessage *msg, *reply;
393 DBusError error;
395 if (!PyArg_ParseTuple(args, "O|f:send_message_with_reply_and_block", &obj,
396 &timeout_s)) {
397 return NULL;
400 msg = DBusPyMessage_BorrowDBusMessage(obj);
401 if (!msg) return NULL;
403 if (timeout_s < 0) {
404 timeout_ms = -1;
406 else {
407 if (timeout_s > ((double)INT_MAX) / 1000.0) {
408 PyErr_SetString(PyExc_ValueError, "Timeout too long");
409 return NULL;
411 timeout_ms = (int)(timeout_s * 1000.0);
414 dbus_error_init(&error);
415 Py_BEGIN_ALLOW_THREADS
416 reply = dbus_connection_send_with_reply_and_block(self->conn, msg,
417 timeout_ms, &error);
418 Py_END_ALLOW_THREADS
420 if (!reply) {
421 return DBusPyException_ConsumeError(&error);
423 return DBusPyMessage_ConsumeDBusMessage(reply);
426 PyDoc_STRVAR(Connection_flush__doc__,
427 "flush()\n\n"
428 "Block until the outgoing message queue is empty.\n");
429 static PyObject *
430 Connection_flush (Connection *self, PyObject *args UNUSED)
432 Py_BEGIN_ALLOW_THREADS
433 dbus_connection_flush (self->conn);
434 Py_END_ALLOW_THREADS
435 Py_RETURN_NONE;
438 /* Unsupported:
439 * dbus_connection_preallocate_send
440 * dbus_connection_free_preallocated_send
441 * dbus_connection_send_preallocated
442 * dbus_connection_borrow_message
443 * dbus_connection_return_message
444 * dbus_connection_steal_borrowed_message
445 * dbus_connection_pop_message
448 /* Non-main-loop handling not yet implemented: */
449 /* dbus_connection_read_write_dispatch */
450 /* dbus_connection_read_write */
452 /* Main loop handling not yet implemented: */
453 /* dbus_connection_get_dispatch_status */
454 /* dbus_connection_dispatch */
455 /* dbus_connection_set_watch_functions */
456 /* dbus_connection_set_timeout_functions */
457 /* dbus_connection_set_wakeup_main_function */
458 /* dbus_connection_set_dispatch_status_function */
460 /* Normally in Python this would be called fileno(), but I don't want to
461 * encourage people to select() on it */
462 PyDoc_STRVAR(Connection_get_unix_fd__doc__,
463 "get_unix_fd() -> int or None\n\n"
464 "Get the connection's UNIX file descriptor, if any.\n\n"
465 "This can be used for SELinux access control checks with ``getpeercon()``\n"
466 "for example. **Do not** read or write to the file descriptor, or try to\n"
467 "``select()`` on it.\n");
468 static PyObject *
469 Connection_get_unix_fd (Connection *self, PyObject *unused UNUSED)
471 int fd;
472 dbus_bool_t ok;
474 Py_BEGIN_ALLOW_THREADS
475 ok = dbus_connection_get_unix_fd (self->conn, &fd);
476 Py_END_ALLOW_THREADS
477 if (!ok) Py_RETURN_NONE;
478 return PyInt_FromLong(fd);
481 PyDoc_STRVAR(Connection_get_peer_unix_user__doc__,
482 "get_peer_unix_user() -> long or None\n\n"
483 "Get the UNIX user ID at the other end of the connection, if it has been\n"
484 "authenticated. Return None if this is a non-UNIX platform or the\n"
485 "connection has not been authenticated.\n");
486 static PyObject *
487 Connection_get_peer_unix_user (Connection *self, PyObject *unused UNUSED)
489 unsigned long uid;
490 dbus_bool_t ok;
492 Py_BEGIN_ALLOW_THREADS
493 ok = dbus_connection_get_unix_user (self->conn, &uid);
494 Py_END_ALLOW_THREADS
495 if (!ok) Py_RETURN_NONE;
496 return PyLong_FromUnsignedLong (uid);
499 PyDoc_STRVAR(Connection_get_peer_unix_process_id__doc__,
500 "get_peer_unix_process_id() -> long or None\n\n"
501 "Get the UNIX process ID at the other end of the connection, if it has been\n"
502 "authenticated. Return None if this is a non-UNIX platform or the\n"
503 "connection has not been authenticated.\n");
504 static PyObject *
505 Connection_get_peer_unix_process_id (Connection *self, PyObject *unused UNUSED)
507 unsigned long pid;
508 dbus_bool_t ok;
510 Py_BEGIN_ALLOW_THREADS
511 ok = dbus_connection_get_unix_process_id (self->conn, &pid);
512 Py_END_ALLOW_THREADS
513 if (!ok) Py_RETURN_NONE;
514 return PyLong_FromUnsignedLong (pid);
517 /* TODO: wrap dbus_connection_set_unix_user_function Pythonically */
519 PyDoc_STRVAR(Connection_add_message_filter__doc__,
520 "add_message_filter(callable)\n\n"
521 "Add the given message filter to the internal list.\n\n"
522 "Filters are handlers that are run on all incoming messages, prior to the\n"
523 "objects registered to handle object paths.\n"
524 "\n"
525 "Filters are run in the order that they were added. The same handler can\n"
526 "be added as a filter more than once, in which case it will be run more\n"
527 "than once. Filters added during a filter callback won't be run on the\n"
528 "message being processed.\n"
530 static PyObject *
531 Connection_add_message_filter(Connection *self, PyObject *callable)
533 dbus_bool_t ok;
535 /* The callable must be referenced by ->filters *before* it is
536 * given to libdbus, which does not own a reference to it.
538 if (PyList_Append(self->filters, callable) < 0) {
539 return NULL;
542 Py_BEGIN_ALLOW_THREADS
543 ok = dbus_connection_add_filter(self->conn, _filter_message, callable,
544 NULL);
545 Py_END_ALLOW_THREADS
547 if (!ok) {
548 Py_XDECREF(PyObject_CallMethod(self->filters, "remove", "(O)",
549 callable));
550 PyErr_NoMemory();
551 return NULL;
553 Py_RETURN_NONE;
556 PyDoc_STRVAR(Connection_remove_message_filter__doc__,
557 "remove_message_filter(callable)\n\n"
558 "Remove the given message filter (see `add_message_filter` for details).\n"
559 "\n"
560 ":Raises LookupError:\n"
561 " The given callable is not among the registered filters\n");
562 static PyObject *
563 Connection_remove_message_filter(Connection *self, PyObject *callable)
565 PyObject *obj;
567 /* It's safe to do this before removing it from libdbus, because
568 * the presence of callable in our arguments means we have a ref
569 * to it. */
570 obj = PyObject_CallMethod(self->filters, "remove", "(O)", callable);
571 if (!obj) return NULL;
572 Py_DECREF(obj);
574 Py_BEGIN_ALLOW_THREADS
575 dbus_connection_remove_filter(self->conn, _filter_message, callable);
576 Py_END_ALLOW_THREADS
578 Py_RETURN_NONE;
581 PyDoc_STRVAR(Connection__register_object_path__doc__,
582 "register_object_path(path: str, on_message: callable[, on_unregister: "
583 "callable[, fallback: bool]])\n"
584 "\n"
585 "Register a callback to be called when messages arrive at the given\n"
586 "object-path. Used to export objects' methods on the bus in a low-level\n"
587 "way. For the high-level interface to this functionality (usually\n"
588 "recommended) see the `dbus.service.Object` base class.\n"
589 "\n"
590 ":Parameters:\n"
591 " `path` : str\n"
592 " Object path to be acted on\n"
593 " `on_message` : callable\n"
594 " Called when a message arrives at the given object-path, with\n"
595 " two positional parameters: the first is this Connection,\n"
596 " the second is the incoming `dbus.lowlevel.Message`.\n"
597 " `fallback` : bool\n"
598 " If True (the default is False), when a message arrives for a\n"
599 " 'subdirectory' of the given path and there is no more specific\n"
600 " handler, use this handler. Normally this handler is only run if\n"
601 " the paths match exactly.\n"
603 static PyObject *
604 Connection__register_object_path(Connection *self, PyObject *args,
605 PyObject *kwargs)
607 dbus_bool_t ok;
608 int fallback = 0;
609 PyObject *callbacks, *path, *tuple, *on_message, *on_unregister = Py_None;
610 static char *argnames[] = {"path", "on_message", "on_unregister",
611 "fallback", NULL};
613 if (!PyArg_ParseTupleAndKeywords(args, kwargs,
614 "OO|Oi:_register_object_path",
615 argnames,
616 &path,
617 &on_message, &on_unregister,
618 &fallback)) return NULL;
620 /* Take a reference to path, which we give away to libdbus in a moment.
622 Also, path needs to be a string (not a subclass which could do something
623 mad) to preserve the desirable property that the DBusConnection can
624 never strongly reference the Connection, even indirectly.
626 if (PyString_CheckExact(path)) {
627 Py_INCREF(path);
629 else if (PyUnicode_Check(path)) {
630 path = PyUnicode_AsUTF8String(path);
631 if (!path) return NULL;
633 else if (PyString_Check(path)) {
634 path = PyString_FromString(PyString_AS_STRING(path));
635 if (!path) return NULL;
637 else {
638 PyErr_SetString(PyExc_TypeError, "path must be a str or unicode object");
639 return NULL;
642 if (!dbus_py_validate_object_path(PyString_AS_STRING(path))) {
643 Py_DECREF(path);
644 return NULL;
647 tuple = Py_BuildValue("(OO)", on_unregister, on_message);
648 if (!tuple) {
649 Py_DECREF(path);
650 return NULL;
653 /* Guard against registering a handler that already exists. */
654 callbacks = PyDict_GetItem(self->object_paths, path);
655 if (callbacks && callbacks != Py_None) {
656 PyErr_Format(PyExc_KeyError, "Can't register the object-path "
657 "handler for '%s': there is already a handler",
658 PyString_AS_STRING(path));
659 Py_DECREF(tuple);
660 Py_DECREF(path);
661 return NULL;
664 /* Pre-allocate a slot in the dictionary, so we know we'll be able
665 * to replace it with the callbacks without OOM.
666 * This ensures we can keep libdbus' opinion of whether those
667 * paths are handled in sync with our own. */
668 if (PyDict_SetItem(self->object_paths, path, Py_None) < 0) {
669 Py_DECREF(tuple);
670 Py_DECREF(path);
671 return NULL;
674 Py_BEGIN_ALLOW_THREADS
675 if (fallback) {
676 ok = dbus_connection_register_fallback(self->conn,
677 PyString_AS_STRING(path),
678 &_object_path_vtable,
679 path);
681 else {
682 ok = dbus_connection_register_object_path(self->conn,
683 PyString_AS_STRING(path),
684 &_object_path_vtable,
685 path);
687 Py_END_ALLOW_THREADS
689 if (ok) {
690 if (PyDict_SetItem(self->object_paths, path, tuple) < 0) {
691 /* That shouldn't have happened, we already allocated enough
692 memory for it. Oh well, try to undo the registration to keep
693 things in sync. If this fails too, we've leaked a bit of
694 memory in libdbus, but tbh we should never get here anyway. */
695 Py_BEGIN_ALLOW_THREADS
696 ok = dbus_connection_unregister_object_path(self->conn,
697 PyString_AS_STRING(path));
698 Py_END_ALLOW_THREADS
699 return NULL;
701 /* don't DECREF path: libdbus owns a ref now */
702 Py_DECREF(tuple);
703 Py_RETURN_NONE;
705 else {
706 /* Oops, OOM. Tidy up, if we can, ignoring any error. */
707 PyDict_DelItem(self->object_paths, path);
708 PyErr_Clear();
709 Py_DECREF(tuple);
710 Py_DECREF(path);
711 PyErr_NoMemory();
712 return NULL;
716 PyDoc_STRVAR(Connection__unregister_object_path__doc__,
717 "unregister_object_path(path: str)\n\n"
718 "Remove a previously registered handler for the given object path.\n"
719 "\n"
720 ":Parameters:\n"
721 " `path` : str\n"
722 " The object path whose handler is to be removed\n"
723 ":Raises KeyError: if there is no handler registered for exactly that\n"
724 " object path.\n"
726 static PyObject *
727 Connection__unregister_object_path(Connection *self, PyObject *args,
728 PyObject *kwargs)
730 dbus_bool_t ok;
731 PyObject *path;
732 PyObject *callbacks;
733 static char *argnames[] = {"path", NULL};
735 if (!PyArg_ParseTupleAndKeywords(args, kwargs,
736 "O:_unregister_object_path",
737 argnames, &path)) return NULL;
739 /* Take a ref to the path. Same comments as for _register_object_path. */
740 if (PyString_CheckExact(path)) {
741 Py_INCREF(path);
743 else if (PyUnicode_Check(path)) {
744 path = PyUnicode_AsUTF8String(path);
745 if (!path) return NULL;
747 else if (PyString_Check(path)) {
748 path = PyString_FromString(PyString_AS_STRING(path));
749 if (!path) return NULL;
751 else {
752 PyErr_SetString(PyExc_TypeError, "path must be a str or unicode object");
753 return NULL;
756 /* Guard against unregistering a handler that doesn't, in fact, exist,
757 or whose unregistration is already in progress. */
758 callbacks = PyDict_GetItem(self->object_paths, path);
759 if (!callbacks || callbacks == Py_None) {
760 PyErr_Format(PyExc_KeyError, "Can't unregister the object-path "
761 "handler for '%s': there is no such handler",
762 PyString_AS_STRING(path));
763 Py_DECREF(path);
764 return NULL;
767 /* Hang on to a reference to the callbacks for the moment. */
768 Py_INCREF(callbacks);
770 /* Get rid of the object-path while we still have the GIL, to
771 guard against unregistering twice from different threads (which
772 causes undefined behaviour in libdbus).
774 Because deletion would make it possible for the re-insertion below
775 to fail, we instead set the handler to None as a placeholder.
777 if (PyDict_SetItem(self->object_paths, path, Py_None) < 0) {
778 /* If that failed, there's no need to be paranoid as below - the
779 callbacks are still set, so we failed, but at least everything
780 is in sync. */
781 Py_DECREF(callbacks);
782 Py_DECREF(path);
783 return NULL;
786 /* BEGIN PARANOIA
787 This is something of a critical section - the dict of object-paths
788 and libdbus' internal structures are out of sync for a bit. We have
789 to be able to cope with that.
791 It's really annoying that dbus_connection_unregister_object_path
792 can fail, *and* has undefined behaviour if the object path has
793 already been unregistered. Either/or would be fine.
796 Py_BEGIN_ALLOW_THREADS
797 ok = dbus_connection_unregister_object_path(self->conn,
798 PyString_AS_STRING(path));
799 Py_END_ALLOW_THREADS
801 if (ok) {
802 Py_DECREF(callbacks);
803 PyDict_DelItem(self->object_paths, path);
804 /* END PARANOIA on successful code path */
805 /* The above can't fail unless by some strange trickery the key is no
806 longer present. Ignore any errors. */
807 Py_DECREF(path);
808 PyErr_Clear();
809 Py_RETURN_NONE;
811 else {
812 /* Oops, OOM. Put the callbacks back in the dict so
813 * we'll have another go if/when the user frees some memory
814 * and tries calling this method again. */
815 PyDict_SetItem(self->object_paths, path, callbacks);
816 /* END PARANOIA on failing code path */
817 /* If the SetItem failed, there's nothing we can do about it - but
818 since we know it's an existing entry, it shouldn't be able to fail
819 anyway. */
820 Py_DECREF(path);
821 Py_DECREF(callbacks);
822 return PyErr_NoMemory();
826 /* dbus_connection_get_object_path_data - not useful to Python,
827 * the object path data is just a PyString containing the path */
828 /* dbus_connection_list_registered could be useful, though */
830 /* dbus_connection_set_change_sigpipe - sets global state */
832 /* Maxima. Does Python code ever need to manipulate these?
833 * OTOH they're easy to wrap */
834 /* dbus_connection_set_max_message_size */
835 /* dbus_connection_get_max_message_size */
836 /* dbus_connection_set_max_received_size */
837 /* dbus_connection_get_max_received_size */
839 /* dbus_connection_get_outgoing_size - almost certainly unneeded */
841 struct PyMethodDef DBusPyConnection_tp_methods[] = {
842 #define ENTRY(name, flags) {#name, (PyCFunction)Connection_##name, flags, Connection_##name##__doc__}
843 ENTRY(close, METH_NOARGS),
844 ENTRY(flush, METH_NOARGS),
845 ENTRY(get_is_connected, METH_NOARGS),
846 ENTRY(get_is_authenticated, METH_NOARGS),
847 ENTRY(set_exit_on_disconnect, METH_VARARGS),
848 ENTRY(get_unix_fd, METH_NOARGS),
849 ENTRY(get_peer_unix_user, METH_NOARGS),
850 ENTRY(get_peer_unix_process_id, METH_NOARGS),
851 ENTRY(add_message_filter, METH_O),
852 ENTRY(_register_object_path, METH_VARARGS|METH_KEYWORDS),
853 ENTRY(remove_message_filter, METH_O),
854 ENTRY(send_message, METH_VARARGS),
855 ENTRY(send_message_with_reply, METH_VARARGS),
856 ENTRY(send_message_with_reply_and_block, METH_VARARGS),
857 ENTRY(_unregister_object_path, METH_VARARGS|METH_KEYWORDS),
858 {NULL},
859 #undef ENTRY
862 /* vim:set ft=c cino< sw=4 sts=4 et: */