D-Bus: use streams for direct IPC with GIO

When using GIO, it is possible to avoid the DBusServer listening on a
publicly accessible address. Connection setup becomes more reliable,
too, because the D-Bus server side can detect that a child died
because the connection will be closed.

When using libdbus, the traditional server/listen and client/connect
model is still used. GDBus GIO mimicks the same API to minimize
changes in ForkExec. The API gets simplified to support both
approaches:
- Choosing an address is no longer possible (was only used in the
  test example anyway)
- The new connection callback must be specified already when starting
  the server.

The GDBus GIO implementation uses SyncEvolution utility code. Strictly
speaking, this creates a circular dependency
libsyncevolution<->libgdbus. This is solved by not linking libgdbus
against libsyncevolution and expecting executables to do that instead.

The GDBus GIO example no longer linked because of that; it gets removed
because it was of little value.

Now that we started using CLOEXEC, we might as well use it for the
permanent file descriptors created for each ForkExec instance.
This commit is contained in:
Patrick Ohly 2014-02-05 15:55:54 +01:00
parent d0b7dfadf3
commit d89ca72d01
8 changed files with 155 additions and 461 deletions

View file

@ -63,8 +63,7 @@ void DBusConnectionPtr::setDisconnect(const Disconnect_t &func)
}
DBusConnectionPtr dbus_get_bus_connection(const std::string &address,
DBusErrorCXX *err,
bool /*delayed*/ /*= false*/)
DBusErrorCXX *err)
{
DBusConnectionPtr conn(dbus_connection_open_private(address.c_str(), err), false);
if (conn) {
@ -79,26 +78,20 @@ void dbus_bus_connection_undelay(const DBusConnectionPtr &/*ptr*/)
// no op
}
boost::shared_ptr<DBusServerCXX> DBusServerCXX::listen(const std::string &address, DBusErrorCXX *err)
boost::shared_ptr<DBusServerCXX> DBusServerCXX::listen(const NewConnection_t &newConnection, DBusErrorCXX *err)
{
DBusServer *server = NULL;
const char *realAddr = address.c_str();
char buffer[80];
char address[80];
if (address.empty()) {
realAddr = buffer;
buffer[0] = 0;
for (int counter = 1; counter < 100 && !server; counter++) {
if (*err) {
g_debug("dbus_server_listen(%s) failed, trying next candidate: %s",
buffer, err->message);
dbus_error_init(err);
}
sprintf(buffer, "unix:abstract=gdbuscxx-%d", counter);
server = dbus_server_listen(realAddr, err);
address[0] = 0;
for (int counter = 1; counter < 100 && !server; counter++) {
if (*err) {
g_debug("dbus_server_listen(%s) failed, trying next candidate: %s",
address, err->message);
dbus_error_init(err);
}
} else {
server = dbus_server_listen(realAddr, err);
sprintf(address, "unix:abstract=gdbuscxx-%d", counter);
server = dbus_server_listen(address, err);
}
if (!server) {
@ -106,8 +99,9 @@ boost::shared_ptr<DBusServerCXX> DBusServerCXX::listen(const std::string &addres
}
b_dbus_setup_server(server);
boost::shared_ptr<DBusServerCXX> res(new DBusServerCXX(server, realAddr));
dbus_server_set_new_connection_function(server, newConnection, res.get(), NULL);
boost::shared_ptr<DBusServerCXX> res(new DBusServerCXX(server, address));
res->m_newConnection = newConnection;
dbus_server_set_new_connection_function(server, DBusServerCXX::newConnection, res.get(), NULL);
return res;
}

View file

@ -201,8 +201,7 @@ DBusConnectionPtr dbus_get_bus_connection(const char *busType,
DBusErrorCXX *err);
DBusConnectionPtr dbus_get_bus_connection(const std::string &address,
DBusErrorCXX *err,
bool delayed = false);
DBusErrorCXX *err);
void dbus_bus_connection_undelay(const DBusConnectionPtr &conn);
@ -224,14 +223,10 @@ class DBusServerCXX : private boost::noncopyable
*/
typedef boost::function<void (DBusServerCXX &, DBusConnectionPtr &)> NewConnection_t;
void setNewConnectionCallback(const NewConnection_t &newConnection) { m_newConnection = newConnection; }
NewConnection_t getNewConnectionCallback() const { return m_newConnection; }
/**
* Start listening for new connections on the given address, like unix:abstract=myaddr.
* Address may be empty, in which case a new, unused address will chosen.
* Start listening for new connections on an unused address.
*/
static boost::shared_ptr<DBusServerCXX> listen(const std::string &address, DBusErrorCXX *err);
static boost::shared_ptr<DBusServerCXX> listen(const NewConnection_t &newConnection, DBusErrorCXX *err);
/**
* address used by the server

View file

@ -19,17 +19,28 @@
#include "gdbus-cxx-bridge.h"
#include <stdio.h>
#include <syncevo/gsignond-pipe-stream.h>
#include <syncevo/GuardFD.h>
#include <syncevo/GLibSupport.h>
#include <syncevo/util.h>
#include <errno.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/socket.h>
SE_GOBJECT_TYPE(GSignondPipeStream)
void intrusive_ptr_add_ref(GDBusConnection *con) { g_object_ref(con); }
void intrusive_ptr_release(GDBusConnection *con) { g_object_unref(con); }
void intrusive_ptr_add_ref(GDBusMessage *msg) { g_object_ref(msg); }
void intrusive_ptr_release(GDBusMessage *msg) { g_object_unref(msg); }
static void intrusive_ptr_add_ref(GDBusServer *server) { g_object_ref(server); }
static void intrusive_ptr_release(GDBusServer *server) { g_object_unref(server); }
namespace GDBusCXX {
using namespace SyncEvo;
MethodHandler::MethodMap MethodHandler::m_methodMap;
boost::function<void (void)> MethodHandler::m_callback;
@ -211,28 +222,25 @@ DBusConnectionPtr dbus_get_bus_connection(const char *busType,
}
DBusConnectionPtr dbus_get_bus_connection(const std::string &address,
DBusErrorCXX *err,
bool delayed /*= false*/)
DBusErrorCXX *err)
{
GError* error = NULL;
int flags = G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT;
if (delayed) {
flags |= G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING;
}
DBusConnectionPtr conn(g_dbus_connection_new_for_address_sync(address.c_str(),
static_cast<GDBusConnectionFlags>(flags),
NULL, /* GDBusAuthObserver */
NULL, /* GCancellable */
&error),
false);
// "address" needs to be the file descriptor number set up
// by DBusServerCXX::listen().
GuardFD fd(atoi(address.c_str()));
GSignondPipeStreamCXX stream(gsignond_pipe_stream_new(fd, fd, true),
TRANSFER_REF);
fd.release();
GErrorCXX gerror;
GDBusCXX::DBusConnectionPtr
conn(g_dbus_connection_new_sync(G_IO_STREAM(stream.get()),
NULL,
G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING,
NULL,
NULL,
gerror));
if (!conn && err) {
err->set(error);
} else {
g_clear_error(&error);
err->set(gerror.release());
}
return conn;
}
@ -268,110 +276,97 @@ void DBusConnectionPtr::setDisconnect(const Disconnect_t &func)
true);
}
boost::shared_ptr<DBusServerCXX> DBusServerCXX::listen(const std::string &address, DBusErrorCXX *err)
boost::shared_ptr<DBusServerCXX> DBusServerCXX::listen(const NewConnection_t &newConnection, DBusErrorCXX *)
{
GDBusServer *server = NULL;
const char *realAddr = address.c_str();
char buffer[80];
gchar *guid = g_dbus_generate_guid();
GError *error = NULL;
if (address.empty()) {
realAddr = buffer;
for (int counter = 1; counter < 100 && !server; counter++) {
if (error) {
// previous attempt failed
g_debug("setting up D-Bus server on %s failed, trying next address: %s",
realAddr,
error->message);
g_clear_error(&error);
}
sprintf(buffer, "unix:abstract=gdbuscxx-%d", counter);
server = g_dbus_server_new_sync(realAddr,
G_DBUS_SERVER_FLAGS_NONE,
guid,
NULL, /* GDBusAuthObserver */
NULL, /* GCancellable */
&error);
}
} else {
server = g_dbus_server_new_sync(realAddr,
G_DBUS_SERVER_FLAGS_NONE,
guid,
NULL, /* GDBusAuthObserver */
NULL, /* GCancellable */
&error);
// Create two fds connected via a two-way stream. The parent
// keeps fd[0] which gets closed automatically when the child
// execs. The parent closes the child's fd[1] after forking.
int fds[2];
int retval = socketpair(AF_UNIX, SOCK_STREAM|SOCK_CLOEXEC, 0, fds);
if (retval) {
SE_THROW(StringPrintf("socketpair: %s", strerror(errno)));
}
g_free(guid);
GuardFD parentfd(fds[0]);
GuardFD childfd(fds[1]);
if (!server) {
if (err) {
err->set(error);
} else {
g_clear_error(&error);
}
return boost::shared_ptr<DBusServerCXX>();
// Child must inherit its fd.
int fdflags;
if ((fdflags = fcntl(childfd, F_GETFD)) == -1 ||
fcntl(childfd, F_SETFD, fdflags & ~FD_CLOEXEC)) {
SE_THROW(StringPrintf("fcntl: %s", strerror(errno)));
}
// steals reference to 'server'
boost::shared_ptr<DBusServerCXX> res(new DBusServerCXX(server, realAddr));
g_signal_connect(server,
"new-connection",
G_CALLBACK(DBusServerCXX::newConnection),
res.get());
// Out listen "address" is the FD number.
std::string address = StringPrintf("%d", childfd.get());
// Transfer ownership of parent fd.
GSignondPipeStreamCXX stream(gsignond_pipe_stream_new(parentfd, parentfd, true),
TRANSFER_REF);
parentfd.release();
GErrorCXX gerror;
GDBusCXX::DBusConnectionPtr
connection(g_dbus_connection_new_sync(G_IO_STREAM(stream.get()),
NULL,
G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING,
NULL,
NULL,
gerror),
false);
if (!connection) {
gerror.throwError("creating GIO D-Bus connection");
}
// A fake DBusServerCXX which does nothing more than return the address, aka
// our FD number, and store data for the idle callback.
boost::shared_ptr<DBusServerCXX> res(new DBusServerCXX(address));
res->m_newConnection = newConnection;
res->m_connection = connection;
// Will be freed in the idle callback. Caller must have forked by then.
res->m_childfd = childfd.release();
// The caller must have some time to set up connection handling and fork.
// Delay the newConnection() callback until we enter the main event loop
// again. Callback must be removed when destructing prematurely because it
// has a plain "this" pointer.
res->m_connectionIdle = g_idle_add(onIdleOnce, &*res);
return res;
}
gboolean DBusServerCXX::newConnection(GDBusServer *server, GDBusConnection *newConn, void *data) throw()
{
DBusServerCXX *me = static_cast<DBusServerCXX *>(data);
if (me->m_newConnection) {
GCredentials *credentials;
std::string credString;
credentials = g_dbus_connection_get_peer_credentials(newConn);
if (credentials == NULL) {
credString = "(no credentials received)";
} else {
gchar *s = g_credentials_to_string(credentials);
credString = s;
g_free(s);
}
g_debug("Client connected.\n"
"Peer credentials: %s\n"
"Negotiated capabilities: unix-fd-passing=%d\n",
credString.c_str(),
g_dbus_connection_get_capabilities(newConn) & G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING);
try {
// Ref count of connection has to be increased if we want to handle it.
// Something inside m_newConnection has to take ownership of connection,
// because conn increases ref count only temporarily.
DBusConnectionPtr conn(newConn, true);
me->m_newConnection(*me, conn);
} catch (...) {
g_error("handling new D-Bus connection failed with C++ exception");
return FALSE;
}
return TRUE;
} else {
return FALSE;
}
}
DBusServerCXX::DBusServerCXX(GDBusServer *server, const std::string &address) :
m_server(server, false), // steal reference
DBusServerCXX::DBusServerCXX(const std::string &address) :
m_connectionIdle(0),
m_childfd(-1),
m_address(address)
{
g_dbus_server_start(server);
}
DBusServerCXX::~DBusServerCXX()
{
g_dbus_server_stop(m_server.get());
if (m_connectionIdle) {
g_source_remove(m_connectionIdle);
}
if (m_childfd >= 0) {
close(m_childfd);
}
}
gboolean DBusServerCXX::onIdleOnce(gpointer custom)
{
DBusServerCXX *me = static_cast<DBusServerCXX *>(custom);
me->m_connectionIdle = 0;
me->m_newConnection(*me, me->m_connection);
me->m_connection.reset();
close(me->m_childfd);
me->m_childfd = -1;
// not again
return false;
}
void Watch::nameOwnerChanged(GDBusConnection *connection,
const gchar *sender_name,
const gchar *object_path,

View file

@ -314,8 +314,7 @@ DBusConnectionPtr dbus_get_bus_connection(const char *busType,
DBusErrorCXX *err);
DBusConnectionPtr dbus_get_bus_connection(const std::string &address,
DBusErrorCXX *err,
bool delayed = false);
DBusErrorCXX *err);
inline void dbus_bus_connection_undelay(const DBusConnectionPtr &conn) { conn.undelay(); }
@ -333,18 +332,22 @@ class DBusServerCXX : private boost::noncopyable
* Called for each new connection. Callback must store the DBusConnectionPtr,
* otherwise it will be unref'ed after the callback returns.
* If the new connection is not wanted, then it is good style to close it
* explicitly in the callback.
* explicitly in the callback. Message processing is delayed on the new
* connection, so the callback can set up objects and then must undelay
* the connection.
*/
typedef boost::function<void (DBusServerCXX &, DBusConnectionPtr &)> NewConnection_t;
void setNewConnectionCallback(const NewConnection_t &newConnection) { m_newConnection = newConnection; }
NewConnection_t getNewConnectionCallback() const { return m_newConnection; }
/**
* Start listening for new connections on the given address, like unix:abstract=myaddr.
* Address may be empty, in which case a new, unused address will chosen.
* Start listening for new connections. Mimics the libdbus DBusServer API, but
* underneath sets up a single connection via pipes. The caller must fork
* the process which calls dbus_get_bus_connection() before entering the main
* event loop again because that is when the DBusServerCXX will finish
* the connection setup (close child fd, call newConnection).
*
* All errors are reported via exceptions, not "err".
*/
static boost::shared_ptr<DBusServerCXX> listen(const std::string &address, DBusErrorCXX *err);
static boost::shared_ptr<DBusServerCXX> listen(const NewConnection_t &newConnection, DBusErrorCXX *err);
/**
* address used by the server
@ -352,12 +355,14 @@ class DBusServerCXX : private boost::noncopyable
std::string getAddress() const { return m_address; }
private:
DBusServerCXX(GDBusServer *server, const std::string &address);
static gboolean newConnection(GDBusServer *server, GDBusConnection *newConn, void *data) throw();
DBusServerCXX(const std::string &address);
DBusConnectionPtr m_connection;
NewConnection_t m_newConnection;
boost::intrusive_ptr<GDBusServer> m_server;
guint m_connectionIdle;
int m_childfd;
std::string m_address;
static gboolean onIdleOnce(gpointer custom);
};
/**

View file

@ -13,12 +13,6 @@ src_gdbusxx_libgdbussyncevo_la_SOURCES = \
src_gdbusxx_libgdbussyncevo_la_LDFLAGS = $(src_gdbus_version_info)
src_gdbusxx_libgdbussyncevo_la_LIBADD = $(GLIB_LIBS) $(DBUS_LIBS)
src_gdbusxx_libgdbussyncevo_la_CXXFLAGS = $(GLIB_CFLAGS) $(DBUS_CFLAGS) $(SYNCEVO_WFLAGS)
src_gdbusxx_libgdbussyncevo_la_CPPFLAGS = $(BOOST_CPPFLAGS)
src_gdbusxx_libgdbussyncevo_la_CPPFLAGS = $(BOOST_CPPFLAGS) -I$(top_srcdir)/src/ # allow access to libsyncevolution utility code
MAINTAINERCLEANFILES += Makefile.in
noinst_PROGRAMS += src/gdbusxx/example
src_gdbusxx_example_SOURCES = src/gdbusxx/test/example.cpp
src_gdbusxx_example_CPPFLAGS = -I$(top_srcdir)/src/gdbusxx/ $(BOOST_CPPFLAGS)
src_gdbusxx_example_CXXFLAGS = $(GLIB_CFLAGS) $(DBUS_CFLAGS) $(SYNCEVO_WFLAGS)
src_gdbusxx_example_LDADD = src/gdbusxx/libgdbussyncevo.la $(GLIB_LIBS) $(DBUS_LIBS)

View file

@ -1,293 +0,0 @@
/*
*
* Library for simple D-Bus integration with GLib
*
* Copyright (C) 2009 Intel Corporation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <sys/signal.h>
#include "gdbus-cxx-bridge.h"
#include <memory>
#include <iostream>
#include <boost/noncopyable.hpp>
namespace GDBusCXX {
struct args {
int a;
std::string b;
std::map<std::string, std::string> c;
};
static void hello_global() {}
class Test {
typedef boost::shared_ptr< Result1<const std::string&> > string_result;
struct async : private boost::noncopyable
{
async(const boost::shared_ptr<Watch> &watch, Watch *watch2, const string_result &result):
m_watch(watch),
m_watch2(watch2),
m_result(result)
{}
~async()
{
delete m_watch2;
}
boost::shared_ptr<Watch> m_watch;
Watch *m_watch2;
string_result m_result;
};
static gboolean method_idle(gpointer data)
{
std::auto_ptr<async> mydata(static_cast<async *>(data));
std::cout << "replying to method_async" << std::endl;
mydata->m_result->done("Hello World, asynchronous and delayed");
return false;
}
static void disconnect(const std::string &id, const std::string &peer)
{
std::cout << id << ": " << peer << " has disconnected." << std::endl;
}
public:
static void hello_static() {}
void hello_const() const {}
static void hello_world(const char *msg) { puts(msg); }
void hello_base() {}
void method(std::string &text)
{
text = "Hello World";
}
void method_async(const Caller_t &caller,
const boost::shared_ptr<Watch> &watch,
int32_t secs,
const string_result &r)
{
watch->setCallback(boost::bind(disconnect, "watch1", caller));
Watch *watch2 = r->createWatch(boost::bind(disconnect, "watch2", caller));
std::cout << "method_async called by " << caller << " delay " << secs << std::endl;
g_timeout_add_seconds(secs, method_idle, new async(watch, watch2, r));
}
void method2(int32_t arg, int32_t &ret)
{
ret = arg * 2;
}
int32_t method3(int32_t arg)
{
return arg * 3;
}
void method8_simple(int32_t a1, int32_t a2, int32_t a3, int32_t a4, int32_t a5,
int32_t a6, int32_t a7, int32_t a8)
{
}
void method9_async(Result9<int32_t, int32_t, int32_t, int32_t, int32_t,
int32_t, int32_t, int32_t, int32_t> *r)
{
r->done(1, 2, 3, 4, 5, 6, 7, 8, 9);
delete r;
}
int32_t method9(int32_t a1, int32_t a2, int32_t a3, int32_t a4, int32_t a5,
int32_t a6, int32_t a7, int32_t a8, int32_t a9)
{
return 0;
}
void hash(const std::map<int8_t, int32_t> &in, std::map<int16_t, int32_t> &out)
{
for (std::map<int8_t, int32_t>::const_iterator it = in.begin();
it != in.end();
++it) {
out.insert(std::make_pair((int16_t)it->first, it->second * it->second));
}
}
void array(const std::vector<int32_t> &in, std::vector<int32_t> &out)
{
for (std::vector<int32_t>::const_iterator it = in.begin();
it != in.end();
++it) {
out.push_back(*it * *it);
}
}
void error()
{
throw dbus_error("org.example.error.Invalid", "error");
}
void argtest(const args &in, args &out)
{
out = in;
out.a = in.a + 1;
}
};
class Test2
{
public:
void test2() {}
};
template<> struct dbus_traits<args> :
public dbus_struct_traits<args, dbus_member<args, int, &args::a,
dbus_member<args, std::string, &args::b,
dbus_member_single<args, std::map<std::string, std::string>, &args::c> > > >
{};
class DBusTest : public Test, private Test2
{
DBusObjectHelper m_object;
DBusObjectHelper m_secondary;
public:
DBusTest(const DBusConnectionPtr &conn) :
m_object(conn, "/test", "org.example.Test"),
// same path!
m_secondary(conn, m_object.getPath(), "org.example.Secondary"),
signal(m_object, "Signal")
{
m_object.add(this, &Test::method8_simple, "Method8Simple");
// m_object.add(this, &Test::method10_async, "Method10Async", G_DBUS_METHOD_FLAG_ASYNC);
// m_object.add(this, &Test::method9, "Method9");
m_object.add(this, &Test::method2, "Method2");
m_object.add(this, &Test::method3, "Method3");
m_object.add(this, &Test::method, "Test");
m_object.add(this, &Test::method_async, "TestAsync");
m_object.add(this, &Test::argtest, "ArgTest");
m_object.add(this, &Test::hash, "Hash");
m_object.add(this, &Test::array, "Array");
m_object.add(this, &Test::error, "Error");
m_object.add(&hello_global, "Global");
m_object.add(&DBusTest::hello_static, "Static");
m_object.add(static_cast<Test2 *>(this), &Test2::test2, "Private");
// The hello_const() method cannot be registered
// because there is no matching MakeMethodEntry<>
// specialization for it or DBusObjectHelper::add()
// fails to determine the right function type,
// depending how one wants to interpret the problem.
// m_object.add2(this, &DBusTest::hello_const, "Const");
m_object.add(signal);
m_secondary.add(this, &DBusTest::hello, "Hello");
}
~DBusTest()
{
}
EmitSignal3<int32_t, const std::string &, const std::map<int32_t, int32_t> &>signal;
void hello() {}
static void hello_static() {}
void hello_const() const {}
void activate()
{
m_secondary.activate();
m_object.activate();
}
void deactivate()
{
m_object.deactivate();
m_secondary.deactivate();
}
};
static GMainLoop *main_loop = NULL;
static void sig_term(int sig)
{
g_main_loop_quit(main_loop);
}
} // namespace GDBusCXX
using namespace GDBusCXX;
int main(int argc, char *argv[])
{
DBusConnectionPtr conn;
DBusErrorCXX err;
struct sigaction sa;
memset(&sa, 0, sizeof(sa));
sa.sa_handler = sig_term;
sigaction(SIGINT, &sa, NULL);
sigaction(SIGTERM, &sa, NULL);
sa.sa_handler = SIG_IGN;
sigaction(SIGCHLD, &sa, NULL);
sigaction(SIGPIPE, &sa, NULL);
main_loop = g_main_loop_new(NULL, FALSE);
conn = dbus_get_bus_connection("SESSION", "org.example", false, &err);
if (conn == NULL) {
std::string message = err.getMessage();
if (!message.empty()) {
fprintf(stderr, "%s\n", message.c_str());
} else
fprintf(stderr, "Can't register with session bus\n");
exit(1);
}
std::auto_ptr<DBusTest> test(new DBusTest(conn));
test->activate();
test->signal(42, "hello world", std::map<int32_t, int32_t>());
test->deactivate();
test->activate();
test->signal(123, "here I am again", std::map<int32_t, int32_t>());
g_main_loop_run(main_loop);
test.reset();
// is this really necessary?
// if(!g_dbus_connection_close_sync(conn, NULL, NULL)) {
// fprintf(stderr, "Problem closing connection.\n");
// }
g_main_loop_unref(main_loop);
return 0;
}

View file

@ -23,6 +23,9 @@
#if defined(HAVE_GLIB)
#include <unistd.h>
#include <fcntl.h>
#include <pcrecpp.h>
#include <ctype.h>
#include "test.h"
@ -182,11 +185,10 @@ void ForkExecParent::start()
GDBusCXX::DBusErrorCXX dbusError;
SE_LOG_DEBUG(NULL, "ForkExecParent: preparing for child process %s", m_helper.c_str());
m_server = GDBusCXX::DBusServerCXX::listen("", &dbusError);
m_server = GDBusCXX::DBusServerCXX::listen(boost::bind(&ForkExecParent::newClientConnection, this, _2), &dbusError);
if (!m_server) {
dbusError.throwFailure("starting server");
}
m_server->setNewConnectionCallback(boost::bind(&ForkExecParent::newClientConnection, this, _2));
// look for helper binary
std::string helper;
@ -246,7 +248,7 @@ void ForkExecParent::start()
if (!g_spawn_async_with_pipes(NULL, // working directory
static_cast<gchar **>(m_argv.get()),
static_cast<gchar **>(m_env.get()),
flags,
(GSpawnFlags)(flags | G_SPAWN_LEAVE_DESCRIPTORS_OPEN),
// child setup function: redirect stdout to stderr, undo LogRedirect
forked, this,
&m_childPid,
@ -277,6 +279,10 @@ void ForkExecParent::setupPipe(GIOChannel *&channel, guint &sourceID, int fd)
return;
}
// Other program executed by us shall not inherit a copy of this
// file descriptor.
fcntl(fd, F_SETFD, fcntl(fd, F_GETFD) | FD_CLOEXEC);
channel = g_io_channel_unix_new(fd);
if (!channel) {
// failure
@ -438,6 +444,7 @@ void ForkExecParent::newClientConnection(GDBusCXX::DBusConnectionPtr &conn) thro
m_api.reset(new ForkExecParentDBusAPI(conn, getInstance()));
#endif
m_onConnect(conn);
dbus_bus_connection_undelay(conn);
} catch (...) {
std::string explanation;
SyncMLStatus status = Exception::handle(explanation);
@ -533,8 +540,7 @@ void ForkExecChild::connect()
address);
GDBusCXX::DBusErrorCXX dbusError;
GDBusCXX::DBusConnectionPtr conn = dbus_get_bus_connection(address,
&dbusError,
true /* always delay message processing */);
&dbusError);
if (!conn) {
dbusError.throwFailure("connecting to server");
}

