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 PyDoc_STRVAR(Connection_close__doc__
,
28 "Close the connection.");
30 Connection_close (Connection
*self
, PyObject
*args
)
32 if (!PyArg_ParseTuple(args
, ":close")) return NULL
;
33 /* Because the user explicitly asked to close the connection, we'll even
34 let them close shared connections. */
36 Py_BEGIN_ALLOW_THREADS
37 dbus_connection_close (self
->conn
);
43 PyDoc_STRVAR(Connection_get_is_connected__doc__
,
44 "get_is_connected() -> bool\n\n"
45 "Return true if this Connection is connected.\n");
47 Connection_get_is_connected (Connection
*self
, PyObject
*args
)
50 if (!PyArg_ParseTuple(args
, ":get_is_connected")) return NULL
;
51 Py_BEGIN_ALLOW_THREADS
52 ret
= dbus_connection_get_is_connected (self
->conn
);
54 return PyBool_FromLong (ret
);
57 PyDoc_STRVAR(Connection_get_is_authenticated__doc__
,
58 "get_is_authenticated() -> bool\n\n"
59 "Return true if this Connection was ever authenticated.\n");
61 Connection_get_is_authenticated (Connection
*self
, PyObject
*args
)
64 if (!PyArg_ParseTuple(args
, ":get_is_authenticated")) return NULL
;
65 Py_BEGIN_ALLOW_THREADS
66 ret
= dbus_connection_get_is_authenticated (self
->conn
);
68 return PyBool_FromLong (ret
);
71 PyDoc_STRVAR(Connection_set_exit_on_disconnect__doc__
,
72 "set_exit_on_disconnect(bool)\n\n"
73 "Set whether the C function ``_exit`` will be called when this Connection\n"
74 "becomes disconnected. This will cause the program to exit without calling\n"
75 "any cleanup code or exit handlers.\n"
77 "The default is for this feature to be disabled for Connections and enabled\n"
80 Connection_set_exit_on_disconnect (Connection
*self
, PyObject
*args
)
82 int exit_on_disconnect
;
83 if (!PyArg_ParseTuple(args
, "i:set_exit_on_disconnect",
84 &exit_on_disconnect
)) {
87 Py_BEGIN_ALLOW_THREADS
88 dbus_connection_set_exit_on_disconnect (self
->conn
,
89 exit_on_disconnect
? 1 : 0);
94 PyDoc_STRVAR(Connection_send_message__doc__
,
95 "send_message(msg) -> long\n\n"
96 "Queue the given message for sending, and return the message serial number.\n"
99 " `msg` : dbus.lowlevel.Message\n"
100 " The message to be sent.\n"
103 Connection_send_message(Connection
*self
, PyObject
*args
)
108 dbus_uint32_t serial
;
110 if (!PyArg_ParseTuple(args
, "O", &obj
)) return NULL
;
112 msg
= Message_BorrowDBusMessage(obj
);
113 if (!msg
) return NULL
;
115 Py_BEGIN_ALLOW_THREADS
116 ok
= dbus_connection_send(self
->conn
, msg
, &serial
);
120 return PyErr_NoMemory();
123 return PyLong_FromUnsignedLong(serial
);
126 /* The timeout is in seconds here, since that's conventional in Python. */
127 PyDoc_STRVAR(Connection_send_message_with_reply__doc__
,
128 "send_message_with_reply(msg: Message, reply_handler: callable[, timeout_s: float])"
129 " -> dbus.lowlevel.PendingCall\n\n"
130 "Queue the message for sending; expect a reply via the returned PendingCall.\n"
133 " `msg` : dbus.lowlevel.Message\n"
134 " The message to be sent\n"
135 " `reply_handler` : callable\n"
136 " Asynchronous reply handler: will be called with one positional\n"
137 " parameter, a Message instance representing the reply.\n"
138 " `timeout_s` : float\n"
139 " If the reply takes more than this many seconds, a timeout error\n"
140 " will be created locally and raised instead. If this timeout is\n"
141 " negative (default), a sane default (supplied by libdbus) is used.\n"
143 " A `dbus.lowlevel.PendingCall` instance which can be used to cancel the pending call.\n"
147 Connection_send_message_with_reply(Connection
*self
, PyObject
*args
)
150 double timeout_s
= -1.0;
152 PyObject
*obj
, *callable
;
154 DBusPendingCall
*pending
;
156 if (!PyArg_ParseTuple(args
, "OO|f:send_message_with_reply", &obj
, &callable
,
161 msg
= Message_BorrowDBusMessage(obj
);
162 if (!msg
) return NULL
;
168 if (timeout_s
> ((double)INT_MAX
) / 1000.0) {
169 PyErr_SetString(PyExc_ValueError
, "Timeout too long");
172 timeout_ms
= (int)(timeout_s
* 1000.0);
175 Py_BEGIN_ALLOW_THREADS
176 ok
= dbus_connection_send_with_reply(self
->conn
, msg
, &pending
,
181 return PyErr_NoMemory();
184 return PendingCall_ConsumeDBusPendingCall(pending
, callable
);
187 /* Again, the timeout is in seconds, since that's conventional in Python. */
188 PyDoc_STRVAR(Connection_send_message_with_reply_and_block__doc__
,
189 "send_message_with_reply_and_block(msg: dbus.lowlevel.Message, [, timeout_s: float])"
190 " -> dbus.lowlevel.Message\n\n"
191 "Send the message and block while waiting for a reply.\n"
193 "This does not re-enter the main loop, so it can lead to a deadlock, if\n"
194 "the called method tries to make a synchronous call to a method in this\n"
195 "application. As such, it's probably a bad idea.\n"
198 " `msg` : dbus.lowlevel.Message\n"
199 " The message to be sent\n"
200 " `timeout_s` : float\n"
201 " If the reply takes more than this many seconds, a timeout error\n"
202 " will be created locally and raised instead. If this timeout is\n"
203 " negative (default), a sane default (supplied by libdbus) is used.\n"
205 " A `dbus.lowlevel.Message` instance (probably a `dbus.lowlevel.MethodReturnMessage`) on success\n"
206 ":Raises dbus.DBusException:\n"
207 " On error (including if the reply arrives but is an\n"
212 Connection_send_message_with_reply_and_block(Connection
*self
, PyObject
*args
)
214 double timeout_s
= -1.0;
217 DBusMessage
*msg
, *reply
;
220 if (!PyArg_ParseTuple(args
, "O|f:send_message_with_reply_and_block", &obj
,
225 msg
= Message_BorrowDBusMessage(obj
);
226 if (!msg
) return NULL
;
232 if (timeout_s
> ((double)INT_MAX
) / 1000.0) {
233 PyErr_SetString(PyExc_ValueError
, "Timeout too long");
236 timeout_ms
= (int)(timeout_s
* 1000.0);
239 dbus_error_init(&error
);
240 Py_BEGIN_ALLOW_THREADS
241 reply
= dbus_connection_send_with_reply_and_block(self
->conn
, msg
,
246 return DBusException_ConsumeError(&error
);
248 return Message_ConsumeDBusMessage(reply
);
251 PyDoc_STRVAR(Connection_flush__doc__
,
253 "Block until the outgoing message queue is empty.\n");
255 Connection_flush (Connection
*self
, PyObject
*args UNUSED
)
257 Py_BEGIN_ALLOW_THREADS
258 dbus_connection_flush (self
->conn
);
264 * dbus_connection_preallocate_send
265 * dbus_connection_free_preallocated_send
266 * dbus_connection_send_preallocated
267 * dbus_connection_borrow_message
268 * dbus_connection_return_message
269 * dbus_connection_steal_borrowed_message
270 * dbus_connection_pop_message
273 /* Non-main-loop handling not yet implemented: */
274 /* dbus_connection_read_write_dispatch */
275 /* dbus_connection_read_write */
277 /* Main loop handling not yet implemented: */
278 /* dbus_connection_get_dispatch_status */
279 /* dbus_connection_dispatch */
280 /* dbus_connection_set_watch_functions */
281 /* dbus_connection_set_timeout_functions */
282 /* dbus_connection_set_wakeup_main_function */
283 /* dbus_connection_set_dispatch_status_function */
285 /* Normally in Python this would be called fileno(), but I don't want to
286 * encourage people to select() on it */
287 PyDoc_STRVAR(Connection_get_unix_fd__doc__
,
288 "get_unix_fd() -> int or None\n\n"
289 "Get the connection's UNIX file descriptor, if any.\n\n"
290 "This can be used for SELinux access control checks with ``getpeercon()``\n"
291 "for example. **Do not** read or write to the file descriptor, or try to\n"
292 "``select()`` on it.\n");
294 Connection_get_unix_fd (Connection
*self
, PyObject
*unused UNUSED
)
299 Py_BEGIN_ALLOW_THREADS
300 ok
= dbus_connection_get_unix_fd (self
->conn
, &fd
);
302 if (!ok
) Py_RETURN_NONE
;
303 return PyInt_FromLong(fd
);
306 PyDoc_STRVAR(Connection_get_peer_unix_user__doc__
,
307 "get_peer_unix_user() -> long or None\n\n"
308 "Get the UNIX user ID at the other end of the connection, if it has been\n"
309 "authenticated. Return None if this is a non-UNIX platform or the\n"
310 "connection has not been authenticated.\n");
312 Connection_get_peer_unix_user (Connection
*self
, PyObject
*unused UNUSED
)
317 Py_BEGIN_ALLOW_THREADS
318 ok
= dbus_connection_get_unix_user (self
->conn
, &uid
);
320 if (!ok
) Py_RETURN_NONE
;
321 return PyLong_FromUnsignedLong (uid
);
324 PyDoc_STRVAR(Connection_get_peer_unix_process_id__doc__
,
325 "get_peer_unix_process_id() -> long or None\n\n"
326 "Get the UNIX process ID at the other end of the connection, if it has been\n"
327 "authenticated. Return None if this is a non-UNIX platform or the\n"
328 "connection has not been authenticated.\n");
330 Connection_get_peer_unix_process_id (Connection
*self
, PyObject
*unused UNUSED
)
335 Py_BEGIN_ALLOW_THREADS
336 ok
= dbus_connection_get_unix_process_id (self
->conn
, &pid
);
338 if (!ok
) Py_RETURN_NONE
;
339 return PyLong_FromUnsignedLong (pid
);
342 /* TODO: wrap dbus_connection_set_unix_user_function Pythonically */
344 PyDoc_STRVAR(Connection_add_message_filter__doc__
,
345 "add_message_filter(callable)\n\n"
346 "Add the given message filter to the internal list.\n\n"
347 "Filters are handlers that are run on all incoming messages, prior to the\n"
348 "objects registered to handle object paths.\n"
350 "Filters are run in the order that they were added. The same handler can\n"
351 "be added as a filter more than once, in which case it will be run more\n"
352 "than once. Filters added during a filter callback won't be run on the\n"
353 "message being processed.\n"
356 Connection_add_message_filter(Connection
*self
, PyObject
*callable
)
360 /* The callable must be referenced by ->filters *before* it is
361 * given to libdbus, which does not own a reference to it.
363 if (PyList_Append(self
->filters
, callable
) < 0) {
367 Py_BEGIN_ALLOW_THREADS
368 ok
= dbus_connection_add_filter(self
->conn
, _filter_message
, callable
,
373 Py_XDECREF(PyObject_CallMethod(self
->filters
, "remove", "(O)",
381 PyDoc_STRVAR(Connection_remove_message_filter__doc__
,
382 "remove_message_filter(callable)\n\n"
383 "Remove the given message filter (see `add_message_filter` for details).\n"
385 ":Raises LookupError:\n"
386 " The given callable is not among the registered filters\n");
388 Connection_remove_message_filter(Connection
*self
, PyObject
*callable
)
392 /* It's safe to do this before removing it from libdbus, because
393 * the presence of callable in our arguments means we have a ref
395 obj
= PyObject_CallMethod(self
->filters
, "remove", "(O)", callable
);
396 if (!obj
) return NULL
;
399 Py_BEGIN_ALLOW_THREADS
400 dbus_connection_remove_filter(self
->conn
, _filter_message
, callable
);
406 PyDoc_STRVAR(Connection__register_object_path__doc__
,
407 "register_object_path(path: str, on_message: callable[, on_unregister: "
408 "callable[, fallback: bool]])\n"
410 "Register a callback to be called when messages arrive at the given\n"
411 "object-path. Used to export objects' methods on the bus in a low-level\n"
412 "way. For the high-level interface to this functionality (usually\n"
413 "recommended) see the `dbus.service.Object` base class.\n"
417 " Object path to be acted on\n"
418 " `on_message` : callable\n"
419 " Called when a message arrives at the given object-path, with\n"
420 " two positional parameters: the first is this Connection,\n"
421 " the second is the incoming `dbus.lowlevel.Message`.\n"
422 " `fallback` : bool\n"
423 " If True (the default is False), when a message arrives for a\n"
424 " 'subdirectory' of the given path and there is no more specific\n"
425 " handler, use this handler. Normally this handler is only run if\n"
426 " the paths match exactly.\n"
429 Connection__register_object_path(Connection
*self
, PyObject
*args
,
434 PyObject
*callbacks
, *path
, *tuple
, *on_message
, *on_unregister
= Py_None
;
435 static char *argnames
[] = {"path", "on_message", "on_unregister",
438 if (!PyArg_ParseTupleAndKeywords(args
, kwargs
,
439 "OO|Oi:_register_object_path",
442 &on_message
, &on_unregister
,
443 &fallback
)) return NULL
;
445 /* Take a reference to path, which we give away to libdbus in a moment.
447 Also, path needs to be a string (not a subclass which could do something
448 mad) to preserve the desirable property that the DBusConnection can
449 never strongly reference the Connection, even indirectly.
451 if (PyString_CheckExact(path
)) {
454 else if (PyUnicode_Check(path
)) {
455 path
= PyUnicode_AsUTF8String(path
);
456 if (!path
) return NULL
;
458 else if (PyString_Check(path
)) {
459 path
= PyString_FromString(PyString_AS_STRING(path
));
460 if (!path
) return NULL
;
463 PyErr_SetString(PyExc_TypeError
, "path must be a str or unicode object");
467 if (!_validate_object_path(PyString_AS_STRING(path
))) {
472 tuple
= Py_BuildValue("(OO)", on_unregister
, on_message
);
478 /* Guard against registering a handler that already exists. */
479 callbacks
= PyDict_GetItem(self
->object_paths
, path
);
480 if (callbacks
&& callbacks
!= Py_None
) {
481 PyErr_Format(PyExc_KeyError
, "Can't register the object-path "
482 "handler for '%s': there is already a handler",
483 PyString_AS_STRING(path
));
489 /* Pre-allocate a slot in the dictionary, so we know we'll be able
490 * to replace it with the callbacks without OOM.
491 * This ensures we can keep libdbus' opinion of whether those
492 * paths are handled in sync with our own. */
493 if (PyDict_SetItem(self
->object_paths
, path
, Py_None
) < 0) {
499 Py_BEGIN_ALLOW_THREADS
501 ok
= dbus_connection_register_fallback(self
->conn
,
502 PyString_AS_STRING(path
),
503 &_object_path_vtable
,
507 ok
= dbus_connection_register_object_path(self
->conn
,
508 PyString_AS_STRING(path
),
509 &_object_path_vtable
,
515 if (PyDict_SetItem(self
->object_paths
, path
, tuple
) < 0) {
516 /* That shouldn't have happened, we already allocated enough
517 memory for it. Oh well, try to undo the registration to keep
518 things in sync. If this fails too, we've leaked a bit of
519 memory in libdbus, but tbh we should never get here anyway. */
520 Py_BEGIN_ALLOW_THREADS
521 ok
= dbus_connection_unregister_object_path(self
->conn
,
522 PyString_AS_STRING(path
));
526 /* don't DECREF path: libdbus owns a ref now */
531 /* Oops, OOM. Tidy up, if we can, ignoring any error. */
532 PyDict_DelItem(self
->object_paths
, path
);
541 PyDoc_STRVAR(Connection__unregister_object_path__doc__
,
542 "unregister_object_path(path: str)\n\n"
543 "Remove a previously registered handler for the given object path.\n"
547 " The object path whose handler is to be removed\n"
548 ":Raises KeyError: if there is no handler registered for exactly that\n"
552 Connection__unregister_object_path(Connection
*self
, PyObject
*args
,
558 static char *argnames
[] = {"path", NULL
};
560 if (!PyArg_ParseTupleAndKeywords(args
, kwargs
,
561 "O:_unregister_object_path",
562 argnames
, &path
)) return NULL
;
564 /* Take a ref to the path. Same comments as for _register_object_path. */
565 if (PyString_CheckExact(path
)) {
568 else if (PyUnicode_Check(path
)) {
569 path
= PyUnicode_AsUTF8String(path
);
570 if (!path
) return NULL
;
572 else if (PyString_Check(path
)) {
573 path
= PyString_FromString(PyString_AS_STRING(path
));
574 if (!path
) return NULL
;
577 PyErr_SetString(PyExc_TypeError
, "path must be a str or unicode object");
581 /* Guard against unregistering a handler that doesn't, in fact, exist,
582 or whose unregistration is already in progress. */
583 callbacks
= PyDict_GetItem(self
->object_paths
, path
);
584 if (!callbacks
|| callbacks
== Py_None
) {
585 PyErr_Format(PyExc_KeyError
, "Can't unregister the object-path "
586 "handler for '%s': there is no such handler",
587 PyString_AS_STRING(path
));
592 /* Hang on to a reference to the callbacks for the moment. */
593 Py_INCREF(callbacks
);
595 /* Get rid of the object-path while we still have the GIL, to
596 guard against unregistering twice from different threads (which
597 causes undefined behaviour in libdbus).
599 Because deletion would make it possible for the re-insertion below
600 to fail, we instead set the handler to None as a placeholder.
602 if (PyDict_SetItem(self
->object_paths
, path
, Py_None
) < 0) {
603 /* If that failed, there's no need to be paranoid as below - the
604 callbacks are still set, so we failed, but at least everything
606 Py_DECREF(callbacks
);
612 This is something of a critical section - the dict of object-paths
613 and libdbus' internal structures are out of sync for a bit. We have
614 to be able to cope with that.
616 It's really annoying that dbus_connection_unregister_object_path
617 can fail, *and* has undefined behaviour if the object path has
618 already been unregistered. Either/or would be fine.
621 Py_BEGIN_ALLOW_THREADS
622 ok
= dbus_connection_unregister_object_path(self
->conn
,
623 PyString_AS_STRING(path
));
627 Py_DECREF(callbacks
);
628 PyDict_DelItem(self
->object_paths
, path
);
629 /* END PARANOIA on successful code path */
630 /* The above can't fail unless by some strange trickery the key is no
631 longer present. Ignore any errors. */
637 /* Oops, OOM. Put the callbacks back in the dict so
638 * we'll have another go if/when the user frees some memory
639 * and tries calling this method again. */
640 PyDict_SetItem(self
->object_paths
, path
, callbacks
);
641 /* END PARANOIA on failing code path */
642 /* If the SetItem failed, there's nothing we can do about it - but
643 since we know it's an existing entry, it shouldn't be able to fail
646 Py_DECREF(callbacks
);
647 return PyErr_NoMemory();
651 /* dbus_connection_get_object_path_data - not useful to Python,
652 * the object path data is just a PyString containing the path */
653 /* dbus_connection_list_registered could be useful, though */
655 /* dbus_connection_set_change_sigpipe - sets global state */
657 /* Maxima. Does Python code ever need to manipulate these?
658 * OTOH they're easy to wrap */
659 /* dbus_connection_set_max_message_size */
660 /* dbus_connection_get_max_message_size */
661 /* dbus_connection_set_max_received_size */
662 /* dbus_connection_get_max_received_size */
664 /* dbus_connection_get_outgoing_size - almost certainly unneeded */
666 static struct PyMethodDef Connection_tp_methods
[] = {
667 #define ENTRY(name, flags) {#name, (PyCFunction)Connection_##name, flags, Connection_##name##__doc__}
668 ENTRY(close
, METH_NOARGS
),
669 ENTRY(flush
, METH_NOARGS
),
670 ENTRY(get_is_connected
, METH_NOARGS
),
671 ENTRY(get_is_authenticated
, METH_NOARGS
),
672 ENTRY(set_exit_on_disconnect
, METH_VARARGS
),
673 ENTRY(get_unix_fd
, METH_NOARGS
),
674 ENTRY(get_peer_unix_user
, METH_NOARGS
),
675 ENTRY(get_peer_unix_process_id
, METH_NOARGS
),
676 ENTRY(add_message_filter
, METH_O
),
677 ENTRY(_register_object_path
, METH_VARARGS
|METH_KEYWORDS
),
678 ENTRY(remove_message_filter
, METH_O
),
679 ENTRY(send_message
, METH_VARARGS
),
680 ENTRY(send_message_with_reply
, METH_VARARGS
),
681 ENTRY(send_message_with_reply_and_block
, METH_VARARGS
),
682 ENTRY(_unregister_object_path
, METH_VARARGS
|METH_KEYWORDS
),
687 /* vim:set ft=c cino< sw=4 sts=4 et: */