summaryrefslogtreecommitdiff
path: root/examples/dbus/peer.cc
blob: 5d80d70155a6fcf77599262c5b194b75e901a466 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
/* Copyright (C) 2011 The giomm Development Team
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library 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
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free
 * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */

/*

Usage examples (modulo addresses / credentials) (copied from the C API's
GDBusServer's example).

UNIX domain socket transport:

 Server:
   $ ./peer --server --address unix:abstract=myaddr
   Server is listening at: unix:abstract=myaddr
   Client connected.
   Peer credentials: GCredentials:unix-user=500,unix-group=500,unix-process=13378
   Negotiated capabilities: unix-fd-passing=1
   Client said: Hey, it's 1273093080 already!

 Client:
   $ ./peer --address unix:abstract=myaddr
   Connected.
   Negotiated capabilities: unix-fd-passing=1
   Server said: You said 'Hey, it's 1273093080 already!'. KTHXBYE!

Nonce-secured TCP transport on the same host:

 Server:
   $ ./peer --server --address nonce-tcp:
   Server is listening at: nonce-tcp:host=localhost,port=43077,noncefile=/tmp/gdbus-nonce-file-X1ZNCV
   Client connected.
   Peer credentials: (no credentials received)
   Negotiated capabilities: unix-fd-passing=0
   Client said: Hey, it's 1273093206 already!

 Client:
   $ ./peer -address nonce-tcp:host=localhost,port=43077,noncefile=/tmp/gdbus-nonce-file-X1ZNCV
   Connected.
   Negotiated capabilities: unix-fd-passing=0
   Server said: You said 'Hey, it's 1273093206 already!'. KTHXBYE!

TCP transport on two different hosts with a shared home directory:

 Server:
   host1 $ ./peer --server --address tcp:host=0.0.0.0
   Server is listening at: tcp:host=0.0.0.0,port=46314
   Client connected.
   Peer credentials: (no credentials received)
   Negotiated capabilities: unix-fd-passing=0
   Client said: Hey, it's 1273093337 already!

 Client:
   host2 $ ./peer -a tcp:host=host1,port=46314
   Connected.
   Negotiated capabilities: unix-fd-passing=0
   Server said: You said 'Hey, it's 1273093337 already!'. KTHXBYE!

TCP transport on two different hosts without authentication:

 Server:
   host1 $ ./peer --server --address tcp:host=0.0.0.0 --allow-anonymous
   Server is listening at: tcp:host=0.0.0.0,port=59556
   Client connected.
   Peer credentials: (no credentials received)
   Negotiated capabilities: unix-fd-passing=0
   Client said: Hey, it's 1273093652 already!

 Client:
   host2 $ ./peer -a tcp:host=host1,port=59556
   Connected.
   Negotiated capabilities: unix-fd-passing=0
   Server said: You said 'Hey, it's 1273093652 already!'. KTHXBYE!
*/

#include <giomm.h>
#include <glibmm.h>
#include <iostream>

static Glib::RefPtr<Gio::DBus::NodeInfo> introspection_data;

static Glib::ustring introspection_xml =
  "<node>"
  "  <interface name='org.glibmm.DBus.TestPeerInterface'>"
  "    <method name='HelloWorld'>"
  "      <arg type='s' name='greeting' direction='in'/>"
  "      <arg type='s' name='response' direction='out'/>"
  "    </method>"
  "  </interface>"
  "</node>";

// This variable is used to keep an incoming connection active until it is
// closed.
static Glib::RefPtr<Gio::DBus::Connection> curr_connection;

static void on_method_call(const Glib::RefPtr<Gio::DBus::Connection>&,
  const Glib::ustring& /* sender */, const Glib::ustring& /* object_path */,
  const Glib::ustring& /* interface_name */, const Glib::ustring& method_name,
  const Glib::VariantContainerBase& parameters,
  const Glib::RefPtr<Gio::DBus::MethodInvocation>& invocation)
{
  if(method_name == "HelloWorld")
  {
    // Get (expected) single string in tupple.
    Glib::Variant<Glib::ustring> param;
    parameters.get_child(param);

    const Glib::ustring response = "You said: '" + param.get() + "'.";

    const Glib::Variant<Glib::ustring> answer =
      Glib::Variant<Glib::ustring>::create(response);

    const Glib::VariantContainerBase ret =
      Glib::VariantContainerBase::create_tuple(answer);

    invocation->return_value(ret);

    std::cout << "Client said '" << param.get() << "'." << std::endl;
  }
}

// Create the interface VTable.
static const Gio::DBus::InterfaceVTable
  interface_vtable(sigc::ptr_fun(&on_method_call));

bool on_new_connection(const Glib::RefPtr<Gio::DBus::Connection>& connection)
{
  Glib::RefPtr<Gio::Credentials> credentials =
    connection->get_peer_credentials();

  std::string credentials_str;

  if(!credentials)
    credentials_str = "(no credentials received)";
  else
    credentials_str = credentials->to_string();

  std::cout <<
    "Client connected." << std::endl <<
    "Peer credentials: " << credentials_str << std::endl <<
    "Negotiated capabilities: unix-fd-passing=" << (connection->get_capabilities() & Gio::DBus::CAPABILITY_FLAGS_UNIX_FD_PASSING) << std::endl;

  // If there is already an active connection, do not accept this new one.
  // There may be a better way to decide how to keep current incoming
  // connections.
  if(curr_connection && !curr_connection->is_closed())
  {
    std::cerr << "Unable to accept new incoming connection because one is "
      "already active." << std::endl;

    return false;
  }

  // In order for the connection to stay active the reference to the
  // connection must be kept so store the connection in a global variable.
  curr_connection = connection;

  const guint reg_id = connection->register_object("/org/glibmm/DBus/TestObject",
    introspection_data->lookup_interface("org.glibmm.DBus.TestPeerInterface"),
    interface_vtable);

  if(reg_id == 0)
  {
    std::cerr << "Registration of object for incoming connection not "
      "possible." << std::endl;
    return false;
  }

  return true;
}