View file

@ -248,7 +248,7 @@ int main(int argc, char **argv)
{ "forkexec", 'e', 0, G_OPTION_ARG_NONE, &opt_fork_exec, "Use fork+exec to start the client (implies --server)", NULL },
{ "forkfailure", 'f', 0, G_OPTION_ARG_NONE, &opt_fork_exec_failure, "Fork /bin/false to simulate a failure in the child (implies )", NULL },
{ "forkkill", 'a', 0, G_OPTION_ARG_STRING, &opt_kill, "'child/parent' call peer which kills itself before replying (implies --forkexec)", NULL },
{ "address", 'a', 0, G_OPTION_ARG_STRING, &opt_address, "D-Bus address to use", NULL },
{ "address", 'a', 0, G_OPTION_ARG_STRING, &opt_address, "D-Bus address to use when connecting to server", NULL },
// { "allow-anonymous", 'n', 0, G_OPTION_ARG_NONE, &opt_allow_anonymous, "Allow anonymous authentication", NULL },
{ NULL}
};
@ -293,16 +293,14 @@ int main(int argc, char **argv)
forkexec->start();
g_main_loop_run(loop.get());
} else if (opt_server) {
boost::scoped_ptr<Test> testptr;
boost::shared_ptr<GDBusCXX::DBusServerCXX> server =
GDBusCXX::DBusServerCXX::listen(opt_address ?
opt_address : "",
GDBusCXX::DBusServerCXX::listen(boost::bind(newClientConnection, _1, _2, boost::ref(testptr)),
&dbusError);
if (!server) {
dbusError.throwFailure("starting server");
}
std::cout << "Server is listening at: " << server->getAddress() << std::endl;
boost::scoped_ptr<Test> testptr;
server->setNewConnectionCallback(boost::bind(newClientConnection, _1, _2, boost::ref(testptr)));
g_main_loop_run(loop.get());
} else if (SyncEvo::ForkExecChild::wasForked()) {