"wvtestmain ''" actually still runs all the tests, so skip the warning.
[wvstreams.git] / dbus / wvdbusserver.cc
blob7dd76e215fa578b067cf4ccc6f71f86fdd9bcee1
1 /* -*- Mode: C++ -*-
2 * Worldvisions Weaver Software:
3 * Copyright (C) 2005-2006 Net Integration Technologies, Inc.
4 *
5 * Pathfinder Software:
6 * Copyright (C) 2007, Carillon Information Security Inc.
8 * This library is licensed under the LGPL, please read LICENSE for details.
10 */
11 #include "wvdbusserver.h"
12 #include "wvdbusconn.h"
13 #include "wvstrutils.h"
14 #include "wvuid.h"
15 #include "wvtcplistener.h"
16 #include "wvdelayedcallback.h"
17 #undef interface // windows
18 #include <dbus/dbus.h>
19 #include "wvx509.h"
22 class WvDBusServerAuth : public IWvDBusAuth
24 enum State { NullWait, AuthWait, BeginWait };
25 State state;
26 wvuid_t client_uid;
27 public:
28 WvDBusServerAuth();
29 virtual bool authorize(WvDBusConn &c);
31 virtual wvuid_t get_uid() { return client_uid; }
35 WvDBusServerAuth::WvDBusServerAuth()
37 state = NullWait;
38 client_uid = WVUID_INVALID;
42 bool WvDBusServerAuth::authorize(WvDBusConn &c)
44 c.log("State=%s\n", state);
45 if (state == NullWait)
47 char buf[1];
48 size_t len = c.read(buf, 1);
49 if (len == 1 && buf[0] == '\0')
51 state = AuthWait;
52 // fall through
54 else if (len > 0)
55 c.seterr("Client didn't start with NUL byte");
56 else
57 return false; // no data yet, come back later
60 const char *line = c.in();
61 if (!line)
62 return false; // not done yet
64 WvStringList words;
65 words.split(line);
66 WvString cmd(words.popstr());
68 if (state == AuthWait)
70 if (!strcasecmp(cmd, "AUTH"))
72 // FIXME actually check authentication information!
73 WvString typ(words.popstr());
74 if (!strcasecmp(typ, "EXTERNAL"))
76 WvString uid =
77 WvHexDecoder().strflushstr(words.popstr());
78 if (!!uid)
80 // FIXME: Check that client is on the same machine!
81 client_uid = uid.num();
84 state = BeginWait;
85 c.out("OK f00f\r\n");
87 else
89 // Some clients insist that we reject something because
90 // their state machine can't handle us accepting just the
91 // "AUTH " command.
92 c.out("REJECTED EXTERNAL\r\n");
93 // no change in state
96 else
97 c.seterr("AUTH command expected: '%s'", line);
99 else if (state == BeginWait)
101 if (!strcasecmp(cmd, "BEGIN"))
102 return true; // done
103 else
104 c.seterr("BEGIN command expected: '%s'", line);
107 return false;
111 WvDBusServer::WvDBusServer()
112 : log("DBus Server", WvLog::Debug)
114 // user must now call listen() at least once.
115 add(&listeners, false, "listeners");
119 WvDBusServer::~WvDBusServer()
121 close();
122 zap();
126 void WvDBusServer::listen(WvStringParm moniker)
128 IWvListener *listener = IWvListener::create(moniker);
129 log(WvLog::Info, "Listening on '%s'\n", *listener->src());
130 if (!listener->isok())
131 log(WvLog::Info, "Can't listen: %s\n",
132 listener->errstr());
133 listener->onaccept(wv::bind(&WvDBusServer::new_connection_cb,
134 this, _1));
135 listeners.add(listener, true, "listener");
139 bool WvDBusServer::isok() const
141 if (geterr())
142 return false;
144 WvIStreamList::Iter i(listeners);
145 for (i.rewind(); i.next(); )
146 if (!i->isok())
147 return false;
148 return WvIStreamList::isok();
152 int WvDBusServer::geterr() const
154 return WvIStreamList::geterr();
158 WvString WvDBusServer::get_addr()
160 // FIXME assumes tcp
161 WvIStreamList::Iter i(listeners);
162 for (i.rewind(); i.next(); )
163 if (i->isok())
164 return WvString("tcp:%s", *i->src());
165 return WvString();
169 void WvDBusServer::register_name(WvStringParm name, WvDBusConn *conn)
171 name_to_conn[name] = conn;
175 void WvDBusServer::unregister_name(WvStringParm name, WvDBusConn *conn)
177 assert(name_to_conn[name] == conn);
178 name_to_conn.erase(name);
182 void WvDBusServer::unregister_conn(WvDBusConn *conn)
185 std::map<WvString,WvDBusConn*>::iterator i;
186 for (i = name_to_conn.begin(); i != name_to_conn.end(); )
188 if (i->second == conn)
190 name_to_conn.erase(i->first);
191 i = name_to_conn.begin();
193 else
194 ++i;
198 all_conns.unlink(conn);
202 bool WvDBusServer::do_server_msg(WvDBusConn &conn, WvDBusMsg &msg)
204 WvString method(msg.get_member());
206 if (msg.get_path() == "/org/freedesktop/DBus/Local")
208 if (method == "Disconnected")
209 return true; // nothing to do until their *stream* disconnects
212 if (msg.get_dest() != "org.freedesktop.DBus") return false;
214 // dbus-daemon seems to ignore the path as long as the service is right
215 //if (msg.get_path() != "/org/freedesktop/DBus") return false;
217 // I guess it's for us!
219 if (method == "Hello")
221 log("hello_cb\n");
222 msg.reply().append(conn.uniquename()).send(conn);
223 return true;
225 else if (method == "RequestName")
227 WvDBusMsg::Iter args(msg);
228 WvString _name = args.getnext();
229 // uint32_t flags = args.getnext(); // supplied, but ignored
231 log("request_name_cb(%s)\n", _name);
232 register_name(_name, &conn);
234 msg.reply().append((uint32_t)DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER)
235 .send(conn);
236 return true;
238 else if (method == "ReleaseName")
240 WvDBusMsg::Iter args(msg);
241 WvString _name = args.getnext();
243 log("release_name_cb(%s)\n", _name);
244 unregister_name(_name, &conn);
246 msg.reply().append((uint32_t)DBUS_RELEASE_NAME_REPLY_RELEASED)
247 .send(conn);
248 return true;
250 else if (method == "NameHasOwner")
252 WvDBusMsg::Iter args(msg);
253 WvString known_name = args.getnext();
254 WvDBusConn *serv = name_to_conn[known_name];
255 msg.reply().append(!!serv).send(conn);
256 return true;
258 else if (method == "GetNameOwner")
260 WvDBusMsg::Iter args(msg);
261 WvString known_name = args.getnext();
262 WvDBusConn *serv = name_to_conn[known_name];
263 if (serv)
264 msg.reply().append(serv->uniquename()).send(conn);
265 else
266 WvDBusError(msg, "org.freedesktop.DBus.Error.NameHasNoOwner",
267 "No match for name '%s'", known_name).send(conn);
268 return true;
270 else if (method == "AddMatch")
272 // we just proxy every signal to everyone for now
273 msg.reply().send(conn);
274 return true;
276 else if (method == "StartServiceByName")
278 // we don't actually support this, but returning an error message
279 // confuses perl's Net::DBus library, at least.
280 msg.reply().send(conn);
281 return true;
283 else if (method == "GetConnectionUnixUser" ||
284 method == "GetConnectionUnixUserName")
286 WvDBusMsg::Iter args(msg);
287 WvString _name = args.getnext();
288 WvDBusConn *target = name_to_conn[_name];
290 if (!target)
292 WvDBusError(msg, "org.freedesktop.DBus.Error.Failed",
293 "No connection found for name '%s'.", _name).send(conn);
294 return true;
297 wvuid_t client_uid = target->get_uid();
299 if (client_uid == WVUID_INVALID)
301 WvDBusError(msg, "org.freedesktop.DBus.Error.Failed",
302 "No user associated with connection '%s'.",
303 target->uniquename()).send(conn);
304 return true;
307 log("Found unix user for '%s', uid is %s.\n", _name, client_uid);
309 if (method == "GetConnectionUnixUser")
311 WvString s(client_uid);
312 msg.reply().append((uint32_t)atoll(s)).send(conn);
313 return true;
315 else if (method == "GetConnectionUnixUserName")
317 WvString username = wv_username_from_uid(client_uid);
318 if (!username)
320 WvDBusError(msg, "org.freedesktop.DBus.Error.Failed",
321 "No username for uid='%s'", client_uid)
322 .send(conn);
323 return true;
326 msg.reply().append(username).send(conn);
327 return true;
329 else
330 assert(false); // should never happen
332 assert(false);
334 else if (method == "GetConnectionCert" ||
335 method == "GetConnectionCertFingerprint")
337 WvDBusMsg::Iter args(msg);
338 WvString connid = args.getnext();
340 WvDBusConn *c = name_to_conn[connid];
342 WvString ret = c ? c->getattr("peercert") : WvString::null;
343 if (ret.isnull())
344 WvDBusError(msg, "org.freedesktop.DBus.Error.Failed",
345 "Connection %s did not present a certificate",
346 connid).send(conn);
347 else
349 if (method == "GetConnectionCertFingerprint")
351 WvX509 tempcert;
352 // We can assume it's valid because our SSL conn authenticated
353 tempcert.decode(WvX509::CertPEM, ret);
354 ret = tempcert.get_fingerprint();
356 msg.reply().append(ret).send(conn);
359 return true;
361 else
363 WvDBusError(msg, "org.freedesktop.DBus.Error.UnknownMethod",
364 "Unknown dbus method '%s'", method).send(conn);
365 return true; // but we've handled it, since it belongs to us
370 bool WvDBusServer::do_bridge_msg(WvDBusConn &conn, WvDBusMsg &msg)
372 // if we get here, nobody handled the message internally, so we can try
373 // to proxy it.
374 if (!!msg.get_dest()) // don't handle blank (broadcast) paths here
376 std::map<WvString,WvDBusConn*>::iterator i
377 = name_to_conn.find(msg.get_dest());
378 WvDBusConn *dconn = (i == name_to_conn.end()) ? NULL : i->second;
379 log("Proxying #%s -> %s\n",
380 msg.get_serial(),
381 dconn ? dconn->uniquename() : WvString("(UNKNOWN)"));
382 dbus_message_set_sender(msg, conn.uniquename().cstr());
383 if (dconn)
384 dconn->send(msg);
385 else
387 log(WvLog::Warning,
388 "Proxy: no connection for '%s'\n", msg.get_dest());
389 return false;
391 return true;
394 return false;
398 bool WvDBusServer::do_broadcast_msg(WvDBusConn &conn, WvDBusMsg &msg)
400 if (!msg.get_dest())
402 log("Broadcasting #%s\n", msg.get_serial());
404 // note: we broadcast messages even back to the connection where
405 // they originated. I'm not sure this is necessarily ideal, but if
406 // you don't do that then an app can't signal objects that might be
407 // inside itself.
408 WvDBusConnList::Iter i(all_conns);
409 for (i.rewind(); i.next(); )
410 i->send(msg);
411 return true;
413 return false;
417 bool WvDBusServer::do_gaveup_msg(WvDBusConn &conn, WvDBusMsg &msg)
419 WvDBusError(msg, "org.freedesktop.DBus.Error.NameHasNoOwner",
420 "No running service named '%s'", msg.get_dest()).send(conn);
421 return true;
425 void WvDBusServer::conn_closed(WvStream &s)
427 WvDBusConn *c = (WvDBusConn *)&s;
428 unregister_conn(c);
429 this->release();
433 void WvDBusServer::new_connection_cb(IWvStream *s)
435 WvDBusConn *c = new WvDBusConn(s, new WvDBusServerAuth, false);
436 c->addRef();
437 this->addRef();
438 all_conns.append(c, true);
439 register_name(c->uniquename(), c);
441 /* The delayed callback here should be explained. The
442 * 'do_broadcast_msg' function sends out data along all connections.
443 * Unfortunately, this is a prime time to figure out a connection died.
444 * A dying connection is removed from the all_conns list... but we are
445 * still in do_broadcast_msg, and using an iterator to go over this list.
446 * The consequences of this were not pleasant, at best. Wrapping cb in a
447 * delayedcallback will always safely remove a connection.
449 IWvStreamCallback mycb = wv::bind(&WvDBusServer::conn_closed, this,
450 wv::ref(*c));
451 c->setclosecallback(wv::delayed(mycb));
453 c->add_callback(WvDBusConn::PriSystem,
454 wv::bind(&WvDBusServer::do_server_msg, this,
455 wv::ref(*c), _1));
456 c->add_callback(WvDBusConn::PriBridge,
457 wv::bind(&WvDBusServer::do_bridge_msg, this,
458 wv::ref(*c), _1));
459 c->add_callback(WvDBusConn::PriBroadcast,
460 wv::bind(&WvDBusServer::do_broadcast_msg, this,
461 wv::ref(*c), _1));
462 c->add_callback(WvDBusConn::PriGaveUp,
463 wv::bind(&WvDBusServer::do_gaveup_msg, this,
464 wv::ref(*c), _1));
466 append(c, true, "wvdbus servconn");