device: renew dhcp leases on awake for software devices
[NetworkManager.git] / src / nm-bus-manager.c
1 /* -*- Mode: C; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- */
2 /* NetworkManager -- Network link manager
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation; either version 2 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License along
15  * with this program; if not, write to the Free Software Foundation, Inc.,
16  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
17  *
18  * Copyright (C) 2006 - 2013 Red Hat, Inc.
19  * Copyright (C) 2006 - 2008 Novell, Inc.
20  */
21
22 #include "nm-default.h"
23
24 #include <unistd.h>
25 #include <sys/stat.h>
26 #include <sys/types.h>
27 #include <errno.h>
28 #include <string.h>
29
30 #include "nm-dbus-interface.h"
31 #include "nm-bus-manager.h"
32 #include "nm-core-internal.h"
33 #include "nm-dbus-compat.h"
34 #include "nm-exported-object.h"
35 #include "NetworkManagerUtils.h"
36
37 #define _NMLOG_DOMAIN       LOGD_CORE
38 #define _NMLOG_PREFIX_NAME  "bus-manager"
39 #define _NMLOG(level, ...) \
40     G_STMT_START { \
41         nm_log ((level), _NMLOG_DOMAIN, \
42                 "%s" _NM_UTILS_MACRO_FIRST(__VA_ARGS__), \
43                 _NMLOG_PREFIX_NAME": " \
44                 _NM_UTILS_MACRO_REST(__VA_ARGS__)); \
45     } G_STMT_END
46
47 enum {
48         DBUS_CONNECTION_CHANGED = 0,
49         PRIVATE_CONNECTION_NEW,
50         PRIVATE_CONNECTION_DISCONNECTED,
51         NUMBER_OF_SIGNALS
52 };
53
54 static guint signals[NUMBER_OF_SIGNALS];
55
56 G_DEFINE_TYPE(NMBusManager, nm_bus_manager, G_TYPE_OBJECT)
57
58 #define NM_BUS_MANAGER_GET_PRIVATE(o) (G_TYPE_INSTANCE_GET_PRIVATE ((o), \
59                                         NM_TYPE_BUS_MANAGER, \
60                                         NMBusManagerPrivate))
61
62 typedef struct _PrivateServer PrivateServer;
63
64 typedef struct {
65         GDBusConnection *connection;
66         GDBusObjectManagerServer *obj_manager;
67         gboolean started;
68
69         GSList *private_servers;
70
71         GDBusProxy *proxy;
72
73         gulong bus_closed_id;
74         guint reconnect_id;
75 } NMBusManagerPrivate;
76
77 static gboolean nm_bus_manager_init_bus (NMBusManager *self);
78 static void nm_bus_manager_cleanup (NMBusManager *self);
79 static void start_reconnection_timeout (NMBusManager *self);
80
81 /* The base path for our GDBusObjectManagerServers.  They do not contain
82  * "NetworkManager" because GDBusObjectManagerServer requires that all
83  * exported objects be *below* the base path, and eg the Manager object
84  * is the base path already.
85  */
86 #define OBJECT_MANAGER_SERVER_BASE_PATH "/org/freedesktop"
87
88 NM_DEFINE_SINGLETON_REGISTER (NMBusManager);
89
90 NMBusManager *
91 nm_bus_manager_get (void)
92 {
93         if (G_UNLIKELY (!singleton_instance)) {
94                 nm_bus_manager_setup (g_object_new (NM_TYPE_BUS_MANAGER, NULL));
95                 if (!nm_bus_manager_init_bus (singleton_instance))
96                         start_reconnection_timeout (singleton_instance);
97         }
98         return singleton_instance;
99 }
100
101 void
102 nm_bus_manager_setup (NMBusManager *instance)
103 {
104         static char already_setup = FALSE;
105
106         g_assert (NM_IS_BUS_MANAGER (instance));
107         g_assert (!already_setup);
108         g_assert (!singleton_instance);
109
110         already_setup = TRUE;
111         singleton_instance = instance;
112         nm_singleton_instance_register ();
113         _LOGD ("setup %s singleton (%p)", "NMBusManager", singleton_instance);
114 }
115
116 /**************************************************************/
117
118 struct _PrivateServer {
119         const char *tag;
120         GQuark detail;
121         char *address;
122         GDBusServer *server;
123
124         /* With peer bus connections, we'll get a new connection for each
125          * client.  For each connection we create an ObjectManager for
126          * that connection to handle exporting our objects.  This table
127          * maps GDBusObjectManager :: 'fake sender'.
128          *
129          * Note that even for connections that don't export any objects
130          * we'll still create GDBusObjectManager since that's where we store
131          * the pointer to the GDBusConnection.
132          */
133         GHashTable *obj_managers;
134
135         NMBusManager *manager;
136 };
137
138 typedef struct {
139         GDBusConnection *connection;
140         PrivateServer *server;
141         gboolean remote_peer_vanished;
142 } CloseConnectionInfo;
143
144 static gboolean
145 close_connection_in_idle (gpointer user_data)
146 {
147         CloseConnectionInfo *info = user_data;
148         PrivateServer *server = info->server;
149         GHashTableIter iter;
150         GDBusObjectManagerServer *manager;
151
152         /* Emit this for the manager */
153         g_signal_emit (server->manager,
154                        signals[PRIVATE_CONNECTION_DISCONNECTED],
155                        server->detail,
156                        info->connection);
157
158         /* FIXME: there's a bug (754730) in GLib for which the connection
159          * is marked as closed when the remote peer vanishes but its
160          * resources are not cleaned up.  Work around it by explicitly
161          * closing the connection in that case. */
162         if (info->remote_peer_vanished)
163                 g_dbus_connection_close (info->connection, NULL, NULL, NULL);
164
165         g_hash_table_iter_init (&iter, server->obj_managers);
166         while (g_hash_table_iter_next (&iter, (gpointer) &manager, NULL)) {
167                 if (g_dbus_object_manager_server_get_connection (manager) == info->connection) {
168                         g_hash_table_iter_remove (&iter);
169                         break;
170                 }
171         }
172
173         g_object_unref (server->manager);
174         g_slice_free (CloseConnectionInfo, info);
175
176         return G_SOURCE_REMOVE;
177 }
178
179 static void
180 private_server_closed_connection (GDBusConnection *conn,
181                                   gboolean remote_peer_vanished,
182                                   GError *error,
183                                   gpointer user_data)
184 {
185         PrivateServer *s = user_data;
186         CloseConnectionInfo *info;
187
188         /* Clean up after the connection */
189         _LOGD ("(%s) closed connection %p on private socket", s->tag, conn);
190
191         info = g_slice_new0 (CloseConnectionInfo);
192         info->connection = conn;
193         info->server = s;
194         info->remote_peer_vanished = remote_peer_vanished;
195
196         g_object_ref (s->manager);
197
198         /* Delay the close of connection to ensure that D-Bus signals
199          * are handled */
200         g_idle_add (close_connection_in_idle, info);
201 }
202
203 static gboolean
204 private_server_new_connection (GDBusServer *server,
205                                GDBusConnection *conn,
206                                gpointer user_data)
207 {
208         PrivateServer *s = user_data;
209         static guint32 counter = 0;
210         GDBusObjectManagerServer *manager;
211         char *sender;
212
213         g_signal_connect (conn, "closed", G_CALLBACK (private_server_closed_connection), s);
214
215         /* Fake a sender since private connections don't have one */
216         sender = g_strdup_printf ("x:y:%d", counter++);
217
218         manager = g_dbus_object_manager_server_new (OBJECT_MANAGER_SERVER_BASE_PATH);
219         g_dbus_object_manager_server_set_connection (manager, conn);
220         g_hash_table_insert (s->obj_managers, manager, sender);
221
222         _LOGD ("(%s) accepted connection %p on private socket", s->tag, conn);
223
224         /* Emit this for the manager */
225         g_signal_emit (s->manager,
226                        signals[PRIVATE_CONNECTION_NEW],
227                        s->detail,
228                        conn,
229                        manager);
230         return TRUE;
231 }
232
233 static void
234 private_server_manager_destroy (GDBusObjectManagerServer *manager)
235 {
236         GDBusConnection *connection = g_dbus_object_manager_server_get_connection (manager);
237
238         if (!g_dbus_connection_is_closed (connection))
239                 g_dbus_connection_close (connection, NULL, NULL, NULL);
240         g_dbus_object_manager_server_set_connection (manager, NULL);
241         g_object_unref (manager);
242 }
243
244 static gboolean
245 private_server_authorize (GDBusAuthObserver *observer,
246                           GIOStream         *stream,
247                           GCredentials      *credentials,
248                           gpointer           user_data)
249 {
250         return g_credentials_get_unix_user (credentials, NULL) == 0;
251 }
252
253 static PrivateServer *
254 private_server_new (const char *path,
255                     const char *tag,
256                     NMBusManager *manager)
257 {
258         PrivateServer *s;
259         GDBusAuthObserver *auth_observer;
260         GDBusServer *server;
261         GError *error = NULL;
262         char *address, *guid;
263
264         unlink (path);
265         address = g_strdup_printf ("unix:path=%s", path);
266
267         _LOGD ("(%s) creating private socket %s", tag, address);
268
269         guid = g_dbus_generate_guid ();
270         auth_observer = g_dbus_auth_observer_new ();
271         g_signal_connect (auth_observer, "authorize-authenticated-peer",
272                           G_CALLBACK (private_server_authorize), NULL);
273         server = g_dbus_server_new_sync (address,
274                                          G_DBUS_SERVER_FLAGS_NONE,
275                                          guid,
276                                          auth_observer,
277                                          NULL, &error);
278         g_free (guid);
279         g_object_unref (auth_observer);
280
281         if (!server) {
282                 _LOGW ("(%s) failed to set up private socket %s: %s",
283                        tag, address, error->message);
284                 g_error_free (error);
285                 g_free (address);
286                 return NULL;
287         }
288
289         s = g_malloc0 (sizeof (*s));
290         s->address = address;
291         s->server = server;
292         g_signal_connect (server, "new-connection",
293                           G_CALLBACK (private_server_new_connection), s);
294
295         s->obj_managers = g_hash_table_new_full (g_direct_hash, g_direct_equal,
296                                                  (GDestroyNotify) private_server_manager_destroy,
297                                                  g_free);
298         s->manager = manager;
299         s->detail = g_quark_from_string (tag);
300         s->tag = g_quark_to_string (s->detail);
301
302         g_dbus_server_start (server);
303
304         return s;
305 }
306
307 static void
308 private_server_free (gpointer ptr)
309 {
310         PrivateServer *s = ptr;
311
312         unlink (s->address);
313         g_free (s->address);
314         g_hash_table_destroy (s->obj_managers);
315
316         g_dbus_server_stop (s->server);
317         g_object_unref (s->server);
318
319         memset (s, 0, sizeof (*s));
320         g_free (s);
321 }
322
323 void
324 nm_bus_manager_private_server_register (NMBusManager *self,
325                                         const char *path,
326                                         const char *tag)
327 {
328         NMBusManagerPrivate *priv = NM_BUS_MANAGER_GET_PRIVATE (self);
329         PrivateServer *s;
330         GSList *iter;
331
332         g_return_if_fail (self != NULL);
333         g_return_if_fail (path != NULL);
334         g_return_if_fail (tag != NULL);
335
336         /* Only one instance per tag; but don't warn */
337         for (iter = priv->private_servers; iter; iter = g_slist_next (iter)) {
338                 s = iter->data;
339                 if (g_strcmp0 (tag, s->tag) == 0)
340                         return;
341         }
342
343         s = private_server_new (path, tag, self);
344         if (s)
345                 priv->private_servers = g_slist_append (priv->private_servers, s);
346 }
347
348 static const char *
349 private_server_get_connection_owner (PrivateServer *s, GDBusConnection *connection)
350 {
351         GHashTableIter iter;
352         GDBusObjectManagerServer *manager;
353         const char *owner;
354
355         g_return_val_if_fail (s != NULL, NULL);
356         g_return_val_if_fail (connection != NULL, NULL);
357
358         g_hash_table_iter_init (&iter, s->obj_managers);
359         while (g_hash_table_iter_next (&iter, (gpointer) &manager, (gpointer) &owner)) {
360                 if (g_dbus_object_manager_server_get_connection (manager) == connection)
361                         return owner;
362         }
363         return NULL;
364 }
365
366 static GDBusConnection *
367 private_server_get_connection_by_owner (PrivateServer *s, const char *owner)
368 {
369         GHashTableIter iter;
370         GDBusObjectManagerServer *manager;
371         const char *priv_sender;
372
373         g_hash_table_iter_init (&iter, s->obj_managers);
374         while (g_hash_table_iter_next (&iter, (gpointer) &manager, (gpointer) &priv_sender)) {
375                 if (g_strcmp0 (owner, priv_sender) == 0)
376                         return g_dbus_object_manager_server_get_connection (manager);
377         }
378         return NULL;
379 }
380
381 /**************************************************************/
382
383 static gboolean
384 _bus_get_unix_pid (NMBusManager *self,
385                    const char *sender,
386                    gulong *out_pid,
387                    GError **error)
388 {
389         guint32 unix_pid = G_MAXUINT32;
390         gs_unref_variant GVariant *ret = NULL;
391
392         ret = _nm_dbus_proxy_call_sync (NM_BUS_MANAGER_GET_PRIVATE (self)->proxy,
393                                         "GetConnectionUnixProcessID",
394                                         g_variant_new ("(s)", sender),
395                                         G_VARIANT_TYPE ("(u)"),
396                                         G_DBUS_CALL_FLAGS_NONE, 2000,
397                                         NULL, error);
398         if (!ret)
399                 return FALSE;
400
401         g_variant_get (ret, "(u)", &unix_pid);
402
403         *out_pid = (gulong) unix_pid;
404         return TRUE;
405 }
406
407 static gboolean
408 _bus_get_unix_user (NMBusManager *self,
409                     const char *sender,
410                     gulong *out_user,
411                     GError **error)
412 {
413         guint32 unix_uid = G_MAXUINT32;
414         gs_unref_variant GVariant *ret = NULL;
415
416         ret = _nm_dbus_proxy_call_sync (NM_BUS_MANAGER_GET_PRIVATE (self)->proxy,
417                                         "GetConnectionUnixUser",
418                                         g_variant_new ("(s)", sender),
419                                         G_VARIANT_TYPE ("(u)"),
420                                         G_DBUS_CALL_FLAGS_NONE, 2000,
421                                         NULL, error);
422         if (!ret)
423                 return FALSE;
424
425         g_variant_get (ret, "(u)", &unix_uid);
426
427         *out_user = (gulong) unix_uid;
428         return TRUE;
429 }
430
431 /**
432  * _get_caller_info():
433  *
434  * Given a GDBus method invocation, or a GDBusConnection + GDBusMessage,
435  * return the sender and the UID of the sender.
436  */
437 static gboolean
438 _get_caller_info (NMBusManager *self,
439                   GDBusMethodInvocation *context,
440                   GDBusConnection *connection,
441                   GDBusMessage *message,
442                   char **out_sender,
443                   gulong *out_uid,
444                   gulong *out_pid)
445 {
446         NMBusManagerPrivate *priv = NM_BUS_MANAGER_GET_PRIVATE (self);
447         const char *sender;
448         GSList *iter;
449
450         if (context) {
451                 connection = g_dbus_method_invocation_get_connection (context);
452
453                 /* only bus connections will have a sender */
454                 sender = g_dbus_method_invocation_get_sender (context);
455         } else {
456                 g_assert (message);
457                 sender = g_dbus_message_get_sender (message);
458         }
459         g_assert (connection);
460
461         if (!sender) {
462                 /* Might be a private connection, for which we fake a sender */
463                 for (iter = priv->private_servers; iter; iter = g_slist_next (iter)) {
464                         PrivateServer *s = iter->data;
465
466                         sender = private_server_get_connection_owner (s, connection);
467                         if (sender) {
468                                 if (out_uid)
469                                         *out_uid = 0;
470                                 if (out_sender)
471                                         *out_sender = g_strdup (sender);
472                                 if (out_pid) {
473                                         GCredentials *creds;
474
475                                         creds = g_dbus_connection_get_peer_credentials (connection);
476                                         if (creds) {
477                                                 pid_t pid;
478
479                                                 pid = g_credentials_get_unix_pid (creds, NULL);
480                                                 if (pid == -1)
481                                                         *out_pid = G_MAXULONG;
482                                                 else
483                                                         *out_pid = pid;
484                                         } else
485                                                 *out_pid = G_MAXULONG;
486                                 }
487                                 return TRUE;
488                         }
489                 }
490                 return FALSE;
491         }
492
493         /* Bus connections always have a sender */
494         g_assert (sender);
495         if (out_uid) {
496                 if (!_bus_get_unix_user (self, sender, out_uid, NULL)) {
497                         *out_uid = G_MAXULONG;
498                         return FALSE;
499                 }
500         }
501
502         if (out_pid) {
503                 if (!_bus_get_unix_pid (self, sender, out_pid, NULL)) {
504                         *out_pid = G_MAXULONG;
505                         return FALSE;
506                 }
507         }
508
509         if (out_sender)
510                 *out_sender = g_strdup (sender);
511
512         return TRUE;
513 }
514
515 gboolean
516 nm_bus_manager_get_caller_info (NMBusManager *self,
517                                 GDBusMethodInvocation *context,
518                                 char **out_sender,
519                                 gulong *out_uid,
520                                 gulong *out_pid)
521 {
522         return _get_caller_info (self, context, NULL, NULL, out_sender, out_uid, out_pid);
523 }
524
525 gboolean
526 nm_bus_manager_get_caller_info_from_message (NMBusManager *self,
527                                              GDBusConnection *connection,
528                                              GDBusMessage *message,
529                                              char **out_sender,
530                                              gulong *out_uid,
531                                              gulong *out_pid)
532 {
533         return _get_caller_info (self, NULL, connection, message, out_sender, out_uid, out_pid);
534 }
535
536 gboolean
537 nm_bus_manager_get_unix_user (NMBusManager *self,
538                               const char *sender,
539                               gulong *out_uid)
540 {
541         NMBusManagerPrivate *priv = NM_BUS_MANAGER_GET_PRIVATE (self);
542         GSList *iter;
543         GError *error = NULL;
544
545         g_return_val_if_fail (sender != NULL, FALSE);
546         g_return_val_if_fail (out_uid != NULL, FALSE);
547
548         /* Check if it's a private connection sender, which we fake */
549         for (iter = priv->private_servers; iter; iter = iter->next) {
550                 if (private_server_get_connection_by_owner (iter->data, sender)) {
551                         *out_uid = 0;
552                         return TRUE;
553                 }
554         }
555
556         /* Otherwise, a bus connection */
557         if (!_bus_get_unix_user (self, sender, out_uid, &error)) {
558                 _LOGW ("failed to get unix user for dbus sender '%s': %s",
559                        sender, error->message);
560                 g_error_free (error);
561                 return FALSE;
562         }
563
564         return TRUE;
565 }
566
567 /**************************************************************/
568
569 static void
570 nm_bus_manager_init (NMBusManager *self)
571 {
572         NMBusManagerPrivate *priv = NM_BUS_MANAGER_GET_PRIVATE (self);
573
574         priv->obj_manager = g_dbus_object_manager_server_new (OBJECT_MANAGER_SERVER_BASE_PATH);
575 }
576
577 static void
578 nm_bus_manager_dispose (GObject *object)
579 {
580         NMBusManager *self = NM_BUS_MANAGER (object);
581         NMBusManagerPrivate *priv = NM_BUS_MANAGER_GET_PRIVATE (self);
582         GList *exported, *iter;
583
584         g_slist_free_full (priv->private_servers, private_server_free);
585         priv->private_servers = NULL;
586
587         nm_bus_manager_cleanup (self);
588
589         if (priv->obj_manager) {
590                 /* The ObjectManager owns the last reference to many exported
591                  * objects, and when that reference is dropped the objects unregister
592                  * themselves via nm_bus_manager_unregister_object().  By that time
593                  * priv->obj_manager is already NULL and that prints warnings.  Unregister
594                  * them before clearing the ObjectManager instead.
595                  */
596                 exported = g_dbus_object_manager_get_objects ((GDBusObjectManager *) priv->obj_manager);
597                 for (iter = exported; iter; iter = iter->next) {
598                         nm_bus_manager_unregister_object (self, iter->data);
599                         g_object_unref (iter->data);
600                 }
601                 g_list_free (exported);
602                 g_clear_object (&priv->obj_manager);
603         }
604
605         nm_clear_g_source (&priv->reconnect_id);
606
607         G_OBJECT_CLASS (nm_bus_manager_parent_class)->dispose (object);
608 }
609
610 static void
611 nm_bus_manager_class_init (NMBusManagerClass *klass)
612 {
613         GObjectClass *object_class = G_OBJECT_CLASS (klass);
614
615         g_type_class_add_private (klass, sizeof (NMBusManagerPrivate));
616
617         object_class->dispose = nm_bus_manager_dispose;
618
619         signals[DBUS_CONNECTION_CHANGED] =
620                 g_signal_new (NM_BUS_MANAGER_DBUS_CONNECTION_CHANGED,
621                               G_OBJECT_CLASS_TYPE (object_class),
622                               G_SIGNAL_RUN_LAST,
623                               G_STRUCT_OFFSET (NMBusManagerClass, dbus_connection_changed),
624                               NULL, NULL, NULL,
625                               G_TYPE_NONE, 1, G_TYPE_POINTER);
626
627         signals[PRIVATE_CONNECTION_NEW] =
628                 g_signal_new (NM_BUS_MANAGER_PRIVATE_CONNECTION_NEW,
629                               G_OBJECT_CLASS_TYPE (object_class),
630                               G_SIGNAL_RUN_LAST | G_SIGNAL_DETAILED,
631                               0, NULL, NULL, NULL,
632                               G_TYPE_NONE, 2, G_TYPE_DBUS_CONNECTION, G_TYPE_DBUS_OBJECT_MANAGER_SERVER);
633
634         signals[PRIVATE_CONNECTION_DISCONNECTED] =
635                 g_signal_new (NM_BUS_MANAGER_PRIVATE_CONNECTION_DISCONNECTED,
636                               G_OBJECT_CLASS_TYPE (object_class),
637                               G_SIGNAL_RUN_LAST | G_SIGNAL_DETAILED,
638                               G_STRUCT_OFFSET (NMBusManagerClass, private_connection_disconnected),
639                               NULL, NULL, NULL,
640                               G_TYPE_NONE, 1, G_TYPE_POINTER);
641 }
642
643
644 /* Only cleanup a specific dbus connection, not all our private data */
645 static void
646 nm_bus_manager_cleanup (NMBusManager *self)
647 {
648         NMBusManagerPrivate *priv = NM_BUS_MANAGER_GET_PRIVATE (self);
649
650         g_clear_object (&priv->proxy);
651
652         if (priv->connection) {
653                 g_signal_handler_disconnect (priv->connection, priv->bus_closed_id);
654                 priv->bus_closed_id = 0;
655                 g_clear_object (&priv->connection);
656         }
657
658         g_dbus_object_manager_server_set_connection (priv->obj_manager, NULL);
659         priv->started = FALSE;
660 }
661
662 static gboolean
663 nm_bus_manager_reconnect (gpointer user_data)
664 {
665         NMBusManager *self = NM_BUS_MANAGER (user_data);
666         NMBusManagerPrivate *priv = NM_BUS_MANAGER_GET_PRIVATE (self);
667
668         g_assert (self != NULL);
669
670         if (nm_bus_manager_init_bus (self)) {
671                 if (nm_bus_manager_start_service (self)) {
672                         _LOGI ("reconnected to the system bus");
673                         g_signal_emit (self, signals[DBUS_CONNECTION_CHANGED],
674                                        0, priv->connection);
675                         priv->reconnect_id = 0;
676                         return FALSE;
677                 }
678         }
679
680         /* Try again */
681         nm_bus_manager_cleanup (self);
682         return TRUE;
683 }
684
685 static void
686 start_reconnection_timeout (NMBusManager *self)
687 {
688         NMBusManagerPrivate *priv = NM_BUS_MANAGER_GET_PRIVATE (self);
689
690         if (priv->reconnect_id)
691                 g_source_remove (priv->reconnect_id);
692
693         /* Schedule timeout for reconnection attempts */
694         priv->reconnect_id = g_timeout_add_seconds (3, nm_bus_manager_reconnect, self);
695 }
696
697 static void
698 closed_cb (GDBusConnection *connection,
699            gboolean remote_peer_vanished,
700            GError *error,
701            gpointer user_data)
702 {
703         NMBusManager *self = NM_BUS_MANAGER (user_data);
704
705         /* Clean up existing connection */
706         _LOGW ("disconnected by the system bus");
707
708         nm_bus_manager_cleanup (self);
709
710         g_signal_emit (G_OBJECT (self), signals[DBUS_CONNECTION_CHANGED], 0, NULL);
711
712         start_reconnection_timeout (self);
713 }
714
715 static gboolean
716 nm_bus_manager_init_bus (NMBusManager *self)
717 {
718         NMBusManagerPrivate *priv = NM_BUS_MANAGER_GET_PRIVATE (self);
719         GError *error = NULL;
720
721         if (priv->connection) {
722                 _LOGW ("DBus Manager already has a valid connection");
723                 return FALSE;
724         }
725
726         priv->connection = g_bus_get_sync (G_BUS_TYPE_SYSTEM, NULL, &error);
727         if (!priv->connection) {
728                 /* Log with 'info' severity; there won't be a bus daemon in minimal
729                  * environments (eg, initrd) where we only want to use the private
730                  * socket.
731                  */
732                 _LOGI ("could not connect to the system bus (%s); only the "
733                        "private D-Bus socket will be available",
734                        error->message);
735                 g_error_free (error);
736                 return FALSE;
737         }
738
739         g_dbus_connection_set_exit_on_close (priv->connection, FALSE);
740         priv->bus_closed_id = g_signal_connect (priv->connection, "closed",
741                                                 G_CALLBACK (closed_cb), self);
742
743         priv->proxy = g_dbus_proxy_new_sync (priv->connection,
744                                              G_DBUS_PROXY_FLAGS_DO_NOT_LOAD_PROPERTIES |
745                                                  G_DBUS_PROXY_FLAGS_DO_NOT_CONNECT_SIGNALS,
746                                              NULL,
747                                              DBUS_SERVICE_DBUS,
748                                              DBUS_PATH_DBUS,
749                                              DBUS_INTERFACE_DBUS,
750                                              NULL, &error);
751         if (!priv->proxy) {
752                 g_clear_object (&priv->connection);
753                 _LOGW ("could not create org.freedesktop.DBus proxy (%s); only the "
754                        "private D-Bus socket will be available",
755                        error->message);
756                 g_error_free (error);
757                 return FALSE;
758         }
759
760         g_dbus_object_manager_server_set_connection (priv->obj_manager, priv->connection);
761         return TRUE;
762 }
763
764 /* Register our service on the bus; shouldn't be called until
765  * all necessary message handlers have been registered, because
766  * when we register on the bus, clients may start to call.
767  */
768 gboolean
769 nm_bus_manager_start_service (NMBusManager *self)
770 {
771         NMBusManagerPrivate *priv;
772         gs_unref_variant GVariant *ret = NULL;
773         int result;
774         GError *err = NULL;
775
776         g_return_val_if_fail (NM_IS_BUS_MANAGER (self), FALSE);
777
778         priv = NM_BUS_MANAGER_GET_PRIVATE (self);
779
780         if (priv->started) {
781                 _LOGE ("service has already started");
782                 return FALSE;
783         }
784
785         /* Pointless to request a name when we aren't connected to the bus */
786         if (!priv->proxy)
787                 return FALSE;
788
789         ret = _nm_dbus_proxy_call_sync (priv->proxy,
790                                         "RequestName",
791                                         g_variant_new ("(su)",
792                                                        NM_DBUS_SERVICE,
793                                                        DBUS_NAME_FLAG_DO_NOT_QUEUE),
794                                         G_VARIANT_TYPE ("(u)"),
795                                         G_DBUS_CALL_FLAGS_NONE, -1,
796                                         NULL, &err);
797         if (!ret) {
798                 _LOGE ("could not acquire the NetworkManager service: '%s'", err->message);
799                 g_error_free (err);
800                 return FALSE;
801         }
802
803         g_variant_get (ret, "(u)", &result);
804
805         if (result != DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER) {
806                 _LOGE ("could not acquire the NetworkManager service as it is already taken");
807                 return FALSE;
808         }
809
810         priv->started = TRUE;
811         return priv->started;
812 }
813
814 GDBusConnection *
815 nm_bus_manager_get_connection (NMBusManager *self)
816 {
817         g_return_val_if_fail (NM_IS_BUS_MANAGER (self), NULL);
818
819         return NM_BUS_MANAGER_GET_PRIVATE (self)->connection;
820 }
821
822 void
823 nm_bus_manager_register_object (NMBusManager *self,
824                                 GDBusObjectSkeleton *object)
825 {
826         NMBusManagerPrivate *priv;
827
828         g_return_if_fail (NM_IS_BUS_MANAGER (self));
829         g_return_if_fail (NM_IS_EXPORTED_OBJECT (object));
830
831         priv = NM_BUS_MANAGER_GET_PRIVATE (self);
832
833 #if NM_MORE_ASSERTS >= 1
834 #if GLIB_CHECK_VERSION(2,34,0)
835         if (g_dbus_object_manager_server_is_exported (priv->obj_manager, object))
836                 g_return_if_reached ();
837 #endif
838 #endif
839
840         g_dbus_object_manager_server_export (priv->obj_manager, object);
841 }
842
843 GDBusObjectSkeleton *
844 nm_bus_manager_get_registered_object (NMBusManager *self,
845                                       const char *path)
846 {
847         NMBusManagerPrivate *priv = NM_BUS_MANAGER_GET_PRIVATE (self);
848
849         return G_DBUS_OBJECT_SKELETON (g_dbus_object_manager_get_object ((GDBusObjectManager *) priv->obj_manager, path));
850 }
851
852 void
853 nm_bus_manager_unregister_object (NMBusManager *self,
854                                   GDBusObjectSkeleton *object)
855 {
856         NMBusManagerPrivate *priv;
857         gs_free char *path = NULL;
858
859         g_return_if_fail (NM_IS_BUS_MANAGER (self));
860         g_return_if_fail (NM_IS_EXPORTED_OBJECT (object));
861
862         priv = NM_BUS_MANAGER_GET_PRIVATE (self);
863
864 #if NM_MORE_ASSERTS >= 1
865 #if GLIB_CHECK_VERSION(2,34,0)
866         if (!g_dbus_object_manager_server_is_exported (priv->obj_manager, object))
867                 g_return_if_reached ();
868 #endif
869 #endif
870
871         g_object_get (G_OBJECT (object), "g-object-path", &path, NULL);
872         g_return_if_fail (path != NULL);
873
874         g_dbus_object_manager_server_unexport (priv->obj_manager, path);
875 }
876
877 const char *
878 nm_bus_manager_connection_get_private_name (NMBusManager *self,
879                                             GDBusConnection *connection)
880 {
881         NMBusManagerPrivate *priv;
882         GSList *iter;
883         const char *owner;
884
885         g_return_val_if_fail (NM_IS_BUS_MANAGER (self), FALSE);
886         g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
887
888         if (g_dbus_connection_get_unique_name (connection)) {
889                 /* Shortcut. The connection is not a private connection. */
890                 return NULL;
891         }
892
893         priv = NM_BUS_MANAGER_GET_PRIVATE (self);
894         for (iter = priv->private_servers; iter; iter = g_slist_next (iter)) {
895                 PrivateServer *s = iter->data;
896
897                 if ((owner = private_server_get_connection_owner (s, connection)))
898                         return owner;
899         }
900         g_return_val_if_reached (NULL);
901 }
902
903 /**
904  * nm_bus_manager_new_proxy:
905  * @self: the #NMBusManager
906  * @connection: the GDBusConnection for which this connection should be created
907  * @proxy_type: the type of #GDBusProxy to create
908  * @name: any name on the message bus
909  * @path: name of the object instance to call methods on
910  * @iface: name of the interface to call methods on
911  *
912  * Creates a new proxy (of type @proxy_type) for a name on a given bus.  Since
913  * the process which called the D-Bus method could be coming from a private
914  * connection or the system bus connection, different proxies must be created
915  * for each case.  This function abstracts that.
916  *
917  * Returns: a #GDBusProxy capable of calling D-Bus methods of the calling process
918  */
919 GDBusProxy *
920 nm_bus_manager_new_proxy (NMBusManager *self,
921                           GDBusConnection *connection,
922                           GType proxy_type,
923                           const char *name,
924                           const char *path,
925                           const char *iface)
926 {
927         const char *owner;
928         GDBusProxy *proxy;
929         GError *error = NULL;
930
931         g_return_val_if_fail (g_type_is_a (proxy_type, G_TYPE_DBUS_PROXY), NULL);
932         g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
933
934         /* Might be a private connection, for which @name is fake */
935         owner = nm_bus_manager_connection_get_private_name (self, connection);
936         if (owner) {
937                 g_return_val_if_fail (!g_strcmp0 (owner, name), NULL);
938                 name = NULL;
939         }
940
941         proxy = g_initable_new (proxy_type, NULL, &error,
942                                 "g-connection", connection,
943                                 "g-flags", (G_DBUS_PROXY_FLAGS_DO_NOT_LOAD_PROPERTIES |
944                                             G_DBUS_PROXY_FLAGS_DO_NOT_CONNECT_SIGNALS),
945                                 "g-name", name,
946                                 "g-object-path", path,
947                                 "g-interface-name", iface,
948                                 NULL);
949         if (!proxy) {
950                 _LOGW ("could not create proxy for %s on connection %s: %s",
951                        iface, name, error->message);
952                 g_error_free (error);
953         }
954         return proxy;
955 }