1    	/* -*- Mode: C; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- */
2    	/* This program is free software; you can redistribute it and/or modify
3    	 * it under the terms of the GNU General Public License as published by
4    	 * the Free Software Foundation; either version 2, or (at your option)
5    	 * any later version.
6    	 *
7    	 * This program is distributed in the hope that it will be useful,
8    	 * but WITHOUT ANY WARRANTY; without even the implied warranty of
9    	 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10   	 * GNU General Public License for more details.
11   	 *
12   	 * You should have received a copy of the GNU General Public License along
13   	 * with this program; if not, write to the Free Software Foundation, Inc.,
14   	 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
15   	 *
16   	 * Copyright (C) 2005 - 2010 Red Hat, Inc.
17   	 *
18   	 */
19   	
20   	#include <config.h>
21   	#include <glib.h>
22   	#include <string.h>
23   	#include <sys/types.h>
24   	#include <sys/wait.h>
25   	#include <errno.h>
26   	#include <unistd.h>
27   	#include <stdio.h>
28   	#include <stdlib.h>
29   	#include <uuid/uuid.h>
30   	
31   	#include "nm-utils.h"
32   	#include "nm-logging.h"
33   	#include "nm-dbus-glib-types.h"
34   	#include "nm-dhcp-client.h"
35   	
36   	typedef struct {
37   		char *       iface;
38   		GByteArray * hwaddr;
39   		gboolean     ipv6;
40   		char *       uuid;
41   		guint32      timeout;
42   		GByteArray * duid;
43   	
44   		guchar       state;
45   		GPid         pid;
46   		gboolean     dead;
47   		guint        timeout_id;
48   		guint        watch_id;
49   		guint32      remove_id;
50   		GHashTable * options;
51   		gboolean     info_only;
52   	
53   	} NMDHCPClientPrivate;
54   	
55   	#define NM_DHCP_CLIENT_GET_PRIVATE(o) (G_TYPE_INSTANCE_GET_PRIVATE ((o), NM_TYPE_DHCP_CLIENT, NMDHCPClientPrivate))
56   	
57   	G_DEFINE_TYPE_EXTENDED (NMDHCPClient, nm_dhcp_client, G_TYPE_OBJECT, G_TYPE_FLAG_ABSTRACT, {})
58   	
59   	enum {
60   		STATE_CHANGED,
61   		TIMEOUT,
62   		REMOVE,
63   		LAST_SIGNAL
64   	};
65   	
66   	static guint signals[LAST_SIGNAL] = { 0 };
67   	
68   	enum {
69   		PROP_0,
70   		PROP_IFACE,
71   		PROP_HWADDR,
72   		PROP_IPV6,
73   		PROP_UUID,
74   		PROP_TIMEOUT,
75   		LAST_PROP
76   	};
77   	
78   	/********************************************/
79   	
80   	GPid
81   	nm_dhcp_client_get_pid (NMDHCPClient *self)
82   	{
83   		g_return_val_if_fail (NM_IS_DHCP_CLIENT (self), -1);
84   	
85   		return NM_DHCP_CLIENT_GET_PRIVATE (self)->pid;
86   	}
87   	
88   	const char *
89   	nm_dhcp_client_get_iface (NMDHCPClient *self)
90   	{
91   		g_return_val_if_fail (NM_IS_DHCP_CLIENT (self), NULL);
92   	
93   		return NM_DHCP_CLIENT_GET_PRIVATE (self)->iface;
94   	}
95   	
96   	gboolean
97   	nm_dhcp_client_get_ipv6 (NMDHCPClient *self)
98   	{
99   		g_return_val_if_fail (NM_IS_DHCP_CLIENT (self), FALSE);
100  	
101  		return NM_DHCP_CLIENT_GET_PRIVATE (self)->ipv6;
102  	}
103  	
104  	const char *
105  	nm_dhcp_client_get_uuid (NMDHCPClient *self)
106  	{
107  		g_return_val_if_fail (NM_IS_DHCP_CLIENT (self), NULL);
108  	
109  		return NM_DHCP_CLIENT_GET_PRIVATE (self)->uuid;
110  	}
111  	
112  	/********************************************/
113  	
114  	static void
115  	timeout_cleanup (NMDHCPClient *self)
116  	{
117  		NMDHCPClientPrivate *priv = NM_DHCP_CLIENT_GET_PRIVATE (self);
118  	
119  		if (priv->timeout_id) {
120  			g_source_remove (priv->timeout_id);
121  			priv->timeout_id = 0;
122  		}
123  	}
124  	
125  	static void
126  	watch_cleanup (NMDHCPClient *self)
127  	{
128  		NMDHCPClientPrivate *priv = NM_DHCP_CLIENT_GET_PRIVATE (self);
129  	
130  		if (priv->watch_id) {
131  			g_source_remove (priv->watch_id);
132  			priv->watch_id = 0;
133  		}
134  	}
135  	
136  	void
137  	nm_dhcp_client_stop_pid (GPid pid, const char *iface, guint timeout_secs)
138  	{
139  		int i = (timeout_secs ? timeout_secs : 3) * 5;  /* default 3 seconds */
140  	
141  		g_return_if_fail (pid > 0);
142  	
143  		/* Tell it to quit; maybe it wants to send out a RELEASE message */
144  		kill (pid, SIGTERM);
145  	
146  		while (i-- > 0) {
147  			gint child_status;
148  			int ret;
149  	
150  			ret = waitpid (pid, &child_status, WNOHANG);
151  			if (ret > 0)
152  				break;
153  	
154  			if (ret == -1) {
155  				/* Child already exited */
156  				if (errno == ECHILD) {
157  					/* Was it really our child and it exited? */
158  					if (kill (pid, 0) < 0 && errno == ESRCH)
159  						break;
160  				} else {
161  					/* Took too long; shoot it in the head */
162  					i = 0;
163  					break;
164  				}
165  			}
166  			g_usleep (G_USEC_PER_SEC / 5);
167  		}
168  	
169  		if (i <= 0) {
170  			if (iface) {
171  				nm_log_warn (LOGD_DHCP, "(%s): DHCP client pid %d didn't exit, will kill it.",
172  				             iface, pid);
173  			}
174  			kill (pid, SIGKILL);
175  	
176  			nm_log_dbg (LOGD_DHCP, "waiting for DHCP client pid %d to exit", pid);
177  			waitpid (pid, NULL, 0);
178  			nm_log_dbg (LOGD_DHCP, "DHCP client pid %d cleaned up", pid);
179  		}
180  	}
181  	
182  	static void
183  	stop (NMDHCPClient *self, gboolean release, const GByteArray *duid)
184  	{
185  		NMDHCPClientPrivate *priv;
186  	
187  		g_return_if_fail (NM_IS_DHCP_CLIENT (self));
188  	
189  		priv = NM_DHCP_CLIENT_GET_PRIVATE (self);
190  		g_return_if_fail (priv->pid > 0);
191  	
192  		/* Clean up the watch handler since we're explicitly killing the daemon */
193  		watch_cleanup (self);
194  	
195  		nm_dhcp_client_stop_pid (priv->pid, priv->iface, 0);
196  	
197  		priv->info_only = FALSE;
198  	}
199  	
200  	static gboolean
201  	daemon_timeout (gpointer user_data)
202  	{
203  		NMDHCPClient *self = NM_DHCP_CLIENT (user_data);
204  		NMDHCPClientPrivate *priv = NM_DHCP_CLIENT_GET_PRIVATE (self);
205  	
206  		if (priv->ipv6) {
207  			nm_log_warn (LOGD_DHCP6, "(%s): DHCPv6 request timed out.", priv->iface);
208  		} else {
209  			nm_log_warn (LOGD_DHCP4, "(%s): DHCPv4 request timed out.", priv->iface);
210  		}
211  		g_signal_emit (G_OBJECT (self), signals[TIMEOUT], 0);
212  		return FALSE;
213  	}
214  	
215  	static gboolean
216  	signal_remove (gpointer user_data)
217  	{
218  		NMDHCPClient *self = NM_DHCP_CLIENT (user_data);
219  	
220  		NM_DHCP_CLIENT_GET_PRIVATE (self)->remove_id = 0;
221  		g_signal_emit (G_OBJECT (self), signals[REMOVE], 0);
222  		return FALSE;
223  	}
224  	
225  	static void
226  	dhcp_client_set_state (NMDHCPClient *self,
227  	                       NMDHCPState state,
228  	                       gboolean emit_state,
229  	                       gboolean remove_now)
230  	{
231  		NMDHCPClientPrivate *priv = NM_DHCP_CLIENT_GET_PRIVATE (self);
232  	
233  		priv->state = state;
234  	
235  		if (emit_state)
236  			g_signal_emit (G_OBJECT (self), signals[STATE_CHANGED], 0, priv->state);
237  	
238  		if (state == DHC_END || state == DHC_ABEND) {
239  			/* Start the remove signal timer */
240  			if (remove_now) {
241  				g_signal_emit (G_OBJECT (self), signals[REMOVE], 0);
242  			} else {
243  				if (!priv->remove_id)
244  					priv->remove_id = g_timeout_add_seconds (5, signal_remove, self);
245  			}
246  		}
247  	}
248  	
249  	static void
250  	daemon_watch_cb (GPid pid, gint status, gpointer user_data)
251  	{
252  		NMDHCPClient *self = NM_DHCP_CLIENT (user_data);
253  		NMDHCPClientPrivate *priv = NM_DHCP_CLIENT_GET_PRIVATE (self);
254  		NMDHCPState new_state;
255  	
256  		if (priv->ipv6) {
257  			nm_log_info (LOGD_DHCP6, "(%s): DHCPv6 client pid %d exited with status %d",
258  			             priv->iface, pid,
259  			             WIFEXITED (status) ? WEXITSTATUS (status) : -1);
260  		} else {
261  			nm_log_info (LOGD_DHCP4, "(%s): DHCPv4 client pid %d exited with status %d",
262  			             priv->iface, pid,
263  			             WIFEXITED (status) ? WEXITSTATUS (status) : -1);
264  		}
265  	
266  		if (!WIFEXITED (status)) {
267  			new_state = DHC_ABEND;
268  			nm_log_warn (LOGD_DHCP, "DHCP client died abnormally");
269  		} else
270  			new_state = DHC_END;
271  	
272  		watch_cleanup (self);
273  		timeout_cleanup (self);
274  		priv->dead = TRUE;
275  	
276  		dhcp_client_set_state (self, new_state, TRUE, FALSE);
277  	}
278  	
279  	static void
280  	start_monitor (NMDHCPClient *self)
281  	{
282  		NMDHCPClientPrivate *priv = NM_DHCP_CLIENT_GET_PRIVATE (self);
283  	
284  		g_return_if_fail (priv->pid > 0);
285  	
286  		/* Set up a timeout on the transaction to kill it after the timeout */
287  		priv->timeout_id = g_timeout_add_seconds (priv->timeout,
288  		                                          daemon_timeout,
289  		                                          self);
290  		priv->watch_id = g_child_watch_add (priv->pid,
291  		                                    (GChildWatchFunc) daemon_watch_cb,
292  		                                    self);
293  	}
294  	
295  	gboolean
296  	nm_dhcp_client_start_ip4 (NMDHCPClient *self,
297  	                          NMSettingIP4Config *s_ip4,
298  	                          guint8 *dhcp_anycast_addr,
299  	                          const char *hostname)
300  	{
301  		NMDHCPClientPrivate *priv;
302  	
303  		g_return_val_if_fail (NM_IS_DHCP_CLIENT (self), FALSE);
304  	
305  		priv = NM_DHCP_CLIENT_GET_PRIVATE (self);
306  		g_return_val_if_fail (priv->pid == -1, FALSE);
307  		g_return_val_if_fail (priv->ipv6 == FALSE, FALSE);
308  		g_return_val_if_fail (priv->uuid != NULL, FALSE);
309  	
310  		nm_log_info (LOGD_DHCP, "Activation (%s) Beginning DHCPv4 transaction (timeout in %d seconds)",
311  		             priv->iface, priv->timeout);
312  	
313  		priv->pid = NM_DHCP_CLIENT_GET_CLASS (self)->ip4_start (self, s_ip4, dhcp_anycast_addr, hostname);
314  		if (priv->pid)
315  			start_monitor (self);
316  	
317  		return priv->pid ? TRUE : FALSE;
318  	}
319  	
320  	/* uuid_parse does not work for machine-id, so we use our own converter */
321  	static gboolean
322  	machine_id_parse (const char *in, uuid_t uu)
323  	{
324  		const char *cp;
325  		int i;
326  		char buf[3];
327  	
328  		g_return_val_if_fail (in != NULL, FALSE);
329  		g_return_val_if_fail (strlen (in) == 32, FALSE);
330  	
331  		for (i = 0; i < 32; i++, cp++) {
332  			if (!g_ascii_isxdigit (in[i]))
333  				return FALSE;
334  		}
335  	
336  		buf[2] = 0;
337  		cp = in;
338  		for (i = 0; i < 16; i++) {
339  			buf[0] = *cp++;
340  			buf[1] = *cp++;
341  			uu[i] = ((unsigned char) strtoul (buf, NULL, 16)) & 0xFF;
342  		}
343  		return TRUE;
344  	}
345  	
346  	static GByteArray *
347  	generate_duid_from_machine_id (void)
348  	{
349  		GByteArray *duid;
350  		char *contents = NULL;
351  		GChecksum *sum;
352  		guint8 buffer[32]; /* SHA256 digest size */
353  		gsize sumlen = sizeof (buffer);
354  		const guint16 duid_type = g_htons (4);
355  		uuid_t uuid;
356  		GRand *generator;
357  		guint i;
358  		gboolean success = FALSE;
359  	
360  		/* Get the machine ID from /etc/machine-id; it's always in /etc no matter
361  		 * where our configured SYSCONFDIR is.  Alternatively, it might be in
362  		 * LOCALSTATEDIR /lib/dbus/machine-id.
363  		 */
364  		if (   g_file_get_contents ("/etc/machine-id", &contents, NULL, NULL)
365  		    || g_file_get_contents (LOCALSTATEDIR "/lib/dbus/machine-id", &contents, NULL, NULL)) {
366  			contents = g_strstrip (contents);
367  			success = machine_id_parse (contents, uuid);
368  			if (success) {
369  				/* Hash the machine ID so it's not leaked to the network */
370  				sum = g_checksum_new (G_CHECKSUM_SHA256);
371  				g_checksum_update (sum, (const guchar *) &uuid, sizeof (uuid));
372  				g_checksum_get_digest (sum, buffer, &sumlen);
373  				g_checksum_free (sum);
374  			}
375  			g_free (contents);
376  		}
377  	
378  		if (!success) {
379  			nm_log_warn (LOGD_DHCP6, "Failed to read " SYSCONFDIR "/machine-id "
380  			             "or " LOCALSTATEDIR "/lib/dbus/machine-id to generate "
381  			             "DHCPv6 DUID; creating non-persistent random DUID.");
382  	
383  			generator = g_rand_new ();
384  			for (i = 0; i < sizeof (buffer) / sizeof (guint32); i++)
385  				((guint32 *) buffer)[i] = g_rand_int (generator);
386  			g_rand_free (generator);
387  		}
388  	
389  		/* Generate a DHCP Unique Identifier for DHCPv6 using the
390  		 * DUID-UUID method (see RFC 6355 section 4).  Format is:
391  		 *
392  		 * u16: type (DUID-UUID = 4)
393  		 * u8[16]: UUID bytes
394  		 */
395  		duid = g_byte_array_sized_new (18);
396  		g_byte_array_append (duid, (guint8 *) &duid_type, sizeof (duid_type));
397  	
398  		/* Since SHA256 is 256 bits, but UUID is 128 bits, we just take the first
399  		 * 128 bits of the SHA256 as the DUID-UUID.
400  		 */
401  		g_byte_array_append (duid, buffer, 16);
402  	
403  		return duid;
404  	}
405  	
406  	static char *
407  	escape_duid (const GByteArray *duid)
408  	{
409  		guint32 i = 0;
410  		GString *s;
411  	
412  		g_return_val_if_fail (duid != NULL, NULL);
413  	
414  		s = g_string_sized_new (40);
415  		while (i < duid->len) {
416  			if (s->len)
417  				g_string_append_c (s, ':');
418  			g_string_append_printf (s, "%02x", duid->data[i++]);
419  		}
420  		return g_string_free (s, FALSE);
421  	}
422  	
423  	static GByteArray *
424  	get_duid (NMDHCPClient *self)
425  	{
426  		static GByteArray *duid = NULL;
427  		GByteArray *copy = NULL;
428  		char *escaped;
429  	
430  		if (G_UNLIKELY (duid == NULL)) {
431  			duid = generate_duid_from_machine_id ();
432  			g_assert (duid);
433  	
434  			if (nm_logging_level_enabled (LOGL_DEBUG)) {
435  				escaped = escape_duid (duid);
436  				nm_log_dbg (LOGD_DHCP6, "Generated DUID %s", escaped);
437  				g_free (escaped);
438  			}
439  		}
440  	
441  		if (G_LIKELY (duid)) {
442  			copy = g_byte_array_sized_new (duid->len);
443  			g_byte_array_append (copy, duid->data, duid->len);
444  		}
445  	
446  		return copy;
447  	}
448  	
449  	gboolean
450  	nm_dhcp_client_start_ip6 (NMDHCPClient *self,
451  	                          NMSettingIP6Config *s_ip6,
452  	                          guint8 *dhcp_anycast_addr,
453  	                          const char *hostname,
454  	                          gboolean info_only)
455  	{
456  		NMDHCPClientPrivate *priv;
457  		char *escaped;
458  	
459  		g_return_val_if_fail (NM_IS_DHCP_CLIENT (self), FALSE);
460  	
461  		priv = NM_DHCP_CLIENT_GET_PRIVATE (self);
462  		g_return_val_if_fail (priv->pid == -1, FALSE);
463  		g_return_val_if_fail (priv->ipv6 == TRUE, FALSE);
464  		g_return_val_if_fail (priv->uuid != NULL, FALSE);
465  	
466  		/* If we don't have one yet, read the default DUID for this DHCPv6 client
467  		 * from the client-specific persistent configuration.
468  		 */
469  		if (!priv->duid)
470  			priv->duid = NM_DHCP_CLIENT_GET_CLASS (self)->get_duid (self);
471  	
472  		if (nm_logging_level_enabled (LOGL_DEBUG)) {
473  			escaped = escape_duid (priv->duid);
474  			nm_log_dbg (LOGD_DHCP, "(%s): DHCPv6 DUID is '%s'", priv->iface, escaped);
475  			g_free (escaped);
476  		}
477  	
478  		priv->info_only = info_only;
479  	
480  		nm_log_info (LOGD_DHCP, "Activation (%s) Beginning DHCPv6 transaction (timeout in %d seconds)",
481  		             priv->iface, priv->timeout);
482  	
483  		priv->pid = NM_DHCP_CLIENT_GET_CLASS (self)->ip6_start (self,
484  		                                                        s_ip6,
485  		                                                        dhcp_anycast_addr,
486  		                                                        hostname,
487  		                                                        info_only,
488  		                                                        priv->duid);
489  		if (priv->pid > 0)
490  			start_monitor (self);
491  	
492  		return priv->pid ? TRUE : FALSE;
493  	}
494  	
495  	void
496  	nm_dhcp_client_stop_existing (const char *pid_file, const char *binary_name)
497  	{
498  		char *pid_contents = NULL, *proc_contents = NULL, *proc_path = NULL;
499  		long int tmp;
500  	
501  		/* Check for an existing instance and stop it */
(1) Event cond_false: Condition "!g_file_get_contents(pid_file, &pid_contents, NULL, NULL)", taking false branch
502  		if (!g_file_get_contents (pid_file, &pid_contents, NULL, NULL))
(2) Event if_end: End of if statement
503  			return;
504  	
505  		errno = 0;
506  		tmp = strtol (pid_contents, NULL, 10);
(3) Event cond_true: Condition "*__errno_location() == 0", taking true branch
(4) Event cond_true: Condition "tmp > 1", taking true branch
507  		if ((errno == 0) && (tmp > 1)) {
508  			const char *exe;
509  	
510  			/* Ensure the process is a DHCP client */
511  			proc_path = g_strdup_printf ("/proc/%ld/cmdline", tmp);
(5) Event cond_true: Condition "g_file_get_contents(proc_path, &proc_contents, NULL, NULL)", taking true branch
512  			if (g_file_get_contents (proc_path, &proc_contents, NULL, NULL)) {
513  				exe = strrchr (proc_contents, '/');
(6) Event cond_false: Condition "exe", taking false branch
514  				if (exe)
515  					exe++;
516  				else
(7) Event else_branch: Reached else branch
517  					exe = proc_contents;
518  	
(8) Event cond_true: Condition "!__coverity_strcmp(exe, binary_name)", taking true branch
519  				if (!strcmp (exe, binary_name))
520  					nm_dhcp_client_stop_pid ((GPid) tmp, NULL, 0);
521  			}
522  		}
523  	
(9) Event check_return: Calling function "remove(pid_file)" without checking return value. This library function may fail and return an error code.
(10) Event unchecked_value: No check of the return value of "remove(pid_file)".
524  		remove (pid_file);
525  		g_free (proc_path);
526  		g_free (pid_contents);
527  		g_free (proc_contents);
528  	}
529  	
530  	void
531  	nm_dhcp_client_stop (NMDHCPClient *self, gboolean release)
532  	{
533  		NMDHCPClientPrivate *priv;
534  	
535  		g_return_if_fail (NM_IS_DHCP_CLIENT (self));
536  	
537  		priv = NM_DHCP_CLIENT_GET_PRIVATE (self);
538  	
539  		/* Kill the DHCP client */
540  		if (!priv->dead) {
541  			NM_DHCP_CLIENT_GET_CLASS (self)->stop (self, release, priv->duid);
542  			priv->dead = TRUE;
543  	
544  			nm_log_info (LOGD_DHCP, "(%s): canceled DHCP transaction, DHCP client pid %d",
545  			             priv->iface, priv->pid);
546  		}
547  	
548  		/* And clean stuff up */
549  	
550  		priv->pid = -1;
551  		dhcp_client_set_state (self, DHC_END, FALSE, TRUE);
552  	
553  		g_hash_table_remove_all (priv->options);
554  	
555  		timeout_cleanup (self);
556  		watch_cleanup (self);
557  	}
558  	
559  	/********************************************/
560  	
561  	static gboolean
562  	state_is_bound (guint32 state)
563  	{
564  		if (   (state == DHC_BOUND4)
565  		    || (state == DHC_BOUND6)
566  		    || (state == DHC_RENEW4)
567  		    || (state == DHC_RENEW6)
568  		    || (state == DHC_REBOOT)
569  		    || (state == DHC_REBIND4)
570  		    || (state == DHC_REBIND6)
571  		    || (state == DHC_IPV4LL))
572  			return TRUE;
573  	
574  		return FALSE;
575  	}
576  	
577  	typedef struct {
578  		NMDHCPState state;
579  		const char *name;
580  	} DhcState;
581  	
582  	#define STATE_TABLE_SIZE (sizeof (state_table) / sizeof (state_table[0]))
583  	
584  	static DhcState state_table[] = {
585  		{ DHC_NBI,     "nbi" },
586  		{ DHC_PREINIT, "preinit" },
587  		{ DHC_PREINIT6,"preinit6" },
588  		{ DHC_BOUND4,  "bound" },
589  		{ DHC_BOUND6,  "bound6" },
590  		{ DHC_IPV4LL,  "ipv4ll" },
591  		{ DHC_RENEW4,  "renew" },
592  		{ DHC_RENEW6,  "renew6" },
593  		{ DHC_REBOOT,  "reboot" },
594  		{ DHC_REBIND4, "rebind" },
595  		{ DHC_REBIND6, "rebind6" },
596  		{ DHC_STOP,    "stop" },
597  		{ DHC_STOP6,   "stop6" },
598  		{ DHC_MEDIUM,  "medium" },
599  		{ DHC_TIMEOUT, "timeout" },
600  		{ DHC_FAIL,    "fail" },
601  		{ DHC_EXPIRE,  "expire" },
602  		{ DHC_EXPIRE6, "expire6" },
603  		{ DHC_RELEASE, "release" },
604  		{ DHC_RELEASE6,"release6" },
605  		{ DHC_START,   "start" },
606  		{ DHC_ABEND,   "abend" },
607  		{ DHC_END,     "end" },
608  		{ DHC_DEPREF6, "depref6" },
609  	};
610  	
611  	static inline const char *
612  	state_to_string (guint32 state)
613  	{
614  		int i;
615  	
616  		for (i = 0; i < STATE_TABLE_SIZE; i++) {
617  			if (state == state_table[i].state)
618  				return state_table[i].name;
619  		}
620  	
621  		return NULL;
622  	}
623  	
624  	static inline NMDHCPState
625  	string_to_state (const char *name)
626  	{
627  		int i;
628  	
629  		for (i = 0; i < STATE_TABLE_SIZE; i++) {
630  			if (!strcasecmp (name, state_table[i].name))
631  				return state_table[i].state;
632  		}
633  	
634  		return 255;
635  	}
636  	
637  	static char *
638  	garray_to_string (GArray *array, const char *key)
639  	{
640  		GString *str;
641  		int i;
642  		unsigned char c;
643  		char *converted = NULL;
644  	
645  		g_return_val_if_fail (array != NULL, NULL);
646  	
647  		/* Since the DHCP options come through environment variables, they should
648  		 * already be UTF-8 safe, but just make sure.
649  		 */
650  		str = g_string_sized_new (array->len);
651  		for (i = 0; i < array->len; i++) {
652  			c = array->data[i];
653  	
654  			/* Convert NULLs to spaces and non-ASCII characters to ? */
655  			if (c == '\0')
656  				c = ' ';
657  			else if (c > 127)
658  				c = '?';
659  			str = g_string_append_c (str, c);
660  		}
661  		str = g_string_append_c (str, '\0');
662  	
663  		converted = str->str;
664  		if (!g_utf8_validate (converted, -1, NULL))
665  			nm_log_warn (LOGD_DHCP, "DHCP option '%s' couldn't be converted to UTF-8", key);
666  		g_string_free (str, FALSE);
667  		return converted;
668  	}
669  	
670  	static void
671  	copy_option (gpointer key,
672  	             gpointer value,
673  	             gpointer user_data)
674  	{
675  		GHashTable *hash = user_data;
676  		const char *str_key = (const char *) key;
677  		char *str_value = NULL;
678  	
679  		if (G_VALUE_TYPE (value) != DBUS_TYPE_G_UCHAR_ARRAY) {
680  			nm_log_warn (LOGD_DHCP, "unexpected key %s value type was not "
681  			             "DBUS_TYPE_G_UCHAR_ARRAY",
682  			             str_key);
683  			return;
684  		}
685  	
686  		str_value = garray_to_string ((GArray *) g_value_get_boxed (value), str_key);
687  		if (str_value)
688  			g_hash_table_insert (hash, g_strdup (str_key), str_value);
689  	}
690  	
691  	void
692  	nm_dhcp_client_new_options (NMDHCPClient *self,
693  	                            GHashTable *options,
694  	                            const char *reason)
695  	{
696  		NMDHCPClientPrivate *priv;
697  		guint32 old_state;
698  		guint32 new_state;
699  	
700  		g_return_if_fail (NM_IS_DHCP_CLIENT (self));
701  		g_return_if_fail (options != NULL);
702  		g_return_if_fail (reason != NULL);
703  	
704  		priv = NM_DHCP_CLIENT_GET_PRIVATE (self);
705  		old_state = priv->state;
706  		new_state = string_to_state (reason);
707  	
708  		/* Clear old and save new DHCP options */
709  		g_hash_table_remove_all (priv->options);
710  		g_hash_table_foreach (options, copy_option, priv->options);
711  	
712  		if (old_state == new_state) {
713  			/* dhclient will stay in the same state (or, really, provide the same
714  			 * reason) for operations like RENEW and REBIND.  We need to ensure
715  			 * that triggers various DHCP lease change code, so we need to pass
716  			 * along same-state transitions for these states.
717  			 */
718  			if (   new_state != DHC_BOUND4
719  			    && new_state != DHC_RENEW4
720  			    && new_state != DHC_REBIND4
721  			    && new_state != DHC_BOUND6
722  			    && new_state != DHC_RENEW6
723  			    && new_state != DHC_REBIND6)
724  				return;
725  		}
726  	
727  		/* Handle changed device state */
728  		if (state_is_bound (new_state)) {
729  			/* Cancel the timeout if the DHCP client is now bound */
730  			timeout_cleanup (self);
731  		}
732  	
733  		if (priv->ipv6) {
734  			nm_log_info (LOGD_DHCP6, "(%s): DHCPv6 state changed %s -> %s",
735  			            priv->iface,
736  			            state_to_string (old_state),
737  			            state_to_string (new_state));
738  		} else {
739  			nm_log_info (LOGD_DHCP4, "(%s): DHCPv4 state changed %s -> %s",
740  			            priv->iface,
741  			            state_to_string (old_state),
742  			            state_to_string (new_state));
743  		}
744  	
745  		dhcp_client_set_state (self, new_state, TRUE, FALSE);
746  	}
747  	
748  	#define NEW_TAG "new_"
749  	#define OLD_TAG "old_"
750  	
751  	gboolean
752  	nm_dhcp_client_foreach_option (NMDHCPClient *self,
753  	                               GHFunc func,
754  	                               gpointer user_data)
755  	{
756  		NMDHCPClientPrivate *priv;
757  		GHashTableIter iter;
758  		gpointer iterkey, itervalue;
759  	
760  		g_return_val_if_fail (NM_IS_DHCP_CLIENT (self), FALSE);
761  		g_return_val_if_fail (func != NULL, FALSE);
762  	
763  		priv = NM_DHCP_CLIENT_GET_PRIVATE (self);
764  	
765  		if (!state_is_bound (priv->state)) {
766  			if (priv->ipv6) {
767  				nm_log_warn (LOGD_DHCP6, "(%s): DHCPv6 client didn't bind to a lease.", priv->iface);
768  			} else {
769  				nm_log_warn (LOGD_DHCP4, "(%s): DHCPv4 client didn't bind to a lease.", priv->iface);
770  			}
771  		}
772  	
773  		g_hash_table_iter_init (&iter, priv->options);
774  		while (g_hash_table_iter_next (&iter, &iterkey, &itervalue)) {
775  			const char *key = iterkey, *value = itervalue;
776  			const char **p;
777  			static const char *filter_options[] = {
778  				"interface", "pid", "reason", "dhcp_message_type", NULL
779  			};
780  			gboolean ignore = FALSE;
781  	
782  			/* Filter out stuff that's not actually new DHCP options */
783  			for (p = filter_options; *p; p++) {
784  				if (!strcmp (*p, key) || !strncmp (key, OLD_TAG, strlen (OLD_TAG))) {
785  					ignore = TRUE;
786  					break;
787  				}
788  			}
789  	
790  			if (!ignore) {
791  				const char *tmp_key = key;
792  	
793  				/* Remove the "new_" prefix that dhclient passes back */
794  				if (!strncmp (key, NEW_TAG, strlen (NEW_TAG)))
795  					tmp_key = key + strlen (NEW_TAG);
796  	
797  				func ((gpointer) tmp_key, (gpointer) value, user_data);
798  			}
799  		}
800  		return TRUE;
801  	}
802  	
803  	static guint32
804  	get_time (void)
805  	{
806  		struct timespec tp;
807  	
808  		clock_gettime (CLOCK_MONOTONIC, &tp);
809  	
810  		return tp.tv_sec;
811  	}
812  	
813  	/********************************************/
814  	
815  	static gboolean
816  	ip4_process_dhcpcd_rfc3442_routes (const char *str,
817  	                                   NMIP4Config *ip4_config,
818  	                                   guint32 *gwaddr)
819  	{
820  		char **routes, **r;
821  		gboolean have_routes = FALSE;
822  	
823  		routes = g_strsplit (str, " ", 0);
824  		if (g_strv_length (routes) == 0)
825  			goto out;
826  	
827  		if ((g_strv_length (routes) % 2) != 0) {
828  			nm_log_warn (LOGD_DHCP4, "  classless static routes provided, but invalid");
829  			goto out;
830  		}
831  	
832  		for (r = routes; *r; r += 2) {
833  			char *slash;
834  			NMPlatformIP4Route route;
835  			int rt_cidr = 32;
836  			guint32 rt_addr, rt_route;
837  	
838  			slash = strchr(*r, '/');
839  			if (slash) {
840  				*slash = '\0';
841  				errno = 0;
842  				rt_cidr = strtol (slash + 1, NULL, 10);
843  				if ((errno == EINVAL) || (errno == ERANGE)) {
844  					nm_log_warn (LOGD_DHCP4, "DHCP provided invalid classless static route cidr: '%s'", slash + 1);
845  					continue;
846  				}
847  			}
848  			if (inet_pton (AF_INET, *r, &rt_addr) <= 0) {
849  				nm_log_warn (LOGD_DHCP4, "DHCP provided invalid classless static route address: '%s'", *r);
850  				continue;
851  			}
852  			if (inet_pton (AF_INET, *(r + 1), &rt_route) <= 0) {
853  				nm_log_warn (LOGD_DHCP4, "DHCP provided invalid classless static route gateway: '%s'", *(r + 1));
854  				continue;
855  			}
856  	
857  			have_routes = TRUE;
858  			if (rt_cidr == 0 && rt_addr == 0) {
859  				/* FIXME: how to handle multiple routers? */
860  				*gwaddr = rt_route;
861  			} else {
862  				nm_log_info (LOGD_DHCP4, "  classless static route %s/%d gw %s", *r, rt_cidr, *(r + 1));
863  				memset (&route, 0, sizeof (route));
864  				route.network = rt_addr;
865  				route.plen = rt_cidr;
866  				route.gateway = rt_route;
867  				nm_ip4_config_add_route (ip4_config, &route);
868  			}
869  		}
870  	
871  	out:
872  		g_strfreev (routes);
873  		return have_routes;
874  	}
875  	
876  	static const char **
877  	process_dhclient_rfc3442_route (const char **octets, NMPlatformIP4Route *route, gboolean *success)
878  	{
879  		const char **o = octets;
880  		int addr_len = 0, i = 0;
881  		long int tmp;
882  		char *next_hop;
883  		guint32 tmp_addr;
884  	
885  		*success = FALSE;
886  	
887  		if (!*o)
888  			return o; /* no prefix */
889  	
890  		tmp = strtol (*o, NULL, 10);
891  		if (tmp < 0 || tmp > 32)  /* 32 == max IP4 prefix length */
892  			return o;
893  	
894  		memset (route, 0, sizeof (*route));
895  		route->plen = tmp;
896  		o++;
897  	
898  		if (tmp > 0)
899  			addr_len = ((tmp - 1) / 8) + 1;
900  	
901  		/* ensure there's at least the address + next hop left */
902  		if (g_strv_length ((char **) o) < addr_len + 4)
903  			goto error;
904  	
905  		if (tmp) {
906  			const char *addr[4] = { "0", "0", "0", "0" };
907  			char *str_addr;
908  	
909  			for (i = 0; i < addr_len; i++)
910  				addr[i] = *o++;
911  	
912  			str_addr = g_strjoin (".", addr[0], addr[1], addr[2], addr[3], NULL);
913  			if (inet_pton (AF_INET, str_addr, &tmp_addr) <= 0) {
914  				g_free (str_addr);
915  				goto error;
916  			}
917  			tmp_addr &= nm_utils_ip4_prefix_to_netmask ((guint32) tmp);
918  			route->network = tmp_addr;
919  		}
920  	
921  		/* Handle next hop */
922  		next_hop = g_strjoin (".", o[0], o[1], o[2], o[3], NULL);
923  		if (inet_pton (AF_INET, next_hop, &tmp_addr) <= 0) {
924  			g_free (next_hop);
925  			goto error;
926  		}
927  		route->gateway = tmp_addr;
928  		g_free (next_hop);
929  	
930  		*success = TRUE;
931  		return o + 4; /* advance to past the next hop */
932  	
933  	error:
934  		return o;
935  	}
936  	
937  	static gboolean
938  	ip4_process_dhclient_rfc3442_routes (const char *str,
939  	                                     NMIP4Config *ip4_config,
940  	                                     guint32 *gwaddr)
941  	{
942  		char **octets, **o;
943  		gboolean have_routes = FALSE;
944  		NMPlatformIP4Route route;
945  		gboolean success;
946  	
947  		o = octets = g_strsplit_set (str, " .", 0);
948  		if (g_strv_length (octets) < 5) {
949  			nm_log_warn (LOGD_DHCP4, "ignoring invalid classless static routes '%s'", str);
950  			goto out;
951  		}
952  	
953  		while (*o) {
954  			memset (&route, 0, sizeof (route));
955  			o = (char **) process_dhclient_rfc3442_route ((const char **) o, &route, &success);
956  			if (!success) {
957  				nm_log_warn (LOGD_DHCP4, "ignoring invalid classless static routes");
958  				break;
959  			}
960  	
961  			have_routes = TRUE;
962  			if (!route.plen) {
963  				/* gateway passed as classless static route */
964  				*gwaddr = route.gateway;
965  			} else {
966  				char addr[INET_ADDRSTRLEN + 1];
967  				char nh[INET_ADDRSTRLEN + 1];
968  	
969  				/* normal route */
970  				nm_ip4_config_add_route (ip4_config, &route);
971  	
972  				inet_ntop (AF_INET, &route.network, addr, sizeof (addr));
973  				inet_ntop (AF_INET, &route.gateway, nh, sizeof (nh));
974  				nm_log_info (LOGD_DHCP4, "  classless static route %s/%d gw %s",
975  				             addr, route.plen, nh);
976  			}
977  		}
978  	
979  	out:
980  		g_strfreev (octets);
981  		return have_routes;
982  	}
983  	
984  	static gboolean
985  	ip4_process_classless_routes (GHashTable *options,
986  	                              NMIP4Config *ip4_config,
987  	                              guint32 *gwaddr)
988  	{
989  		const char *str, *p;
990  	
991  		g_return_val_if_fail (options != NULL, FALSE);
992  		g_return_val_if_fail (ip4_config != NULL, FALSE);
993  	
994  		*gwaddr = 0;
995  	
996  		/* dhcpd/dhclient in Fedora has support for rfc3442 implemented using a
997  		 * slightly different format:
998  		 *
999  		 * option classless-static-routes = array of (destination-descriptor ip-address);
1000 		 *
1001 		 * which results in:
1002 		 *
1003 		 * 0 192.168.0.113 25.129.210.177.132 192.168.0.113 7.2 10.34.255.6
1004 		 *
1005 		 * dhcpcd supports classless static routes natively and uses this same
1006 		 * option identifier with the following format:
1007 		 *
1008 		 * 192.168.10.0/24 192.168.1.1 10.0.0.0/8 10.17.66.41
1009 		 */
1010 		str = g_hash_table_lookup (options, "new_classless_static_routes");
1011 	
1012 		/* dhclient doesn't have actual support for rfc3442 classless static routes
1013 		 * upstream.  Thus, people resort to defining the option in dhclient.conf
1014 		 * and using arbitrary formats like so:
1015 		 *
1016 		 * option rfc3442-classless-static-routes code 121 = array of unsigned integer 8;
1017 		 *
1018 		 * See https://lists.isc.org/pipermail/dhcp-users/2008-December/007629.html
1019 		 */
1020 		if (!str)
1021 			str = g_hash_table_lookup (options, "new_rfc3442_classless_static_routes");
1022 	
1023 		/* Microsoft version; same as rfc3442 but with a different option # (249) */
1024 		if (!str)
1025 			str = g_hash_table_lookup (options, "new_ms_classless_static_routes");
1026 	
1027 		if (!str || !strlen (str))
1028 			return FALSE;
1029 	
1030 		p = str;
1031 		while (*p) {
1032 			if (!g_ascii_isdigit (*p) && (*p != ' ') && (*p != '.') && (*p != '/')) {
1033 				nm_log_warn (LOGD_DHCP4, "ignoring invalid classless static routes '%s'", str);
1034 				return FALSE;
1035 			}
1036 			p++;
1037 		};
1038 	
1039 		if (strchr (str, '/')) {
1040 			/* dhcpcd format */
1041 			return ip4_process_dhcpcd_rfc3442_routes (str, ip4_config, gwaddr);
1042 		}
1043 	
1044 		return ip4_process_dhclient_rfc3442_routes (str, ip4_config, gwaddr);
1045 	}
1046 	
1047 	static void
1048 	process_classful_routes (GHashTable *options, NMIP4Config *ip4_config)
1049 	{
1050 		const char *str;
1051 		char **searches, **s;
1052 	
1053 		str = g_hash_table_lookup (options, "new_static_routes");
1054 		if (!str)
1055 			return;
1056 	
1057 		searches = g_strsplit (str, " ", 0);
1058 		if ((g_strv_length (searches) % 2)) {
1059 			nm_log_info (LOGD_DHCP, "  static routes provided, but invalid");
1060 			goto out;
1061 		}
1062 	
1063 		for (s = searches; *s; s += 2) {
1064 			NMPlatformIP4Route route;
1065 			guint32 rt_addr, rt_route;
1066 	
1067 			if (inet_pton (AF_INET, *s, &rt_addr) <= 0) {
1068 				nm_log_warn (LOGD_DHCP, "DHCP provided invalid static route address: '%s'", *s);
1069 				continue;
1070 			}
1071 			if (inet_pton (AF_INET, *(s + 1), &rt_route) <= 0) {
1072 				nm_log_warn (LOGD_DHCP, "DHCP provided invalid static route gateway: '%s'", *(s + 1));
1073 				continue;
1074 			}
1075 	
1076 			// FIXME: ensure the IP addresse and route are sane
1077 	
1078 			memset (&route, 0, sizeof (route));
1079 			route.network = rt_addr;
1080 			route.plen = 32;
1081 			route.gateway = rt_route;
1082 	
1083 			nm_ip4_config_add_route (ip4_config, &route);
1084 			nm_log_info (LOGD_DHCP, "  static route %s gw %s", *s, *(s + 1));
1085 		}
1086 	
1087 	out:
1088 		g_strfreev (searches);
1089 	}
1090 	
1091 	static void
1092 	process_domain_search (const char *str, GFunc add_func, gpointer user_data)
1093 	{
1094 		char **searches, **s;
1095 		char *unescaped, *p;
1096 		int i;
1097 	
1098 		g_return_if_fail (str != NULL);
1099 		g_return_if_fail (add_func != NULL);
1100 	
1101 		p = unescaped = g_strdup (str);
1102 		do {
1103 			p = strstr (p, "\\032");
1104 			if (!p)
1105 				break;
1106 	
1107 			/* Clear the escaped space with real spaces */
1108 			for (i = 0; i < 4; i++)
1109 				*p++ = ' ';
1110 		} while (*p++);
1111 	
1112 		if (strchr (unescaped, '\\')) {
1113 			nm_log_warn (LOGD_DHCP, "  invalid domain search: '%s'", unescaped);
1114 			goto out;
1115 		}
1116 	
1117 		searches = g_strsplit (unescaped, " ", 0);
1118 		for (s = searches; *s; s++) {
1119 			if (strlen (*s)) {
1120 				nm_log_info (LOGD_DHCP, "  domain search '%s'", *s);
1121 				add_func (*s, user_data);
1122 			}
1123 		}
1124 		g_strfreev (searches);
1125 	
1126 	out:
1127 		g_free (unescaped);
1128 	}
1129 	
1130 	static void
1131 	ip4_add_domain_search (gpointer data, gpointer user_data)
1132 	{
1133 		nm_ip4_config_add_search (NM_IP4_CONFIG (user_data), (const char *) data);
1134 	}
1135 	
1136 	/* Given a table of DHCP options from the client, convert into an IP4Config */
1137 	static NMIP4Config *
1138 	ip4_options_to_config (NMDHCPClient *self)
1139 	{
1140 		NMDHCPClientPrivate *priv;
1141 		NMIP4Config *ip4_config = NULL;
1142 		guint32 tmp_addr;
1143 		NMPlatformIP4Address address;
1144 		char *str = NULL;
1145 		guint32 gwaddr = 0, plen = 0;
1146 	
1147 		g_return_val_if_fail (NM_IS_DHCP_CLIENT (self), NULL);
1148 	
1149 		priv = NM_DHCP_CLIENT_GET_PRIVATE (self);
1150 		g_return_val_if_fail (priv->options != NULL, NULL);
1151 	
1152 		ip4_config = nm_ip4_config_new ();
1153 		memset (&address, 0, sizeof (address));
1154 		address.timestamp = get_time ();
1155 	
1156 		str = g_hash_table_lookup (priv->options, "new_ip_address");
1157 		if (str && (inet_pton (AF_INET, str, &tmp_addr) > 0)) {
1158 			address.address = tmp_addr;
1159 			nm_log_info (LOGD_DHCP4, "  address %s", str);
1160 		} else
1161 			goto error;
1162 	
1163 		str = g_hash_table_lookup (priv->options, "new_subnet_mask");
1164 		if (str && (inet_pton (AF_INET, str, &tmp_addr) > 0)) {
1165 			plen = nm_utils_ip4_netmask_to_prefix (tmp_addr);
1166 			nm_log_info (LOGD_DHCP4, "  plen %d (%s)", plen, str);
1167 		} else {
1168 			/* Get default netmask for the IP according to appropriate class. */
1169 			plen = nm_utils_ip4_get_default_prefix (address.address);
1170 			nm_log_info (LOGD_DHCP4, "  plen %d (default)", plen);
1171 		}
1172 		address.plen = plen;
1173 	
1174 		/* Routes: if the server returns classless static routes, we MUST ignore
1175 		 * the 'static_routes' option.
1176 		 */
1177 		if (!ip4_process_classless_routes (priv->options, ip4_config, &gwaddr))
1178 			process_classful_routes (priv->options, ip4_config);
1179 	
1180 		if (gwaddr) {
1181 			char buf[INET_ADDRSTRLEN + 1];
1182 	
1183 			inet_ntop (AF_INET, &gwaddr, buf, sizeof (buf));
1184 			nm_log_info (LOGD_DHCP4, "  gateway %s", buf);
1185 			nm_ip4_config_set_gateway (ip4_config, gwaddr);
1186 		} else {
1187 			/* If the gateway wasn't provided as a classless static route with a
1188 			 * subnet length of 0, try to find it using the old-style 'routers' option.
1189 			 */
1190 			str = g_hash_table_lookup (priv->options, "new_routers");
1191 			if (str) {
1192 				char **routers = g_strsplit (str, " ", 0);
1193 				char **s;
1194 	
1195 				for (s = routers; *s; s++) {
1196 					/* FIXME: how to handle multiple routers? */
1197 					if (inet_pton (AF_INET, *s, &tmp_addr) > 0) {
1198 						nm_ip4_config_set_gateway (ip4_config, tmp_addr);
1199 						nm_log_info (LOGD_DHCP4, "  gateway %s", *s);
1200 						break;
1201 					} else
1202 						nm_log_warn (LOGD_DHCP4, "ignoring invalid gateway '%s'", *s);
1203 				}
1204 				g_strfreev (routers);
1205 			}
1206 		}
1207 	
1208 		str = g_hash_table_lookup (priv->options, "new_dhcp_lease_time");
1209 		if (str) {
1210 			address.lifetime = address.preferred = strtoul (str, NULL, 10);
1211 			nm_log_info (LOGD_DHCP4, "  lease time %d", address.lifetime);
1212 		}
1213 	
1214 		nm_ip4_config_add_address (ip4_config, &address);
1215 	
1216 		str = g_hash_table_lookup (priv->options, "new_host_name");
1217 		if (str)
1218 			nm_log_info (LOGD_DHCP4, "  hostname '%s'", str);
1219 	
1220 		str = g_hash_table_lookup (priv->options, "new_domain_name_servers");
1221 		if (str) {
1222 			char **searches = g_strsplit (str, " ", 0);
1223 			char **s;
1224 	
1225 			for (s = searches; *s; s++) {
1226 				if (inet_pton (AF_INET, *s, &tmp_addr) > 0) {
1227 					nm_ip4_config_add_nameserver (ip4_config, tmp_addr);
1228 					nm_log_info (LOGD_DHCP4, "  nameserver '%s'", *s);
1229 				} else
1230 					nm_log_warn (LOGD_DHCP4, "ignoring invalid nameserver '%s'", *s);
1231 			}
1232 			g_strfreev (searches);
1233 		}
1234 	
1235 		str = g_hash_table_lookup (priv->options, "new_domain_name");
1236 		if (str) {
1237 			char **domains = g_strsplit (str, " ", 0);
1238 			char **s;
1239 	
1240 			for (s = domains; *s; s++) {
1241 				nm_log_info (LOGD_DHCP4, "  domain name '%s'", *s);
1242 				nm_ip4_config_add_domain (ip4_config, *s);
1243 			}
1244 			g_strfreev (domains);
1245 		}
1246 	
1247 		str = g_hash_table_lookup (priv->options, "new_domain_search");
1248 		if (str)
1249 			process_domain_search (str, ip4_add_domain_search, ip4_config);
1250 	
1251 		str = g_hash_table_lookup (priv->options, "new_netbios_name_servers");
1252 		if (str) {
1253 			char **searches = g_strsplit (str, " ", 0);
1254 			char **s;
1255 	
1256 			for (s = searches; *s; s++) {
1257 				if (inet_pton (AF_INET, *s, &tmp_addr) > 0) {
1258 					nm_ip4_config_add_wins (ip4_config, tmp_addr);
1259 					nm_log_info (LOGD_DHCP4, "  wins '%s'", *s);
1260 				} else
1261 					nm_log_warn (LOGD_DHCP4, "ignoring invalid WINS server '%s'", *s);
1262 			}
1263 			g_strfreev (searches);
1264 		}
1265 	
1266 		str = g_hash_table_lookup (priv->options, "new_interface_mtu");
1267 		if (str) {
1268 			int int_mtu;
1269 	
1270 			errno = 0;
1271 			int_mtu = strtol (str, NULL, 10);
1272 			if ((errno == EINVAL) || (errno == ERANGE))
1273 				goto error;
1274 	
1275 			if (int_mtu > 576)
1276 				nm_ip4_config_set_mtu (ip4_config, int_mtu);
1277 		}
1278 	
1279 		str = g_hash_table_lookup (priv->options, "new_nis_domain");
1280 		if (str) {
1281 			nm_log_info (LOGD_DHCP4, "  NIS domain '%s'", str);
1282 			nm_ip4_config_set_nis_domain (ip4_config, str);
1283 		}
1284 	
1285 		str = g_hash_table_lookup (priv->options, "new_nis_servers");
1286 		if (str) {
1287 			char **searches = g_strsplit (str, " ", 0);
1288 			char **s;
1289 	
1290 			for (s = searches; *s; s++) {
1291 				if (inet_pton (AF_INET, *s, &tmp_addr) > 0) {
1292 					nm_ip4_config_add_nis_server (ip4_config, tmp_addr);
1293 					nm_log_info (LOGD_DHCP4, "  nis '%s'", *s);
1294 				} else
1295 					nm_log_warn (LOGD_DHCP4, "ignoring invalid NIS server '%s'", *s);
1296 			}
1297 			g_strfreev (searches);
1298 		}
1299 	
1300 		return ip4_config;
1301 	
1302 	error:
1303 		g_object_unref (ip4_config);
1304 		return NULL;
1305 	}
1306 	
1307 	NMIP4Config *
1308 	nm_dhcp_client_get_ip4_config (NMDHCPClient *self, gboolean test)
1309 	{
1310 		NMDHCPClientPrivate *priv;
1311 	
1312 		g_return_val_if_fail (NM_IS_DHCP_CLIENT (self), NULL);
1313 	
1314 		priv = NM_DHCP_CLIENT_GET_PRIVATE (self);
1315 	
1316 		if (test && !state_is_bound (priv->state)) {
1317 			nm_log_warn (LOGD_DHCP4, "(%s): DHCPv4 client didn't bind to a lease.", priv->iface);
1318 			return NULL;
1319 		}
1320 	
1321 		if (!g_hash_table_size (priv->options)) {
1322 			/* We never got a response from the DHCP client */
1323 			return NULL;
1324 		}
1325 	
1326 		return ip4_options_to_config (self);
1327 	}
1328 	
1329 	/********************************************/
1330 	
1331 	static void
1332 	ip6_add_domain_search (gpointer data, gpointer user_data)
1333 	{
1334 		nm_ip6_config_add_search (NM_IP6_CONFIG (user_data), (const char *) data);
1335 	}
1336 	
1337 	/* Given a table of DHCP options from the client, convert into an IP6Config */
1338 	static NMIP6Config *
1339 	ip6_options_to_config (NMDHCPClient *self)
1340 	{
1341 		NMDHCPClientPrivate *priv;
1342 		NMIP6Config *ip6_config = NULL;
1343 		struct in6_addr tmp_addr;
1344 		NMPlatformIP6Address address;
1345 		char *str = NULL;
1346 		GHashTableIter iter;
1347 		gpointer key, value;
1348 	
1349 		g_return_val_if_fail (NM_IS_DHCP_CLIENT (self), NULL);
1350 	
1351 		memset (&address, 0, sizeof (address));
1352 		address.plen = 128;
1353 		address.timestamp = get_time ();
1354 	
1355 		priv = NM_DHCP_CLIENT_GET_PRIVATE (self);
1356 		g_return_val_if_fail (priv->options != NULL, NULL);
1357 	
1358 		g_hash_table_iter_init (&iter, priv->options);
1359 		while (g_hash_table_iter_next (&iter, &key, &value)) {
1360 			nm_log_dbg (LOGD_DHCP6, "(%s): option '%s'=>'%s'",
1361 			            priv->iface, (const char *) key, (const char *) value);
1362 		}
1363 	
1364 		ip6_config = nm_ip6_config_new ();
1365 	
1366 		str = g_hash_table_lookup (priv->options, "new_ip6_address");
1367 		if (str) {
1368 			if (!inet_pton (AF_INET6, str, &tmp_addr)) {
1369 				nm_log_warn (LOGD_DHCP6, "(%s): DHCP returned invalid address '%s'",
1370 				             priv->iface, str);
1371 				goto error;
1372 			}
1373 	
1374 			address.address = tmp_addr;
1375 			nm_log_info (LOGD_DHCP6, "  address %s", str);
1376 	
1377 		} else if (priv->info_only == FALSE) {
1378 			/* No address in Managed mode is a hard error */
1379 			goto error;
1380 		}
1381 	
1382 		str = g_hash_table_lookup (priv->options, "new_dhcp_lease_time");
1383 		if (str) {
1384 			address.lifetime = address.preferred = strtoul (str, NULL, 10);
1385 			nm_log_info (LOGD_DHCP6, "  lease time %d", address.lifetime);
1386 		}
1387 	
1388 		nm_ip6_config_add_address (ip6_config, &address);
1389 	
1390 		str = g_hash_table_lookup (priv->options, "new_host_name");
1391 		if (str)
1392 			nm_log_info (LOGD_DHCP6, "  hostname '%s'", str);
1393 	
1394 		str = g_hash_table_lookup (priv->options, "new_dhcp6_name_servers");
1395 		if (str) {
1396 			char **searches = g_strsplit (str, " ", 0);
1397 			char **s;
1398 	
1399 			for (s = searches; *s; s++) {
1400 				if (inet_pton (AF_INET6, *s, &tmp_addr) > 0) {
1401 					nm_ip6_config_add_nameserver (ip6_config, &tmp_addr);
1402 					nm_log_info (LOGD_DHCP6, "  nameserver '%s'", *s);
1403 				} else
1404 					nm_log_warn (LOGD_DHCP6, "ignoring invalid nameserver '%s'", *s);
1405 			}
1406 			g_strfreev (searches);
1407 		}
1408 	
1409 		str = g_hash_table_lookup (priv->options, "new_dhcp6_domain_search");
1410 		if (str)
1411 			process_domain_search (str, ip6_add_domain_search, ip6_config);
1412 	
1413 		return ip6_config;
1414 	
1415 	error:
1416 		g_object_unref (ip6_config);
1417 		return NULL;
1418 	}
1419 	
1420 	NMIP6Config *
1421 	nm_dhcp_client_get_ip6_config (NMDHCPClient *self, gboolean test)
1422 	{
1423 		NMDHCPClientPrivate *priv;
1424 	
1425 		g_return_val_if_fail (NM_IS_DHCP_CLIENT (self), NULL);
1426 	
1427 		priv = NM_DHCP_CLIENT_GET_PRIVATE (self);
1428 	
1429 		if (test && !state_is_bound (priv->state)) {
1430 			nm_log_warn (LOGD_DHCP6, "(%s): DHCPv6 client didn't bind to a lease.", priv->iface);
1431 			return NULL;
1432 		}
1433 	
1434 		if (!g_hash_table_size (priv->options)) {
1435 			/* We never got a response from the DHCP client */
1436 			return NULL;
1437 		}
1438 	
1439 		return ip6_options_to_config (self);
1440 	}
1441 	
1442 	/********************************************/
1443 	
1444 	static void
1445 	nm_dhcp_client_init (NMDHCPClient *self)
1446 	{
1447 		NMDHCPClientPrivate *priv = NM_DHCP_CLIENT_GET_PRIVATE (self);
1448 	
1449 		priv->options = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_free);
1450 		priv->pid = -1;
1451 	}
1452 	
1453 	static void
1454 	get_property (GObject *object, guint prop_id,
1455 				  GValue *value, GParamSpec *pspec)
1456 	{
1457 		NMDHCPClientPrivate *priv = NM_DHCP_CLIENT_GET_PRIVATE (object);
1458 	
1459 		switch (prop_id) {
1460 		case PROP_IFACE:
1461 			g_value_set_string (value, priv->iface);
1462 			break;
1463 		case PROP_HWADDR:
1464 			g_value_set_boxed (value, priv->hwaddr);
1465 			break;
1466 		case PROP_IPV6:
1467 			g_value_set_boolean (value, priv->ipv6);
1468 			break;
1469 		case PROP_UUID:
1470 			g_value_set_string (value, priv->uuid);
1471 			break;
1472 		case PROP_TIMEOUT:
1473 			g_value_set_uint (value, priv->timeout);
1474 			break;
1475 		default:
1476 			G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1477 			break;
1478 		}
1479 	}
1480 	
1481 	static void
1482 	set_property (GObject *object, guint prop_id,
1483 				  const GValue *value, GParamSpec *pspec)
1484 	{
1485 		NMDHCPClientPrivate *priv = NM_DHCP_CLIENT_GET_PRIVATE (object);
1486 	 
1487 		switch (prop_id) {
1488 		case PROP_IFACE:
1489 			/* construct-only */
1490 			priv->iface = g_strdup (g_value_get_string (value));
1491 			break;
1492 		case PROP_HWADDR:
1493 			/* construct only */
1494 			priv->hwaddr = g_value_dup_boxed (value);
1495 			break;
1496 		case PROP_IPV6:
1497 			/* construct-only */
1498 			priv->ipv6 = g_value_get_boolean (value);
1499 			break;
1500 		case PROP_UUID:
1501 			/* construct-only */
1502 			priv->uuid = g_value_dup_string (value);
1503 			break;
1504 		case PROP_TIMEOUT:
1505 			priv->timeout = g_value_get_uint (value);
1506 			break;
1507 		default:
1508 			G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1509 			break;
1510 		}
1511 	}
1512 	
1513 	static void
1514 	dispose (GObject *object)
1515 	{
1516 		NMDHCPClient *self = NM_DHCP_CLIENT (object);
1517 		NMDHCPClientPrivate *priv = NM_DHCP_CLIENT_GET_PRIVATE (self);
1518 	
1519 		/* Stopping the client is left up to the controlling device
1520 		 * explicitly since we may want to quit NetworkManager but not terminate
1521 		 * the DHCP client.
1522 		 */
1523 	
1524 		if (priv->remove_id)
1525 			g_source_remove (priv->remove_id);
1526 	
1527 		g_hash_table_destroy (priv->options);
1528 		g_free (priv->iface);
1529 		if (priv->hwaddr)
1530 			g_byte_array_free (priv->hwaddr, TRUE);
1531 	
1532 		if (priv->duid)
1533 			g_byte_array_free (priv->duid, TRUE);
1534 	
1535 		G_OBJECT_CLASS (nm_dhcp_client_parent_class)->dispose (object);
1536 	}
1537 	
1538 	static void
1539 	nm_dhcp_client_class_init (NMDHCPClientClass *client_class)
1540 	{
1541 		GObjectClass *object_class = G_OBJECT_CLASS (client_class);
1542 	
1543 		g_type_class_add_private (client_class, sizeof (NMDHCPClientPrivate));
1544 	
1545 		/* virtual methods */
1546 		object_class->dispose = dispose;
1547 		object_class->get_property = get_property;
1548 		object_class->set_property = set_property;
1549 	
1550 		client_class->stop = stop;
1551 		client_class->get_duid = get_duid;
1552 	
1553 		g_object_class_install_property
1554 			(object_class, PROP_IFACE,
1555 			 g_param_spec_string (NM_DHCP_CLIENT_INTERFACE,
1556 			                      "iface",
1557 			                      "Interface",
1558 			                      NULL,
1559 			                      G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY));
1560 	
1561 		g_object_class_install_property
1562 			(object_class, PROP_HWADDR,
1563 			 g_param_spec_boxed (NM_DHCP_CLIENT_HWADDR,
1564 			                     "hwaddr",
1565 			                     "hardware address",
1566 			                     G_TYPE_BYTE_ARRAY,
1567 			                     G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY));
1568 	
1569 		g_object_class_install_property
1570 			(object_class, PROP_IPV6,
1571 			 g_param_spec_boolean (NM_DHCP_CLIENT_IPV6,
1572 			                       "ipv6",
1573 			                       "IPv6",
1574 			                       FALSE,
1575 			                       G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY));
1576 	
1577 		g_object_class_install_property
1578 			(object_class, PROP_UUID,
1579 			 g_param_spec_string (NM_DHCP_CLIENT_UUID,
1580 			                      "uuid",
1581 			                      "UUID",
1582 			                      NULL,
1583 			                      G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY));
1584 	
1585 		g_object_class_install_property
1586 			(object_class, PROP_TIMEOUT,
1587 			 g_param_spec_uint (NM_DHCP_CLIENT_TIMEOUT,
1588 			                    "timeout",
1589 			                    "Timeout",
1590 			                    0, G_MAXUINT, 45,
1591 			                    G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY));
1592 	
1593 		/* signals */
1594 		signals[STATE_CHANGED] =
1595 			g_signal_new ("state-changed",
1596 						  G_OBJECT_CLASS_TYPE (object_class),
1597 						  G_SIGNAL_RUN_FIRST,
1598 						  G_STRUCT_OFFSET (NMDHCPClientClass, state_changed),
1599 						  NULL, NULL,
1600 						  g_cclosure_marshal_VOID__UINT,
1601 						  G_TYPE_NONE, 1, G_TYPE_UINT);
1602 	
1603 		signals[TIMEOUT] =
1604 			g_signal_new ("timeout",
1605 						  G_OBJECT_CLASS_TYPE (object_class),
1606 						  G_SIGNAL_RUN_FIRST,
1607 						  G_STRUCT_OFFSET (NMDHCPClientClass, timeout),
1608 						  NULL, NULL,
1609 						  g_cclosure_marshal_VOID__VOID,
1610 						  G_TYPE_NONE, 0);
1611 	
1612 		signals[REMOVE] =
1613 			g_signal_new ("remove",
1614 						  G_OBJECT_CLASS_TYPE (object_class),
1615 						  G_SIGNAL_RUN_FIRST,
1616 						  G_STRUCT_OFFSET (NMDHCPClientClass, remove),
1617 						  NULL, NULL,
1618 						  g_cclosure_marshal_VOID__VOID,
1619 						  G_TYPE_NONE, 0);
1620 	}
1621 	
1622