summaryrefslogtreecommitdiff
path: root/callouts/nm-dispatcher-action.c
blob: a919122132e666d9e64900bd2dd76adcb414683f (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
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- */
/* NetworkManager -- Network link manager
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * 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 Street, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Copyright (C) 2008 Red Hat, Inc.
 */

#include <syslog.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <signal.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <errno.h>
#include <arpa/inet.h>

#include <glib.h>
#include <dbus/dbus.h>
#include <dbus/dbus-glib-lowlevel.h>
#include <dbus/dbus-glib.h>

#include <NetworkManager.h>
#include "nm-glib-compat.h"
#include <libnm-util/nm-connection.h>
#include <libnm-util/nm-setting-ip4-config.h>
#include <libnm-util/nm-setting-connection.h>
#include <libnm-glib/nm-dhcp4-config.h>
#include <libnm-glib/nm-device.h>

#include "nm-dispatcher-action.h"

#define NMD_SCRIPT_DIR    SYSCONFDIR "/NetworkManager/dispatcher.d"

static GMainLoop *loop = NULL;
static gboolean debug = FALSE;

static gboolean quit_timeout_cb (gpointer user_data);

typedef struct Handler Handler;
typedef struct HandlerClass HandlerClass;

GType handler_get_type (void);

struct Handler {
	GObject parent;
};

struct HandlerClass {
  GObjectClass parent;
};

#define HANDLER_TYPE              (handler_get_type ())
#define HANDLER(object)           (G_TYPE_CHECK_INSTANCE_CAST ((object), HANDLER_TYPE, Handler))
#define HANDLER_CLASS(klass)      (G_TYPE_CHECK_CLASS_CAST ((klass), HANDLER_TYPE, HandlerClass))
#define IS_HANDLER(object)        (G_TYPE_CHECK_INSTANCE_TYPE ((object), HANDLER_TYPE))
#define IS_HANDLER_CLASS(klass)   (G_TYPE_CHECK_CLASS_TYPE ((klass), HANDLER_TYPE))
#define HANDLER_GET_CLASS(obj)    (G_TYPE_INSTANCE_GET_CLASS ((obj), HANDLER_TYPE, HandlerClass))

G_DEFINE_TYPE(Handler, handler, G_TYPE_OBJECT)

typedef struct {
	DBusGConnection *g_connection;
	DBusGProxy *bus_proxy;
	guint quit_timeout;
	gboolean persist;

	Handler *handler;
} Dispatcher;

static gboolean
nm_dispatcher_action (Handler *obj,
                      const char *action,
                      GHashTable *connection,
                      GHashTable *connection_props,
                      GHashTable *device_props,
                      GError **error);

#include "nm-dispatcher-glue.h"


static void
handler_init (Handler *h)
{
}

static void
handler_finalize (GObject *object)
{
	G_OBJECT_CLASS (handler_parent_class)->finalize (object);
}

static void
handler_class_init (HandlerClass *h_class)
{
  GObjectClass *gobject_class = G_OBJECT_CLASS (h_class);

  gobject_class->finalize = handler_finalize;
}

/*
 * nmd_permission_check
 *
 * Verify that the given script has the permissions we want.  Specifically,
 * ensure that the file is
 *	- A regular file.
 *	- Owned by root.
 *	- Not writable by the group or by other.
 *	- Not setuid.
 *	- Executable by the owner.
 *
 */
static inline gboolean
nmd_permission_check (struct stat *s, GError **error)
{
	g_return_val_if_fail (s != NULL, FALSE);
	g_return_val_if_fail (error != NULL, FALSE);
	g_return_val_if_fail (*error == NULL, FALSE);

	/* Only accept regular files */
	if (!S_ISREG (s->st_mode)) {
		g_set_error (error, 0, 0, "not a regular file.");
		return FALSE;
	}

	/* Only accept files owned by root */
	if (s->st_uid != 0) {
		g_set_error (error, 0, 0, "not owned by root.");
		return FALSE;
	}

	/* Only accept files not writable by group or other, and not SUID */
	if (s->st_mode & (S_IWGRP | S_IWOTH | S_ISUID)) {
		g_set_error (error, 0, 0, "writable by group or other, or set-UID.");
		return FALSE;
	}

	/* Only accept files executable by the owner */
	if (!(s->st_mode & S_IXUSR)) {
		g_set_error (error, 0, 0, "not executable by owner.");
		return FALSE;
	}

	return TRUE;
}


/*
 * nmd_is_valid_filename
 *
 * Verify that the given script is a valid file name. Specifically,
 * ensure that the file:
 *	- is not a editor backup file
 *	- is not a package management file
 *	- does not start with '.'
 */
static inline gboolean
nmd_is_valid_filename (const char *file_name)
{
	char *bad_suffixes[] = { "~", ".rpmsave", ".rpmorig", ".rpmnew", NULL };
	char *tmp;
	int i;

	if (file_name[0] == '.')
		return FALSE;
	for (i = 0; bad_suffixes[i]; i++) {
		if (g_str_has_suffix(file_name, bad_suffixes[i]))
			return FALSE;
	}
	tmp = g_strrstr(file_name, ".dpkg-");
	if (tmp && (tmp == strrchr(file_name,'.')))
		return FALSE;
	return TRUE;
}

static gint
sort_files (gconstpointer a, gconstpointer b)
{
	char *a_base = NULL, *b_base = NULL;
	int ret = 0;

	if (a && !b)
		return 1;
	if (!a && !b)
		return 0;
	if (!a && b)
		return -1;

	a_base = g_path_get_basename (a);
	b_base = g_path_get_basename (b);

	ret = strcmp (a_base, b_base);

	g_free (a_base);
	g_free (b_base);
	return ret;
}

static void
child_setup (gpointer user_data G_GNUC_UNUSED)
{
        /* We are in the child process at this point */
		/* Give child a different process group to ensure signal separation. */
        pid_t pid = getpid ();
        setpgid (pid, pid);
}

typedef struct {
	char **envp;
	guint32 i;
} EnvAddInfo;

static void
add_one_option_to_envp (gpointer key, gpointer value, gpointer user_data)
{
	EnvAddInfo *info = (EnvAddInfo *) user_data;
	char *ucased;

	ucased = g_ascii_strup (key, -1);
	info->envp[info->i++] = g_strdup_printf ("DHCP4_%s=%s", ucased, (char *) value);
	g_free (ucased);
}

static char **
construct_envp (const char *uuid,
                const char *id,
                NMIP4Config *ip4_config,
                NMDHCP4Config *dhcp4_config)
{
	guint32 env_size = 0;
	char **envp;
	guint32 envp_idx = 0;
	GHashTable *options = NULL;
	GSList *addresses, *routes, *iter;
	GArray *nameservers;
	GPtrArray *domains;
	guint32 num, i;
	GString *tmp;

	if (!ip4_config)
		return g_new0 (char *, 1);

	addresses = (GSList *) nm_ip4_config_get_addresses (ip4_config);
	nameservers = (GArray *) nm_ip4_config_get_nameservers (ip4_config);
	domains = (GPtrArray *) nm_ip4_config_get_domains (ip4_config);
	routes = (GSList *) nm_ip4_config_get_routes (ip4_config);

	env_size =   g_slist_length (addresses)
	           + 1 /* addresses length */
	           + 1 /* nameservers */
	           + 1 /* domains */
	           + 1 /* hostname */
	           + g_slist_length (routes)
	           + 1 /* routes length */
	           + 1 /* connection UUID */
	           + 1 /* connection ID */;

	if (dhcp4_config) {
		options = nm_dhcp4_config_get_options (dhcp4_config);
		env_size += g_hash_table_size (options);
	}

	envp = g_new0 (char *, env_size + 1);

	if (uuid)
		envp[envp_idx++] = g_strdup_printf ("CONNECTION_UUID=%s", uuid);
	if (id)
		envp[envp_idx++] = g_strdup_printf ("CONNECTION_ID=%s", id);

	/* IP4 config stuff */
	for (iter = addresses, num = 0; iter; iter = g_slist_next (iter)) {
		NMIP4Address *addr = (NMIP4Address *) iter->data;
		char str_addr[INET_ADDRSTRLEN + 1];
		char str_gw[INET_ADDRSTRLEN + 1];
		struct in_addr tmp_addr;
		guint32 prefix = nm_ip4_address_get_prefix (addr);

		memset (str_addr, 0, sizeof (str_addr));
		tmp_addr.s_addr = nm_ip4_address_get_address (addr);
		if (!inet_ntop (AF_INET, &tmp_addr, str_addr, sizeof (str_addr)))
			continue;

		memset (str_gw, 0, sizeof (str_gw));
		tmp_addr.s_addr = nm_ip4_address_get_gateway (addr);
		inet_ntop (AF_INET, &tmp_addr, str_gw, sizeof (str_gw));

		tmp = g_string_sized_new (25 + strlen (str_addr) + strlen (str_gw));
		g_string_append_printf (tmp, "IP4_ADDRESS_%d=%s/%d %s", num++, str_addr, prefix, str_gw);
		envp[envp_idx++] = tmp->str;
		g_string_free (tmp, FALSE);
	}
	if (num)
		envp[envp_idx++] = g_strdup_printf ("IP4_NUM_ADDRESSES=%d", num);

	if (nameservers && nameservers->len) {
		gboolean first = TRUE;

		tmp = g_string_new ("IP4_NAMESERVERS=");
		for (i = 0; i < nameservers->len; i++) {
			struct in_addr addr;
			char buf[INET_ADDRSTRLEN + 1];

			addr.s_addr = g_array_index (nameservers, guint32, i);
			memset (buf, 0, sizeof (buf));
			if (inet_ntop (AF_INET, &addr, buf, sizeof (buf))) {
				if (!first)
					g_string_append_c (tmp, ' ');
				g_string_append (tmp, buf);
				first = FALSE;
			}
		}
		envp[envp_idx++] = tmp->str;
		g_string_free (tmp, FALSE);
	}

	if (domains && domains->len) {
		tmp = g_string_new ("IP4_DOMAINS=");
		for (i = 0; i < domains->len; i++) {
			if (i > 0)
				g_string_append_c (tmp, ' ');
			g_string_append (tmp, (char *) g_ptr_array_index (domains, i));
		}
		envp[envp_idx++] = tmp->str;
		g_string_free (tmp, FALSE);
	}

	for (iter = routes, num = 0; iter; iter = g_slist_next (iter)) {
		NMIP4Route *route = (NMIP4Route *) iter->data;
		char str_addr[INET_ADDRSTRLEN + 1];
		char str_nh[INET_ADDRSTRLEN + 1];
		struct in_addr tmp_addr;
		guint32 prefix = nm_ip4_route_get_prefix (route);
		guint32 metric = nm_ip4_route_get_metric (route);

		memset (str_addr, 0, sizeof (str_addr));
		tmp_addr.s_addr = nm_ip4_route_get_dest (route);
		if (!inet_ntop (AF_INET, &tmp_addr, str_addr, sizeof (str_addr)))
			continue;

		memset (str_nh, 0, sizeof (str_nh));
		tmp_addr.s_addr = nm_ip4_route_get_next_hop (route);
		inet_ntop (AF_INET, &tmp_addr, str_nh, sizeof (str_nh));

		tmp = g_string_sized_new (30 + strlen (str_addr) + strlen (str_nh));
		g_string_append_printf (tmp, "IP4_ROUTE_%d=%s/%d %s %d", num++, str_addr, prefix, str_nh, metric);
		envp[envp_idx++] = tmp->str;
		g_string_free (tmp, FALSE);
	}
	envp[envp_idx++] = g_strdup_printf ("IP4_NUM_ROUTES=%d", num);

	/* DHCP stuff */
	if (dhcp4_config && options) {
		EnvAddInfo info;

		info.envp = envp;
		info.i = envp_idx;
		g_hash_table_foreach (options, add_one_option_to_envp, &info);
	}

	if (debug) {
		char **p;

		g_message ("------------ Script Environment ------------");
		for (p = envp; *p; p++)
			g_message ("  %s", *p);
		g_message ("\n");
	}

	return envp;
}

static void
dispatch_scripts (const char *action,
                  const char *iface,
                  const char *parent_iface,
                  NMDeviceType type,
                  const char *uuid,
                  const char *id,
                  NMIP4Config *ip4_config,
                  NMDHCP4Config *dhcp4_config)
{
	GDir *dir;
	const char *filename;
	GSList *scripts = NULL, *iter;
	GError *error = NULL;
	char **envp = NULL;

	if (!(dir = g_dir_open (NMD_SCRIPT_DIR, 0, &error))) {
		g_warning ("g_dir_open() could not open '" NMD_SCRIPT_DIR "'.  '%s'",
		           error->message);
		g_error_free (error);
		return;
	}

	while ((filename = g_dir_read_name (dir))) {
		char *file_path;
		struct stat	s;
		GError *pc_error = NULL;
		int err;

		if (!nmd_is_valid_filename (filename))
			continue;

		file_path = g_build_filename (NMD_SCRIPT_DIR, filename, NULL);

		err = stat (file_path, &s);
		if (err) {
			g_warning ("Script '%s' could not be stated: %d", file_path, err);
			g_free (file_path);
			continue;
		}

		if (!nmd_permission_check (&s, &pc_error)) {
			g_warning ("Script '%s' could not be executed: %s", file_path, pc_error->message);
			g_error_free (pc_error);
			g_free (file_path);
		} else {
			/* success */
			scripts = g_slist_insert_sorted (scripts, file_path, sort_files);
		}
	}
	g_dir_close (dir);

	envp = construct_envp (uuid, id, ip4_config, dhcp4_config);

	for (iter = scripts; iter; iter = g_slist_next (iter)) {
		gchar *argv[4];
		gint status = -1;

		argv[0] = (char *) iter->data;
		argv[1] = iface ? (char *) iface : "none";
		argv[2] = (char *) action;
		argv[3] = NULL;

		if (debug)
			g_message ("Script: %s %s %s", (char *) iter->data, iface ? (char *) iface : "(none)", (char *) action);

		error = NULL;
		if (g_spawn_sync ("/", argv, envp, 0, child_setup, NULL, NULL, NULL, &status, &error)) {
			if (WIFEXITED (status)) {
				if (WEXITSTATUS (status) != 0)
					g_warning ("Script '%s' exited with error status %d.",
					           (char *) iter->data, WEXITSTATUS (status));
			} else
				g_warning ("Script '%s' exited abnormally.", (char *) iter->data);
		} else {
			g_warning ("Could not run script '%s': (%d) %s",
			           (char *) iter->data, error->code, error->message);
			g_error_free (error);
		}
	}

	g_strfreev (envp);

	g_slist_foreach (scripts, (GFunc) g_free, NULL);
	g_slist_free (scripts);
}

static gboolean
nm_dispatcher_action (Handler *h,
                      const char *action,
                      GHashTable *connection_hash,
                      GHashTable *connection_props,
                      GHashTable *device_props,
                      GError **error)
{
	Dispatcher *d = g_object_get_data (G_OBJECT (h), "dispatcher");
	NMConnection *connection;
	char *iface = NULL, *parent_iface = NULL;
	const char *uuid = NULL, *id = NULL;
	NMDeviceType type = NM_DEVICE_TYPE_UNKNOWN;
	NMDeviceState dev_state = NM_DEVICE_STATE_UNKNOWN;
	NMDevice *device = NULL;
	NMDHCP4Config *dhcp4_config = NULL;
	NMIP4Config *ip4_config = NULL;
	GValue *value;

	/* Back off the quit timeout */
	if (d->quit_timeout)
		g_source_remove (d->quit_timeout);
	if (!d->persist)
		d->quit_timeout = g_timeout_add_seconds (10, quit_timeout_cb, NULL);

	/* Hostname changes don't require a device nor contain a connection */
	if (!strcmp (action, "hostname"))
		goto dispatch;

	connection = nm_connection_new_from_hash (connection_hash, error);
	if (connection) {
		uuid = nm_connection_get_uuid (connection);
		id = nm_connection_get_id (connection);
	} else {
		g_warning ("%s: Invalid connection: '%s' / '%s' invalid: %d",
		           __func__,
		           g_type_name (nm_connection_lookup_setting_type_by_quark ((*error)->domain)),
		           (*error)->message, (*error)->code);
		/* Don't fail on this error yet */
		g_error_free (*error);
		*error = NULL;
	}

	/* interface name */
	value = g_hash_table_lookup (device_props, NMD_DEVICE_PROPS_INTERFACE);
	if (!value || !G_VALUE_HOLDS_STRING (value)) {
		g_warning ("Missing or invalid required value " NMD_DEVICE_PROPS_INTERFACE "!");
		goto out;
	}
	iface = (char *) g_value_get_string (value);

	/* IP interface name */
	value = g_hash_table_lookup (device_props, NMD_DEVICE_PROPS_IP_INTERFACE);
	if (value) {
		if (!G_VALUE_HOLDS_STRING (value)) {
			g_warning ("Invalid required value " NMD_DEVICE_PROPS_IP_INTERFACE "!");
			goto out;
		}
		parent_iface = iface;
		iface = (char *) g_value_get_string (value);
	}

	/* Device type */
	value = g_hash_table_lookup (device_props, NMD_DEVICE_PROPS_TYPE);
	if (!value || !G_VALUE_HOLDS_UINT (value)) {
		g_warning ("Missing or invalid required value " NMD_DEVICE_PROPS_TYPE "!");
		goto out;
	}
	type = g_value_get_uint (value);

	/* Device state */
	value = g_hash_table_lookup (device_props, NMD_DEVICE_PROPS_STATE);
	if (!value || !G_VALUE_HOLDS_UINT (value)) {
		g_warning ("Missing or invalid required value " NMD_DEVICE_PROPS_STATE "!");
		goto out;
	}
	dev_state = g_value_get_uint (value);

	/* device itself */
	value = g_hash_table_lookup (device_props, NMD_DEVICE_PROPS_PATH);
	if (!value || (G_VALUE_TYPE (value) != DBUS_TYPE_G_OBJECT_PATH)) {
		g_warning ("Missing or invalid required value " NMD_DEVICE_PROPS_PATH "!");
		goto out;
	}
	device = NM_DEVICE (nm_device_new (d->g_connection, (const char *) g_value_get_boxed (value)));

	/* Get the DHCP4 config */
	if (device && (dev_state == NM_DEVICE_STATE_ACTIVATED)) {
		dhcp4_config = nm_device_get_dhcp4_config (device);
		ip4_config = nm_device_get_ip4_config (device);
	}

dispatch:
	dispatch_scripts (action, iface, parent_iface, type, uuid, id, ip4_config, dhcp4_config);

	if (device)
		g_object_unref (device);

out:
	return TRUE;
}

static gboolean
start_dbus_service (Dispatcher *d)
{
	int request_name_result;
	GError *err = NULL;
	gboolean success = FALSE;

	if (!dbus_g_proxy_call (d->bus_proxy, "RequestName", &err,
							G_TYPE_STRING, NM_DISPATCHER_DBUS_SERVICE,
							G_TYPE_UINT, DBUS_NAME_FLAG_DO_NOT_QUEUE,
							G_TYPE_INVALID,
							G_TYPE_UINT, &request_name_result,
							G_TYPE_INVALID)) {
		g_warning ("Could not acquire the " NM_DISPATCHER_DBUS_SERVICE " service.\n"
		           "  Message: '%s'", err->message);
		g_error_free (err);
		goto out;
	}

	if (request_name_result != DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER) {
		g_warning ("Could not acquire the " NM_DISPATCHER_DBUS_SERVICE " service "
		           "as it is already taken.  Return: %d",
		           request_name_result);
		goto out;
	}
	success = TRUE;

out:
	return success;
}

static void
destroy_cb (DBusGProxy *proxy, gpointer user_data)
{
	g_warning ("Disconnected from the system bus, exiting.");
	g_main_loop_quit (loop);
}

static gboolean
dbus_init (Dispatcher *d)
{
	GError *err = NULL;
	DBusConnection *connection;
	
	dbus_connection_set_change_sigpipe (TRUE);

	d->g_connection = dbus_g_bus_get (DBUS_BUS_SYSTEM, &err);
	if (!d->g_connection) {
		g_warning ("Could not get the system bus.  Make sure "
		           "the message bus daemon is running!  Message: %s",
		           err->message);
		g_error_free (err);
		return FALSE;
	}

	/* Clean up nicely if we get kicked off the bus */
	connection = dbus_g_connection_get_connection (d->g_connection);
	dbus_connection_set_exit_on_disconnect (connection, FALSE);

	d->bus_proxy = dbus_g_proxy_new_for_name (d->g_connection,
	                                          "org.freedesktop.DBus",
	                                          "/org/freedesktop/DBus",
	                                          "org.freedesktop.DBus");
	if (!d->bus_proxy) {
		g_warning ("Could not get the DBus object!");
		goto error;
	}

	g_signal_connect (d->bus_proxy, "destroy", G_CALLBACK (destroy_cb), NULL);

	return TRUE;

error:	
	return FALSE;
}

static void
log_handler (const gchar *log_domain,
             GLogLevelFlags log_level,
             const gchar *message,
             gpointer ignored)
{
	int syslog_priority;	

	switch (log_level) {
		case G_LOG_LEVEL_ERROR:
			syslog_priority = LOG_CRIT;
			break;

		case G_LOG_LEVEL_CRITICAL:
			syslog_priority = LOG_ERR;
			break;

		case G_LOG_LEVEL_WARNING:
			syslog_priority = LOG_WARNING;
			break;

		case G_LOG_LEVEL_MESSAGE:
			syslog_priority = LOG_NOTICE;
			break;

		case G_LOG_LEVEL_DEBUG:
			syslog_priority = LOG_DEBUG;
			break;

		case G_LOG_LEVEL_INFO:
		default:
			syslog_priority = LOG_INFO;
			break;
	}

	syslog (syslog_priority, "%s", message);
}


static void
logging_setup (void)
{
	openlog (G_LOG_DOMAIN, LOG_CONS, LOG_DAEMON);
	g_log_set_handler (G_LOG_DOMAIN, 
	                   G_LOG_LEVEL_MASK | G_LOG_FLAG_FATAL | G_LOG_FLAG_RECURSION,
	                   log_handler,
	                   NULL);
}

static void
logging_shutdown (void)
{
	closelog ();
}

static void
signal_handler (int signo)
{
	if (signo == SIGINT || signo == SIGTERM) {
		g_message ("Caught signal %d, shutting down...", signo);
		g_main_loop_quit (loop);
	}
}

static void
setup_signals (void)
{
	struct sigaction action;
	sigset_t mask;

	sigemptyset (&mask);
	action.sa_handler = signal_handler;
	action.sa_mask = mask;
	action.sa_flags = 0;
	sigaction (SIGTERM,  &action, NULL);
	sigaction (SIGINT,  &action, NULL);
}

static gboolean
quit_timeout_cb (gpointer user_data)
{
	g_main_loop_quit (loop);
	return FALSE;
}

int
main (int argc, char **argv)
{
	Dispatcher *d = g_malloc0 (sizeof (Dispatcher));
	GOptionContext *opt_ctx;
	GError *error = NULL;
	gboolean persist = FALSE;

	GOptionEntry entries[] = {
		{ "debug", 0, 0, G_OPTION_ARG_NONE, &debug, "Output to console rather than syslog", NULL },
		{ "persist", 0, 0, G_OPTION_ARG_NONE, &persist, "Don't quit after a short timeout", NULL },
		{ NULL }
	};

	opt_ctx = g_option_context_new (NULL);
	g_option_context_set_summary (opt_ctx, "Executes scripts upon actions by NetworkManager.");
	g_option_context_add_main_entries (opt_ctx, entries, NULL);

	if (!g_option_context_parse (opt_ctx, &argc, &argv, &error)) {
		g_warning ("%s\n", error->message);
		g_error_free (error);
		g_free (d);
		return 1;
	}

	g_option_context_free (opt_ctx);

	g_type_init ();
	setup_signals ();

	if (!debug)
		logging_setup ();

	loop = g_main_loop_new (NULL, FALSE);

	if (!dbus_init (d))
		return -1;
	if (!start_dbus_service (d))
		return -1;

	d->persist = persist;
	d->handler = g_object_new (HANDLER_TYPE, NULL);
	if (!d->handler)
		return -1;
	g_object_set_data (G_OBJECT (d->handler), "dispatcher", d);

	dbus_g_object_type_install_info (HANDLER_TYPE, &dbus_glib_nm_dispatcher_object_info);
	dbus_g_connection_register_g_object (d->g_connection,
	                                     NM_DISPATCHER_DBUS_PATH,
	                                     G_OBJECT (d->handler));

	if (!persist)
		d->quit_timeout = g_timeout_add_seconds (10, quit_timeout_cb, NULL);

	g_main_loop_run (loop);

	g_object_unref (d->handler);
	dbus_g_connection_unref (d->g_connection);
	g_free (d);

	if (!debug)
		logging_shutdown ();

	return 0;
}