void run_as_server(const Glib::ustring& address, bool allow_anonymous)
{
  Glib::ustring guid = Gio::DBus::generate_guid();
  Gio::DBus::ServerFlags flags = Gio::DBus::SERVER_FLAGS_NONE;

  if(allow_anonymous)
    flags |= Gio::DBus::SERVER_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS;

  Glib::RefPtr<Gio::DBus::Server> server;

  try
  {
    server = Gio::DBus::Server::create_sync(address, guid, flags);
  }
  catch(const Glib::Error& ex)
  {
    std::cerr << "Error creating server at address: " << address <<
      ": " << ex.what() << "." << std::endl;
    return;
  }

  server->start();

  std::cout << "Server is listening at: " << server->get_client_address() <<
    "." << std::endl;

  server->signal_new_connection().connect(sigc::ptr_fun(&on_new_connection));

  Glib::RefPtr<Glib::MainLoop> loop = Glib::MainLoop::create();
  loop->run();
}

void run_as_client(const Glib::ustring& address)
{
  Glib::RefPtr<Gio::DBus::Connection> connection;

  try
  {
    connection = Gio::DBus::Connection::create_for_address_sync(address,
      Gio::DBus::CONNECTION_FLAGS_AUTHENTICATION_CLIENT);
  }
  catch(const Glib::Error& ex)
  {
    std::cerr << "Error connecting to D-Bus address " << address << ": " <<
      ex.what() << "." << std::endl;
    return;
  }

  std::cout << "Connected. " << std::endl <<
    "Negotiated capabilities: unix-fd-passing=" <<
    static_cast<bool>(connection->get_capabilities() & Gio::DBus::CAPABILITY_FLAGS_UNIX_FD_PASSING) << "." << std::endl;

  // Get the current time to send as a greeting when calling a server's method.
  Glib::TimeVal time;
  time.assign_current_time();

  // Create the single string tuple parameter for the method call.

  Glib::ustring greeting("Hello, it's: "  + time.as_iso8601() + '.');

  const Glib::Variant<Glib::ustring> param =
    Glib::Variant<Glib::ustring>::create(greeting);

  const Glib::VariantContainerBase parameters =
    Glib::VariantContainerBase::create_tuple(param);

  try
  {
    const Glib::VariantContainerBase result =
      connection->call_sync( "/org/glibmm/DBus/TestObject",
      "org.glibmm.DBus.TestPeerInterface",
      "HelloWorld", parameters);

    Glib::Variant<Glib::ustring> child;
    result.get_child(child);

    std::cout << "The server said: " << child.get() << "." << std::endl;

    connection->close_sync();
  }
  catch(const Glib::Error& ex)
  {
    std::cerr << "Error communicating with the server: " << ex.what() <<
      "." << std::endl;
    return;
  }
}

int main(int argc, char** argv)
{
  std::locale::global(std::locale(""));
  Gio::init();

  bool opt_server = false;
  char* opt_address = 0;
  bool opt_allow_anonymous = false;

  static const GOptionEntry opt_entries[] =
  {
    { "server", 's', 0, G_OPTION_ARG_NONE, &opt_server, "Start a server instead of a client", NULL },
      { "address", 'a', 0, G_OPTION_ARG_STRING, &opt_address, "D-Bus address to use", NULL },
      { "allow-anonymous", 'n', 0, G_OPTION_ARG_NONE, &opt_allow_anonymous, "Allow anonymous authentication", NULL },
      { 0, '\0', 0, G_OPTION_ARG_NONE, 0, 0, 0 }
  };

  Glib::OptionContext opt_context("DBus peer-to-peer example");
  g_option_context_add_main_entries(opt_context.gobj(), opt_entries, 0);

  try
  {
    if(!opt_context.parse(argc, argv))
    {
      std::cerr << "Error parsing options and initializing.  Sorry." <<
        std::endl;
      return 1;
    }
  }
  catch(const Glib::OptionError& ex)
  {
    std::cerr << "Error parsing options: " << ex.what() << std::endl;
    return 1;
  }

  if(!opt_address)
  {
    std::cerr << "Incorrect usage, try the --help options." << std::endl;
    return 1;
  }

  if(!opt_server && opt_allow_anonymous)
  {
    std::cerr << "The --allow-anonymous option is only valid with the "
      "--server option." << std::endl;
    return 1;
  }

  try
  {
    introspection_data = Gio::DBus::NodeInfo::create_for_xml(introspection_xml);
  }
  catch(const Glib::Error& ex)
  {
    std::cerr << "Unable to create introspection data: " << ex.what() <<
      "." << std::endl;
    return 1;
  }

  if(opt_server)
    run_as_server(opt_address, opt_allow_anonymous);
  else
    run_as_client(opt_address);

  return 0;
}