Remove old libxml2-based introspection parser
[dbus-python-phuang.git] / _dbus_bindings / conn-methods.c
blob4ae56084e9f725b72a5b225702c7a27f002b8dbd
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 int 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_close__doc__,
205 "close()\n\n"
206 "Close the connection.");
207 static PyObject *
208 Connection_close (Connection *self, PyObject *args)
210 TRACE(self);
211 if (!PyArg_ParseTuple(args, ":close")) return NULL;
212 /* Because the user explicitly asked to close the connection, we'll even
213 let them close shared connections. */
214 if (self->conn) {
215 Py_BEGIN_ALLOW_THREADS
216 dbus_connection_close(self->conn);
217 Py_END_ALLOW_THREADS
219 Py_RETURN_NONE;
222 PyDoc_STRVAR(Connection_get_is_connected__doc__,
223 "get_is_connected() -> bool\n\n"
224 "Return true if this Connection is connected.\n");
225 static PyObject *
226 Connection_get_is_connected (Connection *self, PyObject *args)
228 dbus_bool_t ret;
230 TRACE(self);
231 DBUS_PY_RAISE_VIA_NULL_IF_FAIL(self->conn);
232 if (!PyArg_ParseTuple(args, ":get_is_connected")) return NULL;
233 Py_BEGIN_ALLOW_THREADS
234 ret = dbus_connection_get_is_connected(self->conn);
235 Py_END_ALLOW_THREADS
236 return PyBool_FromLong(ret);
239 PyDoc_STRVAR(Connection_get_is_authenticated__doc__,
240 "get_is_authenticated() -> bool\n\n"
241 "Return true if this Connection was ever authenticated.\n");
242 static PyObject *
243 Connection_get_is_authenticated (Connection *self, PyObject *args)
245 dbus_bool_t ret;
247 TRACE(self);
248 DBUS_PY_RAISE_VIA_NULL_IF_FAIL(self->conn);
249 if (!PyArg_ParseTuple(args, ":get_is_authenticated")) return NULL;
250 Py_BEGIN_ALLOW_THREADS
251 ret = dbus_connection_get_is_authenticated(self->conn);
252 Py_END_ALLOW_THREADS
253 return PyBool_FromLong(ret);
256 PyDoc_STRVAR(Connection_set_exit_on_disconnect__doc__,
257 "set_exit_on_disconnect(bool)\n\n"
258 "Set whether the C function ``_exit`` will be called when this Connection\n"
259 "becomes disconnected. This will cause the program to exit without calling\n"
260 "any cleanup code or exit handlers.\n"
261 "\n"
262 "The default is for this feature to be disabled for Connections and enabled\n"
263 "for Buses.\n");
264 static PyObject *
265 Connection_set_exit_on_disconnect (Connection *self, PyObject *args)
267 int exit_on_disconnect;
269 TRACE(self);
270 DBUS_PY_RAISE_VIA_NULL_IF_FAIL(self->conn);
271 if (!PyArg_ParseTuple(args, "i:set_exit_on_disconnect",
272 &exit_on_disconnect)) {
273 return NULL;
275 Py_BEGIN_ALLOW_THREADS
276 dbus_connection_set_exit_on_disconnect(self->conn,
277 exit_on_disconnect ? 1 : 0);
278 Py_END_ALLOW_THREADS
279 Py_RETURN_NONE;
282 PyDoc_STRVAR(Connection_send_message__doc__,
283 "send_message(msg) -> long\n\n"
284 "Queue the given message for sending, and return the message serial number.\n"
285 "\n"
286 ":Parameters:\n"
287 " `msg` : dbus.lowlevel.Message\n"
288 " The message to be sent.\n"
290 static PyObject *
291 Connection_send_message(Connection *self, PyObject *args)
293 dbus_bool_t ok;
294 PyObject *obj;
295 DBusMessage *msg;
296 dbus_uint32_t serial;
298 TRACE(self);
299 DBUS_PY_RAISE_VIA_NULL_IF_FAIL(self->conn);
300 if (!PyArg_ParseTuple(args, "O", &obj)) return NULL;
302 msg = DBusPyMessage_BorrowDBusMessage(obj);
303 if (!msg) return NULL;
305 Py_BEGIN_ALLOW_THREADS
306 ok = dbus_connection_send(self->conn, msg, &serial);
307 Py_END_ALLOW_THREADS
309 if (!ok) {
310 return PyErr_NoMemory();
313 return PyLong_FromUnsignedLong(serial);
316 /* The timeout is in seconds here, since that's conventional in Python. */
317 PyDoc_STRVAR(Connection_send_message_with_reply__doc__,
318 "send_message_with_reply(msg, reply_handler, timeout_s=-1)"
319 " -> dbus.lowlevel.PendingCall\n\n"
320 "Queue the message for sending; expect a reply via the returned PendingCall,\n"
321 "which can also be used to cancel the pending call.\n"
322 "\n"
323 ":Parameters:\n"
324 " `msg` : dbus.lowlevel.Message\n"
325 " The message to be sent\n"
326 " `reply_handler` : callable\n"
327 " Asynchronous reply handler: will be called with one positional\n"
328 " parameter, a Message instance representing the reply.\n"
329 " `timeout_s` : float\n"
330 " If the reply takes more than this many seconds, a timeout error\n"
331 " will be created locally and raised instead. If this timeout is\n"
332 " negative (default), a sane default (supplied by libdbus) is used.\n"
333 "\n"
335 static PyObject *
336 Connection_send_message_with_reply(Connection *self, PyObject *args)
338 dbus_bool_t ok;
339 double timeout_s = -1.0;
340 int timeout_ms;
341 PyObject *obj, *callable;
342 DBusMessage *msg;
343 DBusPendingCall *pending;
345 TRACE(self);
346 DBUS_PY_RAISE_VIA_NULL_IF_FAIL(self->conn);
347 if (!PyArg_ParseTuple(args, "OO|f:send_message_with_reply", &obj, &callable,
348 &timeout_s)) {
349 return NULL;
352 msg = DBusPyMessage_BorrowDBusMessage(obj);
353 if (!msg) return NULL;
355 if (timeout_s < 0) {
356 timeout_ms = -1;
358 else {
359 if (timeout_s > ((double)INT_MAX) / 1000.0) {
360 PyErr_SetString(PyExc_ValueError, "Timeout too long");
361 return NULL;
363 timeout_ms = (int)(timeout_s * 1000.0);
366 Py_BEGIN_ALLOW_THREADS
367 ok = dbus_connection_send_with_reply(self->conn, msg, &pending,
368 timeout_ms);
369 Py_END_ALLOW_THREADS
371 if (!ok) {
372 return PyErr_NoMemory();
375 return DBusPyPendingCall_ConsumeDBusPendingCall(pending, callable);
378 /* Again, the timeout is in seconds, since that's conventional in Python. */
379 PyDoc_STRVAR(Connection_send_message_with_reply_and_block__doc__,
380 "send_message_with_reply_and_block(msg, timeout_s=-1)"
381 " -> dbus.lowlevel.Message\n\n"
382 "Send the message and block while waiting for a reply.\n"
383 "\n"
384 "This does not re-enter the main loop, so it can lead to a deadlock, if\n"
385 "the called method tries to make a synchronous call to a method in this\n"
386 "application. As such, it's probably a bad idea.\n"
387 "\n"
388 ":Parameters:\n"
389 " `msg` : dbus.lowlevel.Message\n"
390 " The message to be sent\n"
391 " `timeout_s` : float\n"
392 " If the reply takes more than this many seconds, a timeout error\n"
393 " will be created locally and raised instead. If this timeout is\n"
394 " negative (default), a sane default (supplied by libdbus) is used.\n"
395 ":Returns:\n"
396 " A `dbus.lowlevel.Message` instance (probably a `dbus.lowlevel.MethodReturnMessage`) on success\n"
397 ":Raises dbus.DBusException:\n"
398 " On error (including if the reply arrives but is an\n"
399 " error message)\n"
400 "\n"
402 static PyObject *
403 Connection_send_message_with_reply_and_block(Connection *self, PyObject *args)
405 double timeout_s = -1.0;
406 int timeout_ms;
407 PyObject *obj;
408 DBusMessage *msg, *reply;
409 DBusError error;
411 TRACE(self);
412 DBUS_PY_RAISE_VIA_NULL_IF_FAIL(self->conn);
413 if (!PyArg_ParseTuple(args, "O|f:send_message_with_reply_and_block", &obj,
414 &timeout_s)) {
415 return NULL;
418 msg = DBusPyMessage_BorrowDBusMessage(obj);
419 if (!msg) return NULL;
421 if (timeout_s < 0) {
422 timeout_ms = -1;
424 else {
425 if (timeout_s > ((double)INT_MAX) / 1000.0) {
426 PyErr_SetString(PyExc_ValueError, "Timeout too long");
427 return NULL;
429 timeout_ms = (int)(timeout_s * 1000.0);
432 dbus_error_init(&error);
433 Py_BEGIN_ALLOW_THREADS
434 reply = dbus_connection_send_with_reply_and_block(self->conn, msg,
435 timeout_ms, &error);
436 Py_END_ALLOW_THREADS
438 if (!reply) {
439 return DBusPyException_ConsumeError(&error);
441 return DBusPyMessage_ConsumeDBusMessage(reply);
444 PyDoc_STRVAR(Connection_flush__doc__,
445 "flush()\n\n"
446 "Block until the outgoing message queue is empty.\n");
447 static PyObject *
448 Connection_flush (Connection *self, PyObject *args UNUSED)
450 TRACE(self);
451 DBUS_PY_RAISE_VIA_NULL_IF_FAIL(self->conn);
452 Py_BEGIN_ALLOW_THREADS
453 dbus_connection_flush (self->conn);
454 Py_END_ALLOW_THREADS
455 Py_RETURN_NONE;
458 /* Unsupported:
459 * dbus_connection_preallocate_send
460 * dbus_connection_free_preallocated_send
461 * dbus_connection_send_preallocated
462 * dbus_connection_borrow_message
463 * dbus_connection_return_message
464 * dbus_connection_steal_borrowed_message
465 * dbus_connection_pop_message
468 /* Non-main-loop handling not yet implemented: */
469 /* dbus_connection_read_write_dispatch */
470 /* dbus_connection_read_write */
472 /* Main loop handling not yet implemented: */
473 /* dbus_connection_get_dispatch_status */
474 /* dbus_connection_dispatch */
475 /* dbus_connection_set_watch_functions */
476 /* dbus_connection_set_timeout_functions */
477 /* dbus_connection_set_wakeup_main_function */
478 /* dbus_connection_set_dispatch_status_function */
480 /* Normally in Python this would be called fileno(), but I don't want to
481 * encourage people to select() on it */
482 PyDoc_STRVAR(Connection_get_unix_fd__doc__,
483 "get_unix_fd() -> int or None\n\n"
484 "Get the connection's UNIX file descriptor, if any.\n\n"
485 "This can be used for SELinux access control checks with ``getpeercon()``\n"
486 "for example. **Do not** read or write to the file descriptor, or try to\n"
487 "``select()`` on it.\n");
488 static PyObject *
489 Connection_get_unix_fd (Connection *self, PyObject *unused UNUSED)
491 int fd;
492 dbus_bool_t ok;
494 TRACE(self);
495 DBUS_PY_RAISE_VIA_NULL_IF_FAIL(self->conn);
496 Py_BEGIN_ALLOW_THREADS
497 ok = dbus_connection_get_unix_fd (self->conn, &fd);
498 Py_END_ALLOW_THREADS
499 if (!ok) Py_RETURN_NONE;
500 return PyInt_FromLong(fd);
503 PyDoc_STRVAR(Connection_get_peer_unix_user__doc__,
504 "get_peer_unix_user() -> long or None\n\n"
505 "Get the UNIX user ID at the other end of the connection, if it has been\n"
506 "authenticated. Return None if this is a non-UNIX platform or the\n"
507 "connection has not been authenticated.\n");
508 static PyObject *
509 Connection_get_peer_unix_user (Connection *self, PyObject *unused UNUSED)
511 unsigned long uid;
512 dbus_bool_t ok;
514 TRACE(self);
515 DBUS_PY_RAISE_VIA_NULL_IF_FAIL(self->conn);
516 Py_BEGIN_ALLOW_THREADS
517 ok = dbus_connection_get_unix_user (self->conn, &uid);
518 Py_END_ALLOW_THREADS
519 if (!ok) Py_RETURN_NONE;
520 return PyLong_FromUnsignedLong (uid);
523 PyDoc_STRVAR(Connection_get_peer_unix_process_id__doc__,
524 "get_peer_unix_process_id() -> long or None\n\n"
525 "Get the UNIX process ID at the other end of the connection, if it has been\n"
526 "authenticated. Return None if this is a non-UNIX platform or the\n"
527 "connection has not been authenticated.\n");
528 static PyObject *
529 Connection_get_peer_unix_process_id (Connection *self, PyObject *unused UNUSED)
531 unsigned long pid;
532 dbus_bool_t ok;
534 TRACE(self);
535 DBUS_PY_RAISE_VIA_NULL_IF_FAIL(self->conn);
536 Py_BEGIN_ALLOW_THREADS
537 ok = dbus_connection_get_unix_process_id (self->conn, &pid);
538 Py_END_ALLOW_THREADS
539 if (!ok) Py_RETURN_NONE;
540 return PyLong_FromUnsignedLong (pid);
543 /* TODO: wrap dbus_connection_set_unix_user_function Pythonically */
545 PyDoc_STRVAR(Connection_add_message_filter__doc__,
546 "add_message_filter(callable)\n\n"
547 "Add the given message filter to the internal list.\n\n"
548 "Filters are handlers that are run on all incoming messages, prior to the\n"
549 "objects registered to handle object paths.\n"
550 "\n"
551 "Filters are run in the order that they were added. The same handler can\n"
552 "be added as a filter more than once, in which case it will be run more\n"
553 "than once. Filters added during a filter callback won't be run on the\n"
554 "message being processed.\n"
556 static PyObject *
557 Connection_add_message_filter(Connection *self, PyObject *callable)
559 dbus_bool_t ok;
561 TRACE(self);
562 DBUS_PY_RAISE_VIA_NULL_IF_FAIL(self->conn);
563 /* The callable must be referenced by ->filters *before* it is
564 * given to libdbus, which does not own a reference to it.
566 if (PyList_Append(self->filters, callable) < 0) {
567 return NULL;
570 Py_BEGIN_ALLOW_THREADS
571 ok = dbus_connection_add_filter(self->conn, _filter_message, callable,
572 NULL);
573 Py_END_ALLOW_THREADS
575 if (!ok) {
576 Py_XDECREF(PyObject_CallMethod(self->filters, "remove", "(O)",
577 callable));
578 PyErr_NoMemory();
579 return NULL;
581 Py_RETURN_NONE;
584 PyDoc_STRVAR(Connection_remove_message_filter__doc__,
585 "remove_message_filter(callable)\n\n"
586 "Remove the given message filter (see `add_message_filter` for details).\n"
587 "\n"
588 ":Raises LookupError:\n"
589 " The given callable is not among the registered filters\n");
590 static PyObject *
591 Connection_remove_message_filter(Connection *self, PyObject *callable)
593 PyObject *obj;
595 TRACE(self);
596 DBUS_PY_RAISE_VIA_NULL_IF_FAIL(self->conn);
597 /* It's safe to do this before removing it from libdbus, because
598 * the presence of callable in our arguments means we have a ref
599 * to it. */
600 obj = PyObject_CallMethod(self->filters, "remove", "(O)", callable);
601 if (!obj) return NULL;
602 Py_DECREF(obj);
604 Py_BEGIN_ALLOW_THREADS
605 dbus_connection_remove_filter(self->conn, _filter_message, callable);
606 Py_END_ALLOW_THREADS
608 Py_RETURN_NONE;
611 PyDoc_STRVAR(Connection__register_object_path__doc__,
612 "register_object_path(path, on_message, on_unregister=None, fallback=False)\n"
613 "\n"
614 "Register a callback to be called when messages arrive at the given\n"
615 "object-path. Used to export objects' methods on the bus in a low-level\n"
616 "way. For the high-level interface to this functionality (usually\n"
617 "recommended) see the `dbus.service.Object` base class.\n"
618 "\n"
619 ":Parameters:\n"
620 " `path` : str\n"
621 " Object path to be acted on\n"
622 " `on_message` : callable\n"
623 " Called when a message arrives at the given object-path, with\n"
624 " two positional parameters: the first is this Connection,\n"
625 " the second is the incoming `dbus.lowlevel.Message`.\n"
626 " `on_unregister` : callable or None\n"
627 " If not None, called when the callback is unregistered.\n"
628 " `fallback` : bool\n"
629 " If True (the default is False), when a message arrives for a\n"
630 " 'subdirectory' of the given path and there is no more specific\n"
631 " handler, use this handler. Normally this handler is only run if\n"
632 " the paths match exactly.\n"
634 static PyObject *
635 Connection__register_object_path(Connection *self, PyObject *args,
636 PyObject *kwargs)
638 dbus_bool_t ok;
639 int fallback = 0;
640 PyObject *callbacks, *path, *tuple, *on_message, *on_unregister = Py_None;
641 static char *argnames[] = {"path", "on_message", "on_unregister",
642 "fallback", NULL};
644 TRACE(self);
645 DBUS_PY_RAISE_VIA_NULL_IF_FAIL(self->conn);
646 if (!PyArg_ParseTupleAndKeywords(args, kwargs,
647 "OO|Oi:_register_object_path",
648 argnames,
649 &path,
650 &on_message, &on_unregister,
651 &fallback)) return NULL;
653 /* Take a reference to path, which we give away to libdbus in a moment.
655 Also, path needs to be a string (not a subclass which could do something
656 mad) to preserve the desirable property that the DBusConnection can
657 never strongly reference the Connection, even indirectly.
659 if (PyString_CheckExact(path)) {
660 Py_INCREF(path);
662 else if (PyUnicode_Check(path)) {
663 path = PyUnicode_AsUTF8String(path);
664 if (!path) return NULL;
666 else if (PyString_Check(path)) {
667 path = PyString_FromString(PyString_AS_STRING(path));
668 if (!path) return NULL;
670 else {
671 PyErr_SetString(PyExc_TypeError, "path must be a str or unicode object");
672 return NULL;
675 if (!dbus_py_validate_object_path(PyString_AS_STRING(path))) {
676 Py_DECREF(path);
677 return NULL;
680 tuple = Py_BuildValue("(OO)", on_unregister, on_message);
681 if (!tuple) {
682 Py_DECREF(path);
683 return NULL;
686 /* Guard against registering a handler that already exists. */
687 callbacks = PyDict_GetItem(self->object_paths, path);
688 if (callbacks && callbacks != Py_None) {
689 PyErr_Format(PyExc_KeyError, "Can't register the object-path "
690 "handler for '%s': there is already a handler",
691 PyString_AS_STRING(path));
692 Py_DECREF(tuple);
693 Py_DECREF(path);
694 return NULL;
697 /* Pre-allocate a slot in the dictionary, so we know we'll be able
698 * to replace it with the callbacks without OOM.
699 * This ensures we can keep libdbus' opinion of whether those
700 * paths are handled in sync with our own. */
701 if (PyDict_SetItem(self->object_paths, path, Py_None) < 0) {
702 Py_DECREF(tuple);
703 Py_DECREF(path);
704 return NULL;
707 Py_BEGIN_ALLOW_THREADS
708 if (fallback) {
709 ok = dbus_connection_register_fallback(self->conn,
710 PyString_AS_STRING(path),
711 &_object_path_vtable,
712 path);
714 else {
715 ok = dbus_connection_register_object_path(self->conn,
716 PyString_AS_STRING(path),
717 &_object_path_vtable,
718 path);
720 Py_END_ALLOW_THREADS
722 if (ok) {
723 if (PyDict_SetItem(self->object_paths, path, tuple) < 0) {
724 /* That shouldn't have happened, we already allocated enough
725 memory for it. Oh well, try to undo the registration to keep
726 things in sync. If this fails too, we've leaked a bit of
727 memory in libdbus, but tbh we should never get here anyway. */
728 Py_BEGIN_ALLOW_THREADS
729 ok = dbus_connection_unregister_object_path(self->conn,
730 PyString_AS_STRING(path));
731 Py_END_ALLOW_THREADS
732 return NULL;
734 /* don't DECREF path: libdbus owns a ref now */
735 Py_DECREF(tuple);
736 Py_RETURN_NONE;
738 else {
739 /* Oops, OOM. Tidy up, if we can, ignoring any error. */
740 PyDict_DelItem(self->object_paths, path);
741 PyErr_Clear();
742 Py_DECREF(tuple);
743 Py_DECREF(path);
744 PyErr_NoMemory();
745 return NULL;
749 PyDoc_STRVAR(Connection__unregister_object_path__doc__,
750 "unregister_object_path(path)\n\n"
751 "Remove a previously registered handler for the given object path.\n"
752 "\n"
753 ":Parameters:\n"
754 " `path` : str\n"
755 " The object path whose handler is to be removed\n"
756 ":Raises KeyError: if there is no handler registered for exactly that\n"
757 " object path.\n"
759 static PyObject *
760 Connection__unregister_object_path(Connection *self, PyObject *args,
761 PyObject *kwargs)
763 dbus_bool_t ok;
764 PyObject *path;
765 PyObject *callbacks;
766 static char *argnames[] = {"path", NULL};
768 TRACE(self);
769 DBUS_PY_RAISE_VIA_NULL_IF_FAIL(self->conn);
770 if (!PyArg_ParseTupleAndKeywords(args, kwargs,
771 "O:_unregister_object_path",
772 argnames, &path)) return NULL;
774 /* Take a ref to the path. Same comments as for _register_object_path. */
775 if (PyString_CheckExact(path)) {
776 Py_INCREF(path);
778 else if (PyUnicode_Check(path)) {
779 path = PyUnicode_AsUTF8String(path);
780 if (!path) return NULL;
782 else if (PyString_Check(path)) {
783 path = PyString_FromString(PyString_AS_STRING(path));
784 if (!path) return NULL;
786 else {
787 PyErr_SetString(PyExc_TypeError, "path must be a str or unicode object");
788 return NULL;
791 /* Guard against unregistering a handler that doesn't, in fact, exist,
792 or whose unregistration is already in progress. */
793 callbacks = PyDict_GetItem(self->object_paths, path);
794 if (!callbacks || callbacks == Py_None) {
795 PyErr_Format(PyExc_KeyError, "Can't unregister the object-path "
796 "handler for '%s': there is no such handler",
797 PyString_AS_STRING(path));
798 Py_DECREF(path);
799 return NULL;
802 /* Hang on to a reference to the callbacks for the moment. */
803 Py_INCREF(callbacks);
805 /* Get rid of the object-path while we still have the GIL, to
806 guard against unregistering twice from different threads (which
807 causes undefined behaviour in libdbus).
809 Because deletion would make it possible for the re-insertion below
810 to fail, we instead set the handler to None as a placeholder.
812 if (PyDict_SetItem(self->object_paths, path, Py_None) < 0) {
813 /* If that failed, there's no need to be paranoid as below - the
814 callbacks are still set, so we failed, but at least everything
815 is in sync. */
816 Py_DECREF(callbacks);
817 Py_DECREF(path);
818 return NULL;
821 /* BEGIN PARANOIA
822 This is something of a critical section - the dict of object-paths
823 and libdbus' internal structures are out of sync for a bit. We have
824 to be able to cope with that.
826 It's really annoying that dbus_connection_unregister_object_path
827 can fail, *and* has undefined behaviour if the object path has
828 already been unregistered. Either/or would be fine.
831 Py_BEGIN_ALLOW_THREADS
832 ok = dbus_connection_unregister_object_path(self->conn,
833 PyString_AS_STRING(path));
834 Py_END_ALLOW_THREADS
836 if (ok) {
837 Py_DECREF(callbacks);
838 PyDict_DelItem(self->object_paths, path);
839 /* END PARANOIA on successful code path */
840 /* The above can't fail unless by some strange trickery the key is no
841 longer present. Ignore any errors. */
842 Py_DECREF(path);
843 PyErr_Clear();
844 Py_RETURN_NONE;
846 else {
847 /* Oops, OOM. Put the callbacks back in the dict so
848 * we'll have another go if/when the user frees some memory
849 * and tries calling this method again. */
850 PyDict_SetItem(self->object_paths, path, callbacks);
851 /* END PARANOIA on failing code path */
852 /* If the SetItem failed, there's nothing we can do about it - but
853 since we know it's an existing entry, it shouldn't be able to fail
854 anyway. */
855 Py_DECREF(path);
856 Py_DECREF(callbacks);
857 return PyErr_NoMemory();
861 /* dbus_connection_get_object_path_data - not useful to Python,
862 * the object path data is just a PyString containing the path */
863 /* dbus_connection_list_registered could be useful, though */
865 /* dbus_connection_set_change_sigpipe - sets global state */
867 /* Maxima. Does Python code ever need to manipulate these?
868 * OTOH they're easy to wrap */
869 /* dbus_connection_set_max_message_size */
870 /* dbus_connection_get_max_message_size */
871 /* dbus_connection_set_max_received_size */
872 /* dbus_connection_get_max_received_size */
874 /* dbus_connection_get_outgoing_size - almost certainly unneeded */
876 struct PyMethodDef DBusPyConnection_tp_methods[] = {
877 #define ENTRY(name, flags) {#name, (PyCFunction)Connection_##name, flags, Connection_##name##__doc__}
878 ENTRY(close, METH_NOARGS),
879 ENTRY(flush, METH_NOARGS),
880 ENTRY(get_is_connected, METH_NOARGS),
881 ENTRY(get_is_authenticated, METH_NOARGS),
882 ENTRY(set_exit_on_disconnect, METH_VARARGS),
883 ENTRY(get_unix_fd, METH_NOARGS),
884 ENTRY(get_peer_unix_user, METH_NOARGS),
885 ENTRY(get_peer_unix_process_id, METH_NOARGS),
886 ENTRY(add_message_filter, METH_O),
887 ENTRY(_register_object_path, METH_VARARGS|METH_KEYWORDS),
888 ENTRY(remove_message_filter, METH_O),
889 ENTRY(send_message, METH_VARARGS),
890 ENTRY(send_message_with_reply, METH_VARARGS),
891 ENTRY(send_message_with_reply_and_block, METH_VARARGS),
892 ENTRY(_unregister_object_path, METH_VARARGS|METH_KEYWORDS),
893 {NULL},
894 #undef ENTRY
897 /* vim:set ft=c cino< sw=4 sts=4 et: */