Remove trailing whitespace in C source
[dbus-python-phuang.git] / _dbus_bindings / conn-methods.c
blob23ca1d370540ef8a754e3efde9fac311a2415362
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 library is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU Lesser General Public License as published by
10 * the Free Software Foundation; either version 2.1 of the License, or
11 * (at your option) any later version.
13 * This library is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU Lesser General Public License for more details.
18 * You should have received a copy of the GNU Lesser General Public License
19 * along with this library; if not, write to the Free Software
20 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
24 #include "dbus_bindings-internal.h"
25 #include "conn-internal.h"
27 static void
28 _object_path_unregister(DBusConnection *conn, void *user_data)
30 PyGILState_STATE gil = PyGILState_Ensure();
31 PyObject *tuple = NULL;
32 Connection *conn_obj = NULL;
33 PyObject *callable;
35 conn_obj = (Connection *)DBusPyConnection_ExistingFromDBusConnection(conn);
36 if (!conn_obj) goto out;
37 TRACE(conn_obj);
39 DBG("Connection at %p unregistering object path %s",
40 conn_obj, PyString_AS_STRING((PyObject *)user_data));
41 tuple = DBusPyConnection_GetObjectPathHandlers((PyObject *)conn_obj, (PyObject *)user_data);
42 if (!tuple) goto out;
43 if (tuple == Py_None) goto out;
45 DBG("%s", "... yes we have handlers for that object path");
47 /* 0'th item is the unregisterer (if that's a word) */
48 callable = PyTuple_GetItem(tuple, 0);
49 if (callable && callable != Py_None) {
50 DBG("%s", "... and we even have an unregisterer");
51 /* any return from the unregisterer is ignored */
52 Py_XDECREF(PyObject_CallFunctionObjArgs(callable, conn_obj, NULL));
54 out:
55 Py_XDECREF(conn_obj);
56 Py_XDECREF(tuple);
57 /* the user_data (a Python str) is no longer ref'd by the DBusConnection */
58 Py_XDECREF((PyObject *)user_data);
59 if (PyErr_Occurred()) {
60 PyErr_Print();
62 PyGILState_Release(gil);
65 static DBusHandlerResult
66 _object_path_message(DBusConnection *conn, DBusMessage *message,
67 void *user_data)
69 DBusHandlerResult ret;
70 PyGILState_STATE gil = PyGILState_Ensure();
71 Connection *conn_obj = NULL;
72 PyObject *tuple = NULL;
73 PyObject *msg_obj;
74 PyObject *callable; /* borrowed */
76 dbus_message_ref(message);
77 msg_obj = DBusPyMessage_ConsumeDBusMessage(message);
78 if (!msg_obj) {
79 ret = DBUS_HANDLER_RESULT_NEED_MEMORY;
80 goto out;
83 conn_obj = (Connection *)DBusPyConnection_ExistingFromDBusConnection(conn);
84 if (!conn_obj) {
85 ret = DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
86 goto out;
88 TRACE(conn_obj);
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 Py_ssize_t 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;
159 TRACE(conn_obj);
161 /* The user_data is a pointer to a Python object. To avoid
162 * cross-library reference cycles, the DBusConnection isn't allowed
163 * to reference it. However, as long as the Connection is still
164 * alive, its ->filters list owns a reference to the same Python
165 * object, so the object should also still be alive.
167 * To ensure that this works, be careful whenever manipulating the
168 * filters list! (always put things in the list *before* giving
169 * them to libdbus, etc.)
171 #ifdef DBUS_PYTHON_DISABLE_CHECKS
172 callable = (PyObject *)user_data;
173 #else
174 size = PyList_GET_SIZE(conn_obj->filters);
175 for (i = 0; i < size; i++) {
176 callable = PyList_GET_ITEM(conn_obj->filters, i);
177 if (callable == user_data) {
178 Py_INCREF(callable);
180 else {
181 callable = NULL;
185 if (!callable) {
186 DBG("... filter %p has vanished from ->filters, so not calling it",
187 user_data);
188 ret = DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
189 goto out;
191 #endif
193 ret = DBusPyConnection_HandleMessage(conn_obj, msg_obj, callable);
194 out:
195 Py_XDECREF(msg_obj);
196 Py_XDECREF(conn_obj);
197 Py_XDECREF(callable);
198 PyGILState_Release(gil);
199 return ret;
202 PyDoc_STRVAR(Connection__require_main_loop__doc__,
203 "_require_main_loop()\n\n"
204 "Raise an exception if this Connection is not bound to any main loop -\n"
205 "in this state, asynchronous calls, receiving signals and exporting objects\n"
206 "will not work.\n"
207 "\n"
208 "`dbus.mainloop.NULL_MAIN_LOOP` is treated like a valid main loop - if you're\n"
209 "using that, you presumably know what you're doing.\n");
210 static PyObject *
211 Connection__require_main_loop (Connection *self, PyObject *args UNUSED)
213 if (!self->has_mainloop) {
214 PyErr_SetString(PyExc_RuntimeError,
215 "To make asynchronous calls, receive signals or "
216 "export objects, D-Bus connections must be attached "
217 "to a main loop by passing mainloop=... to the "
218 "constructor or calling "
219 "dbus.set_default_main_loop(...)");
220 return NULL;
222 Py_RETURN_NONE;
225 PyDoc_STRVAR(Connection_close__doc__,
226 "close()\n\n"
227 "Close the connection.");
228 static PyObject *
229 Connection_close (Connection *self, PyObject *args UNUSED)
231 TRACE(self);
232 /* Because the user explicitly asked to close the connection, we'll even
233 let them close shared connections. */
234 if (self->conn) {
235 Py_BEGIN_ALLOW_THREADS
236 dbus_connection_close(self->conn);
237 Py_END_ALLOW_THREADS
239 Py_RETURN_NONE;
242 PyDoc_STRVAR(Connection_get_is_connected__doc__,
243 "get_is_connected() -> bool\n\n"
244 "Return true if this Connection is connected.\n");
245 static PyObject *
246 Connection_get_is_connected (Connection *self, PyObject *args UNUSED)
248 dbus_bool_t ret;
250 TRACE(self);
251 DBUS_PY_RAISE_VIA_NULL_IF_FAIL(self->conn);
252 Py_BEGIN_ALLOW_THREADS
253 ret = dbus_connection_get_is_connected(self->conn);
254 Py_END_ALLOW_THREADS
255 return PyBool_FromLong(ret);
258 PyDoc_STRVAR(Connection_get_is_authenticated__doc__,
259 "get_is_authenticated() -> bool\n\n"
260 "Return true if this Connection was ever authenticated.\n");
261 static PyObject *
262 Connection_get_is_authenticated (Connection *self, PyObject *args UNUSED)
264 dbus_bool_t ret;
266 TRACE(self);
267 DBUS_PY_RAISE_VIA_NULL_IF_FAIL(self->conn);
268 Py_BEGIN_ALLOW_THREADS
269 ret = dbus_connection_get_is_authenticated(self->conn);
270 Py_END_ALLOW_THREADS
271 return PyBool_FromLong(ret);
274 PyDoc_STRVAR(Connection_set_exit_on_disconnect__doc__,
275 "set_exit_on_disconnect(bool)\n\n"
276 "Set whether the C function ``_exit`` will be called when this Connection\n"
277 "becomes disconnected. This will cause the program to exit without calling\n"
278 "any cleanup code or exit handlers.\n"
279 "\n"
280 "The default is for this feature to be disabled for Connections and enabled\n"
281 "for Buses.\n");
282 static PyObject *
283 Connection_set_exit_on_disconnect (Connection *self, PyObject *args)
285 int exit_on_disconnect;
287 TRACE(self);
288 DBUS_PY_RAISE_VIA_NULL_IF_FAIL(self->conn);
289 if (!PyArg_ParseTuple(args, "i:set_exit_on_disconnect",
290 &exit_on_disconnect)) {
291 return NULL;
293 Py_BEGIN_ALLOW_THREADS
294 dbus_connection_set_exit_on_disconnect(self->conn,
295 exit_on_disconnect ? 1 : 0);
296 Py_END_ALLOW_THREADS
297 Py_RETURN_NONE;
300 PyDoc_STRVAR(Connection_send_message__doc__,
301 "send_message(msg) -> long\n\n"
302 "Queue the given message for sending, and return the message serial number.\n"
303 "\n"
304 ":Parameters:\n"
305 " `msg` : dbus.lowlevel.Message\n"
306 " The message to be sent.\n"
308 static PyObject *
309 Connection_send_message(Connection *self, PyObject *args)
311 dbus_bool_t ok;
312 PyObject *obj;
313 DBusMessage *msg;
314 dbus_uint32_t serial;
316 TRACE(self);
317 DBUS_PY_RAISE_VIA_NULL_IF_FAIL(self->conn);
318 if (!PyArg_ParseTuple(args, "O", &obj)) return NULL;
320 msg = DBusPyMessage_BorrowDBusMessage(obj);
321 if (!msg) return NULL;
323 Py_BEGIN_ALLOW_THREADS
324 ok = dbus_connection_send(self->conn, msg, &serial);
325 Py_END_ALLOW_THREADS
327 if (!ok) {
328 return PyErr_NoMemory();
331 return PyLong_FromUnsignedLong(serial);
334 /* The timeout is in seconds here, since that's conventional in Python. */
335 PyDoc_STRVAR(Connection_send_message_with_reply__doc__,
336 "send_message_with_reply(msg, reply_handler, timeout_s=-1, "
337 "require_main_loop=False) -> dbus.lowlevel.PendingCall\n\n"
338 "Queue the message for sending; expect a reply via the returned PendingCall,\n"
339 "which can also be used to cancel the pending call.\n"
340 "\n"
341 ":Parameters:\n"
342 " `msg` : dbus.lowlevel.Message\n"
343 " The message to be sent\n"
344 " `reply_handler` : callable\n"
345 " Asynchronous reply handler: will be called with one positional\n"
346 " parameter, a Message instance representing the reply.\n"
347 " `timeout_s` : float\n"
348 " If the reply takes more than this many seconds, a timeout error\n"
349 " will be created locally and raised instead. If this timeout is\n"
350 " negative (default), a sane default (supplied by libdbus) is used.\n"
351 " `require_main_loop` : bool\n"
352 " If True, raise RuntimeError if this Connection does not have a main\n"
353 " loop configured. If False (default) and there is no main loop, you are\n"
354 " responsible for calling block() on the PendingCall.\n"
355 "\n"
357 static PyObject *
358 Connection_send_message_with_reply(Connection *self, PyObject *args, PyObject *kw)
360 dbus_bool_t ok;
361 double timeout_s = -1.0;
362 int timeout_ms;
363 PyObject *obj, *callable;
364 DBusMessage *msg;
365 DBusPendingCall *pending;
366 int require_main_loop = 0;
367 static char *argnames[] = {"msg", "reply_handler", "timeout_s",
368 "require_main_loop", NULL};
370 TRACE(self);
371 DBUS_PY_RAISE_VIA_NULL_IF_FAIL(self->conn);
372 if (!PyArg_ParseTupleAndKeywords(args, kw,
373 "OO|fi:send_message_with_reply",
374 argnames,
375 &obj, &callable, &timeout_s,
376 &require_main_loop)) {
377 return NULL;
379 if (require_main_loop && !Connection__require_main_loop(self, NULL)) {
380 return NULL;
383 msg = DBusPyMessage_BorrowDBusMessage(obj);
384 if (!msg) return NULL;
386 if (timeout_s < 0) {
387 timeout_ms = -1;
389 else {
390 if (timeout_s > ((double)INT_MAX) / 1000.0) {
391 PyErr_SetString(PyExc_ValueError, "Timeout too long");
392 return NULL;
394 timeout_ms = (int)(timeout_s * 1000.0);
397 Py_BEGIN_ALLOW_THREADS
398 ok = dbus_connection_send_with_reply(self->conn, msg, &pending,
399 timeout_ms);
400 Py_END_ALLOW_THREADS
402 if (!ok) {
403 return PyErr_NoMemory();
406 if (!pending) {
407 /* connection is disconnected (doesn't return FALSE!) */
408 PyErr_SetString (DBusPyException, "Connection is disconnected - "
409 "unable to make method call");
410 return NULL;
413 return DBusPyPendingCall_ConsumeDBusPendingCall(pending, callable);
416 /* Again, the timeout is in seconds, since that's conventional in Python. */
417 PyDoc_STRVAR(Connection_send_message_with_reply_and_block__doc__,
418 "send_message_with_reply_and_block(msg, timeout_s=-1)"
419 " -> dbus.lowlevel.Message\n\n"
420 "Send the message and block while waiting for a reply.\n"
421 "\n"
422 "This does not re-enter the main loop, so it can lead to a deadlock, if\n"
423 "the called method tries to make a synchronous call to a method in this\n"
424 "application. As such, it's probably a bad idea.\n"
425 "\n"
426 ":Parameters:\n"
427 " `msg` : dbus.lowlevel.Message\n"
428 " The message to be sent\n"
429 " `timeout_s` : float\n"
430 " If the reply takes more than this many seconds, a timeout error\n"
431 " will be created locally and raised instead. If this timeout is\n"
432 " negative (default), a sane default (supplied by libdbus) is used.\n"
433 ":Returns:\n"
434 " A `dbus.lowlevel.Message` instance (probably a `dbus.lowlevel.MethodReturnMessage`) on success\n"
435 ":Raises dbus.DBusException:\n"
436 " On error (including if the reply arrives but is an\n"
437 " error message)\n"
438 "\n"
440 static PyObject *
441 Connection_send_message_with_reply_and_block(Connection *self, PyObject *args)
443 double timeout_s = -1.0;
444 int timeout_ms;
445 PyObject *obj;
446 DBusMessage *msg, *reply;
447 DBusError error;
449 TRACE(self);
450 DBUS_PY_RAISE_VIA_NULL_IF_FAIL(self->conn);
451 if (!PyArg_ParseTuple(args, "O|f:send_message_with_reply_and_block", &obj,
452 &timeout_s)) {
453 return NULL;
456 msg = DBusPyMessage_BorrowDBusMessage(obj);
457 if (!msg) return NULL;
459 if (timeout_s < 0) {
460 timeout_ms = -1;
462 else {
463 if (timeout_s > ((double)INT_MAX) / 1000.0) {
464 PyErr_SetString(PyExc_ValueError, "Timeout too long");
465 return NULL;
467 timeout_ms = (int)(timeout_s * 1000.0);
470 dbus_error_init(&error);
471 Py_BEGIN_ALLOW_THREADS
472 reply = dbus_connection_send_with_reply_and_block(self->conn, msg,
473 timeout_ms, &error);
474 Py_END_ALLOW_THREADS
476 if (!reply) {
477 return DBusPyException_ConsumeError(&error);
479 return DBusPyMessage_ConsumeDBusMessage(reply);
482 PyDoc_STRVAR(Connection_flush__doc__,
483 "flush()\n\n"
484 "Block until the outgoing message queue is empty.\n");
485 static PyObject *
486 Connection_flush (Connection *self, PyObject *args UNUSED)
488 TRACE(self);
489 DBUS_PY_RAISE_VIA_NULL_IF_FAIL(self->conn);
490 Py_BEGIN_ALLOW_THREADS
491 dbus_connection_flush (self->conn);
492 Py_END_ALLOW_THREADS
493 Py_RETURN_NONE;
496 /* Unsupported:
497 * dbus_connection_preallocate_send
498 * dbus_connection_free_preallocated_send
499 * dbus_connection_send_preallocated
500 * dbus_connection_borrow_message
501 * dbus_connection_return_message
502 * dbus_connection_steal_borrowed_message
503 * dbus_connection_pop_message
506 /* Non-main-loop handling not yet implemented: */
507 /* dbus_connection_read_write_dispatch */
508 /* dbus_connection_read_write */
510 /* Main loop handling not yet implemented: */
511 /* dbus_connection_get_dispatch_status */
512 /* dbus_connection_dispatch */
513 /* dbus_connection_set_watch_functions */
514 /* dbus_connection_set_timeout_functions */
515 /* dbus_connection_set_wakeup_main_function */
516 /* dbus_connection_set_dispatch_status_function */
518 /* Normally in Python this would be called fileno(), but I don't want to
519 * encourage people to select() on it */
520 PyDoc_STRVAR(Connection_get_unix_fd__doc__,
521 "get_unix_fd() -> int or None\n\n"
522 "Get the connection's UNIX file descriptor, if any.\n\n"
523 "This can be used for SELinux access control checks with ``getpeercon()``\n"
524 "for example. **Do not** read or write to the file descriptor, or try to\n"
525 "``select()`` on it.\n");
526 static PyObject *
527 Connection_get_unix_fd (Connection *self, PyObject *unused UNUSED)
529 int fd;
530 dbus_bool_t ok;
532 TRACE(self);
533 DBUS_PY_RAISE_VIA_NULL_IF_FAIL(self->conn);
534 Py_BEGIN_ALLOW_THREADS
535 ok = dbus_connection_get_unix_fd (self->conn, &fd);
536 Py_END_ALLOW_THREADS
537 if (!ok) Py_RETURN_NONE;
538 return PyInt_FromLong(fd);
541 PyDoc_STRVAR(Connection_get_peer_unix_user__doc__,
542 "get_peer_unix_user() -> long or None\n\n"
543 "Get the UNIX user ID at the other end of the connection, if it has been\n"
544 "authenticated. Return None if this is a non-UNIX platform or the\n"
545 "connection has not been authenticated.\n");
546 static PyObject *
547 Connection_get_peer_unix_user (Connection *self, PyObject *unused UNUSED)
549 unsigned long uid;
550 dbus_bool_t ok;
552 TRACE(self);
553 DBUS_PY_RAISE_VIA_NULL_IF_FAIL(self->conn);
554 Py_BEGIN_ALLOW_THREADS
555 ok = dbus_connection_get_unix_user (self->conn, &uid);
556 Py_END_ALLOW_THREADS
557 if (!ok) Py_RETURN_NONE;
558 return PyLong_FromUnsignedLong (uid);
561 PyDoc_STRVAR(Connection_get_peer_unix_process_id__doc__,
562 "get_peer_unix_process_id() -> long or None\n\n"
563 "Get the UNIX process ID at the other end of the connection, if it has been\n"
564 "authenticated. Return None if this is a non-UNIX platform or the\n"
565 "connection has not been authenticated.\n");
566 static PyObject *
567 Connection_get_peer_unix_process_id (Connection *self, PyObject *unused UNUSED)
569 unsigned long pid;
570 dbus_bool_t ok;
572 TRACE(self);
573 DBUS_PY_RAISE_VIA_NULL_IF_FAIL(self->conn);
574 Py_BEGIN_ALLOW_THREADS
575 ok = dbus_connection_get_unix_process_id (self->conn, &pid);
576 Py_END_ALLOW_THREADS
577 if (!ok) Py_RETURN_NONE;
578 return PyLong_FromUnsignedLong (pid);
581 /* TODO: wrap dbus_connection_set_unix_user_function Pythonically */
583 PyDoc_STRVAR(Connection_add_message_filter__doc__,
584 "add_message_filter(callable)\n\n"
585 "Add the given message filter to the internal list.\n\n"
586 "Filters are handlers that are run on all incoming messages, prior to the\n"
587 "objects registered to handle object paths.\n"
588 "\n"
589 "Filters are run in the order that they were added. The same handler can\n"
590 "be added as a filter more than once, in which case it will be run more\n"
591 "than once. Filters added during a filter callback won't be run on the\n"
592 "message being processed.\n"
594 static PyObject *
595 Connection_add_message_filter(Connection *self, PyObject *callable)
597 dbus_bool_t ok;
599 TRACE(self);
600 DBUS_PY_RAISE_VIA_NULL_IF_FAIL(self->conn);
601 /* The callable must be referenced by ->filters *before* it is
602 * given to libdbus, which does not own a reference to it.
604 if (PyList_Append(self->filters, callable) < 0) {
605 return NULL;
608 Py_BEGIN_ALLOW_THREADS
609 ok = dbus_connection_add_filter(self->conn, _filter_message, callable,
610 NULL);
611 Py_END_ALLOW_THREADS
613 if (!ok) {
614 Py_XDECREF(PyObject_CallMethod(self->filters, "remove", "(O)",
615 callable));
616 PyErr_NoMemory();
617 return NULL;
619 Py_RETURN_NONE;
622 PyDoc_STRVAR(Connection_remove_message_filter__doc__,
623 "remove_message_filter(callable)\n\n"
624 "Remove the given message filter (see `add_message_filter` for details).\n"
625 "\n"
626 ":Raises LookupError:\n"
627 " The given callable is not among the registered filters\n");
628 static PyObject *
629 Connection_remove_message_filter(Connection *self, PyObject *callable)
631 PyObject *obj;
633 TRACE(self);
634 DBUS_PY_RAISE_VIA_NULL_IF_FAIL(self->conn);
635 /* It's safe to do this before removing it from libdbus, because
636 * the presence of callable in our arguments means we have a ref
637 * to it. */
638 obj = PyObject_CallMethod(self->filters, "remove", "(O)", callable);
639 if (!obj) return NULL;
640 Py_DECREF(obj);
642 Py_BEGIN_ALLOW_THREADS
643 dbus_connection_remove_filter(self->conn, _filter_message, callable);
644 Py_END_ALLOW_THREADS
646 Py_RETURN_NONE;
649 PyDoc_STRVAR(Connection__register_object_path__doc__,
650 "register_object_path(path, on_message, on_unregister=None, fallback=False)\n"
651 "\n"
652 "Register a callback to be called when messages arrive at the given\n"
653 "object-path. Used to export objects' methods on the bus in a low-level\n"
654 "way. For the high-level interface to this functionality (usually\n"
655 "recommended) see the `dbus.service.Object` base class.\n"
656 "\n"
657 ":Parameters:\n"
658 " `path` : str\n"
659 " Object path to be acted on\n"
660 " `on_message` : callable\n"
661 " Called when a message arrives at the given object-path, with\n"
662 " two positional parameters: the first is this Connection,\n"
663 " the second is the incoming `dbus.lowlevel.Message`.\n"
664 " `on_unregister` : callable or None\n"
665 " If not None, called when the callback is unregistered.\n"
666 " `fallback` : bool\n"
667 " If True (the default is False), when a message arrives for a\n"
668 " 'subdirectory' of the given path and there is no more specific\n"
669 " handler, use this handler. Normally this handler is only run if\n"
670 " the paths match exactly.\n"
672 static PyObject *
673 Connection__register_object_path(Connection *self, PyObject *args,
674 PyObject *kwargs)
676 dbus_bool_t ok;
677 int fallback = 0;
678 PyObject *callbacks, *path, *tuple, *on_message, *on_unregister = Py_None;
679 static char *argnames[] = {"path", "on_message", "on_unregister",
680 "fallback", NULL};
682 TRACE(self);
683 DBUS_PY_RAISE_VIA_NULL_IF_FAIL(self->conn);
684 if (!Connection__require_main_loop(self, NULL)) {
685 return NULL;
687 if (!PyArg_ParseTupleAndKeywords(args, kwargs,
688 "OO|Oi:_register_object_path",
689 argnames,
690 &path,
691 &on_message, &on_unregister,
692 &fallback)) return NULL;
694 /* Take a reference to path, which we give away to libdbus in a moment.
696 Also, path needs to be a string (not a subclass which could do something
697 mad) to preserve the desirable property that the DBusConnection can
698 never strongly reference the Connection, even indirectly.
700 if (PyString_CheckExact(path)) {
701 Py_INCREF(path);
703 else if (PyUnicode_Check(path)) {
704 path = PyUnicode_AsUTF8String(path);
705 if (!path) return NULL;
707 else if (PyString_Check(path)) {
708 path = PyString_FromString(PyString_AS_STRING(path));
709 if (!path) return NULL;
711 else {
712 PyErr_SetString(PyExc_TypeError, "path must be a str or unicode object");
713 return NULL;
716 if (!dbus_py_validate_object_path(PyString_AS_STRING(path))) {
717 Py_DECREF(path);
718 return NULL;
721 tuple = Py_BuildValue("(OO)", on_unregister, on_message);
722 if (!tuple) {
723 Py_DECREF(path);
724 return NULL;
727 /* Guard against registering a handler that already exists. */
728 callbacks = PyDict_GetItem(self->object_paths, path);
729 if (callbacks && callbacks != Py_None) {
730 PyErr_Format(PyExc_KeyError, "Can't register the object-path "
731 "handler for '%s': there is already a handler",
732 PyString_AS_STRING(path));
733 Py_DECREF(tuple);
734 Py_DECREF(path);
735 return NULL;
738 /* Pre-allocate a slot in the dictionary, so we know we'll be able
739 * to replace it with the callbacks without OOM.
740 * This ensures we can keep libdbus' opinion of whether those
741 * paths are handled in sync with our own. */
742 if (PyDict_SetItem(self->object_paths, path, Py_None) < 0) {
743 Py_DECREF(tuple);
744 Py_DECREF(path);
745 return NULL;
748 Py_BEGIN_ALLOW_THREADS
749 if (fallback) {
750 ok = dbus_connection_register_fallback(self->conn,
751 PyString_AS_STRING(path),
752 &_object_path_vtable,
753 path);
755 else {
756 ok = dbus_connection_register_object_path(self->conn,
757 PyString_AS_STRING(path),
758 &_object_path_vtable,
759 path);
761 Py_END_ALLOW_THREADS
763 if (ok) {
764 if (PyDict_SetItem(self->object_paths, path, tuple) < 0) {
765 /* That shouldn't have happened, we already allocated enough
766 memory for it. Oh well, try to undo the registration to keep
767 things in sync. If this fails too, we've leaked a bit of
768 memory in libdbus, but tbh we should never get here anyway. */
769 Py_BEGIN_ALLOW_THREADS
770 ok = dbus_connection_unregister_object_path(self->conn,
771 PyString_AS_STRING(path));
772 Py_END_ALLOW_THREADS
773 return NULL;
775 /* don't DECREF path: libdbus owns a ref now */
776 Py_DECREF(tuple);
777 Py_RETURN_NONE;
779 else {
780 /* Oops, OOM. Tidy up, if we can, ignoring any error. */
781 PyDict_DelItem(self->object_paths, path);
782 PyErr_Clear();
783 Py_DECREF(tuple);
784 Py_DECREF(path);
785 PyErr_NoMemory();
786 return NULL;
790 PyDoc_STRVAR(Connection__unregister_object_path__doc__,
791 "unregister_object_path(path)\n\n"
792 "Remove a previously registered handler for the given object path.\n"
793 "\n"
794 ":Parameters:\n"
795 " `path` : str\n"
796 " The object path whose handler is to be removed\n"
797 ":Raises KeyError: if there is no handler registered for exactly that\n"
798 " object path.\n"
800 static PyObject *
801 Connection__unregister_object_path(Connection *self, PyObject *args,
802 PyObject *kwargs)
804 dbus_bool_t ok;
805 PyObject *path;
806 PyObject *callbacks;
807 static char *argnames[] = {"path", NULL};
809 TRACE(self);
810 DBUS_PY_RAISE_VIA_NULL_IF_FAIL(self->conn);
811 if (!PyArg_ParseTupleAndKeywords(args, kwargs,
812 "O:_unregister_object_path",
813 argnames, &path)) return NULL;
815 /* Take a ref to the path. Same comments as for _register_object_path. */
816 if (PyString_CheckExact(path)) {
817 Py_INCREF(path);
819 else if (PyUnicode_Check(path)) {
820 path = PyUnicode_AsUTF8String(path);
821 if (!path) return NULL;
823 else if (PyString_Check(path)) {
824 path = PyString_FromString(PyString_AS_STRING(path));
825 if (!path) return NULL;
827 else {
828 PyErr_SetString(PyExc_TypeError, "path must be a str or unicode object");
829 return NULL;
832 /* Guard against unregistering a handler that doesn't, in fact, exist,
833 or whose unregistration is already in progress. */
834 callbacks = PyDict_GetItem(self->object_paths, path);
835 if (!callbacks || callbacks == Py_None) {
836 PyErr_Format(PyExc_KeyError, "Can't unregister the object-path "
837 "handler for '%s': there is no such handler",
838 PyString_AS_STRING(path));
839 Py_DECREF(path);
840 return NULL;
843 /* Hang on to a reference to the callbacks for the moment. */
844 Py_INCREF(callbacks);
846 /* Get rid of the object-path while we still have the GIL, to
847 guard against unregistering twice from different threads (which
848 causes undefined behaviour in libdbus).
850 Because deletion would make it possible for the re-insertion below
851 to fail, we instead set the handler to None as a placeholder.
853 if (PyDict_SetItem(self->object_paths, path, Py_None) < 0) {
854 /* If that failed, there's no need to be paranoid as below - the
855 callbacks are still set, so we failed, but at least everything
856 is in sync. */
857 Py_DECREF(callbacks);
858 Py_DECREF(path);
859 return NULL;
862 /* BEGIN PARANOIA
863 This is something of a critical section - the dict of object-paths
864 and libdbus' internal structures are out of sync for a bit. We have
865 to be able to cope with that.
867 It's really annoying that dbus_connection_unregister_object_path
868 can fail, *and* has undefined behaviour if the object path has
869 already been unregistered. Either/or would be fine.
872 Py_BEGIN_ALLOW_THREADS
873 ok = dbus_connection_unregister_object_path(self->conn,
874 PyString_AS_STRING(path));
875 Py_END_ALLOW_THREADS
877 if (ok) {
878 Py_DECREF(callbacks);
879 PyDict_DelItem(self->object_paths, path);
880 /* END PARANOIA on successful code path */
881 /* The above can't fail unless by some strange trickery the key is no
882 longer present. Ignore any errors. */
883 Py_DECREF(path);
884 PyErr_Clear();
885 Py_RETURN_NONE;
887 else {
888 /* Oops, OOM. Put the callbacks back in the dict so
889 * we'll have another go if/when the user frees some memory
890 * and tries calling this method again. */
891 PyDict_SetItem(self->object_paths, path, callbacks);
892 /* END PARANOIA on failing code path */
893 /* If the SetItem failed, there's nothing we can do about it - but
894 since we know it's an existing entry, it shouldn't be able to fail
895 anyway. */
896 Py_DECREF(path);
897 Py_DECREF(callbacks);
898 return PyErr_NoMemory();
902 /* dbus_connection_get_object_path_data - not useful to Python,
903 * the object path data is just a PyString containing the path */
904 /* dbus_connection_list_registered could be useful, though */
906 /* dbus_connection_set_change_sigpipe - sets global state */
908 /* Maxima. Does Python code ever need to manipulate these?
909 * OTOH they're easy to wrap */
910 /* dbus_connection_set_max_message_size */
911 /* dbus_connection_get_max_message_size */
912 /* dbus_connection_set_max_received_size */
913 /* dbus_connection_get_max_received_size */
915 /* dbus_connection_get_outgoing_size - almost certainly unneeded */
917 struct PyMethodDef DBusPyConnection_tp_methods[] = {
918 #define ENTRY(name, flags) {#name, (PyCFunction)Connection_##name, flags, Connection_##name##__doc__}
919 ENTRY(_require_main_loop, METH_NOARGS),
920 ENTRY(close, METH_NOARGS),
921 ENTRY(flush, METH_NOARGS),
922 ENTRY(get_is_connected, METH_NOARGS),
923 ENTRY(get_is_authenticated, METH_NOARGS),
924 ENTRY(set_exit_on_disconnect, METH_VARARGS),
925 ENTRY(get_unix_fd, METH_NOARGS),
926 ENTRY(get_peer_unix_user, METH_NOARGS),
927 ENTRY(get_peer_unix_process_id, METH_NOARGS),
928 ENTRY(add_message_filter, METH_O),
929 ENTRY(_register_object_path, METH_VARARGS|METH_KEYWORDS),
930 ENTRY(remove_message_filter, METH_O),
931 ENTRY(send_message, METH_VARARGS),
932 ENTRY(send_message_with_reply, METH_VARARGS|METH_KEYWORDS),
933 ENTRY(send_message_with_reply_and_block, METH_VARARGS),
934 ENTRY(_unregister_object_path, METH_VARARGS|METH_KEYWORDS),
935 {NULL},
936 #undef ENTRY
939 /* vim:set ft=c cino< sw=4 sts=4 et: */