summaryrefslogtreecommitdiff
path: root/src/dhcp.c
blob: 58a63ebbaf8e81970d0a038dac9643517d08a98b (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
/*
 * OpenWFD - Open-Source Wifi-Display Implementation
 *
 * Copyright (c) 2013 David Herrmann <dh.herrmann@gmail.com>
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files
 * (the "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be included
 * in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
 * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
 * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

/*
 * Small DHCP Client/Server for OpenWFD
 * Wifi-P2P requires us to use DHCP to set up a private P2P network. As all
 * DHCP daemons available have horrible interfaces for ad-hoc setups, we have
 * this small replacement for all DHCP operations.
 *
 * This program implements a DHCP server and daemon. See --help for usage
 * information. We build on gdhcp from connman as the underlying DHCP protocol
 * implementation. To configure network devices, we actually invoke the "ip"
 * binary.
 *
 * Note that this is a gross hack! We don't intend to provide a fully functional
 * DHCP server or client here. This is only a replacement for the current lack
 * of Wifi-P2P support in common network managers. Once they gain proper
 * support, we will drop this helper!
 *
 * The "ip" invokation is quite fragile and ugly. However, performing these
 * steps directly involves netlink operations and more. As no-one came up with
 * patches, yet, we keep the hack. To anyone trying to fix it: Please, spend
 * this time hacking on NetworkManager, connman and friends instead! If they
 * gain Wifi-P2P support, this whole thing will get trashed.
 */

#include <arpa/inet.h>
#include <errno.h>
#include <glib.h>
#include <netinet/in.h>
#include <signal.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/epoll.h>
#include <sys/signalfd.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <unistd.h>
#include "dhcp.h"
#include "gdhcp/gdhcp.h"
#include "shared.h"
#include "shl_log.h"

struct owfd_dhcp {
	struct owfd_dhcp_config config;
	int ifindex;
	char *iflabel;
	GMainLoop *loop;

	int sfd;
	GIOChannel *sfd_chan;
	guint sfd_id;

	GDHCPClient *client;
	char *client_addr;
};

static int flush_if_addr(struct owfd_dhcp *dhcp)
{
	char *argv[64];
	int i, r;
	pid_t pid, rp;
	sigset_t mask;

	pid = fork();
	if (pid < 0) {
		return log_ERRNO();
	} else if (!pid) {
		/* child */

		sigemptyset(&mask);
		sigprocmask(SIG_SETMASK, &mask, NULL);

		/* redirect stdout to stderr */
		dup2(2, 1);

		i = 0;
		argv[i++] = dhcp->config.ip_binary;
		argv[i++] = "addr";
		argv[i++] = "flush";
		argv[i++] = "dev";
		argv[i++] = dhcp->config.interface;
		argv[i++] = "label";
		argv[i++] = dhcp->iflabel;
		argv[i] = NULL;

		execve(argv[0], argv, environ);
		_exit(1);
	}

	log_info("flushing local if-addr");
	rp = waitpid(pid, &r, 0);
	if (rp != pid) {
		log_error("cannot flush local if-addr via '%s'",
			  dhcp->config.ip_binary);
		return -EFAULT;
	} else if (!WIFEXITED(r)) {
		log_error("flushing local if-addr via '%s' failed",
			  dhcp->config.ip_binary);
		return -EFAULT;
	} else if (WEXITSTATUS(r)) {
		log_error("flushing local if-addr via '%s' failed with: %d",
			  dhcp->config.ip_binary, WEXITSTATUS(r));
		return -EFAULT;
	}

	log_debug("successfully flushed local if-addr via %s",
		  dhcp->config.ip_binary);

	return 0;
}

static int add_if_addr(struct owfd_dhcp *dhcp, char *addr)
{
	char *argv[64];
	int i, r;
	pid_t pid, rp;
	sigset_t mask;

	pid = fork();
	if (pid < 0) {
		return log_ERRNO();
	} else if (!pid) {
		/* child */

		sigemptyset(&mask);
		sigprocmask(SIG_SETMASK, &mask, NULL);

		/* redirect stdout to stderr */
		dup2(2, 1);

		i = 0;
		argv[i++] = dhcp->config.ip_binary;
		argv[i++] = "addr";
		argv[i++] = "add";
		argv[i++] = addr;
		argv[i++] = "dev";
		argv[i++] = dhcp->config.interface;
		argv[i++] = "label";
		argv[i++] = dhcp->iflabel;
		argv[i] = NULL;

		execve(argv[0], argv, environ);
		_exit(1);
	}

	log_info("adding local if-addr %s", addr);
	rp = waitpid(pid, &r, 0);
	if (rp != pid) {
		log_error("cannot set local if-addr %s via '%s'",
			  addr, dhcp->config.ip_binary);
		return -EFAULT;
	} else if (!WIFEXITED(r)) {
		log_error("setting local if-addr %s via '%s' failed",
			  addr, dhcp->config.ip_binary);
		return -EFAULT;
	} else if (WEXITSTATUS(r)) {
		log_error("setting local if-addr %s via '%s' failed with: %d",
			  addr, dhcp->config.ip_binary, WEXITSTATUS(r));
		return -EFAULT;
	}

	log_debug("successfully set local if-addr %s via %s",
		  addr, dhcp->config.ip_binary);

	return 0;
}

static void client_lease_fn(GDHCPClient *client, gpointer data)
{
	struct owfd_dhcp *dhcp = data;
	char *addr, *a, *subnet = NULL;
	GList *l;
	int r;

	log_info("lease available");

	addr = g_dhcp_client_get_address(client);
	log_info("lease: address: %s", addr);

	l = g_dhcp_client_get_option(client, G_DHCP_SUBNET);
	for ( ; l; l = l->next) {
		subnet = subnet ? : (char*)l->data;
		log_info("lease: subnet: %s", (char*)l->data);
	}

	l = g_dhcp_client_get_option(client, G_DHCP_DNS_SERVER);
	for ( ; l; l = l->next)
		log_info("lease: dns-server: %s", (char*)l->data);

	l = g_dhcp_client_get_option(client, G_DHCP_ROUTER);
	for ( ; l; l = l->next)
		log_info("lease: router: %s", (char*)l->data);

	if (!addr) {
		log_error("lease without IP address");
		goto error;
	}
	if (!subnet) {
		log_warning("lease without subnet mask, using 24");
		subnet = "24";
	}

	r = asprintf(&a, "%s/%s", addr, subnet);
	if (r < 0) {
		log_vENOMEM();
		g_free(addr);
		goto error;
	} else {
		g_free(addr);
	}

	if (dhcp->client_addr && !strcmp(dhcp->client_addr, a)) {
		log_info("given address already set");
		free(a);
	} else {
		free(dhcp->client_addr);
		dhcp->client_addr = a;

		r = flush_if_addr(dhcp);
		if (r < 0) {
			log_error("cannot flush addr on local interface %s",
				  dhcp->config.interface);
			goto error;
		}

		r = add_if_addr(dhcp, dhcp->client_addr);
		if (r < 0) {
			log_error("cannot set parameters on local interface %s",
				  dhcp->config.interface);
			goto error;
		}
	}

	return;

error:
	g_main_loop_quit(dhcp->loop);
}

static void client_no_lease_fn(GDHCPClient *client, gpointer data)
{
	struct owfd_dhcp *dhcp = data;

	log_error("no lease available");
	g_main_loop_quit(dhcp->loop);
}

static gboolean owfd_dhcp_sfd_fn(GIOChannel *chan, GIOCondition mask,
				 gpointer data)
{
	struct owfd_dhcp *dhcp = data;
	ssize_t l;
	struct signalfd_siginfo info;

	if (mask & (G_IO_HUP | G_IO_ERR)) {
		log_vEPIPE();
		g_main_loop_quit(dhcp->loop);
		return FALSE;
	}

	l = read(dhcp->sfd, &info, sizeof(info));
	if (l < 0) {
		log_vERRNO();
		g_main_loop_quit(dhcp->loop);
		return FALSE;
	} else if (l != sizeof(info)) {
		log_vEFAULT();
		return TRUE;
	}

	log_notice("received signal %d: %s",
		   info.ssi_signo, strsignal(info.ssi_signo));

	g_main_loop_quit(dhcp->loop);
	return FALSE;
}

static int owfd_dhcp_run(struct owfd_dhcp *dhcp)
{
	int r;

	if (dhcp->config.client) {
		log_info("running dhcp client on %s via '%s'",
			 dhcp->config.interface, dhcp->config.ip_binary);

		r = g_dhcp_client_start(dhcp->client, NULL);
		if (r != 0) {
			log_error("cannot start DHCP client: %d", r);
			return -EFAULT;
		}
	} else {
		log_info("running dhcp server on %s via '%s'",
			 dhcp->config.interface, dhcp->config.ip_binary);
	}

	g_main_loop_run(dhcp->loop);

	return 0;
}

static void owfd_dhcp_teardown(struct owfd_dhcp *dhcp)
{
	if (dhcp->config.client) {
		if (dhcp->client) {
			g_dhcp_client_stop(dhcp->client);

			if (dhcp->client_addr) {
				flush_if_addr(dhcp);
				free(dhcp->client_addr);
			}

			g_dhcp_client_unref(dhcp->client);
		}
	} else {
	}

	if (dhcp->sfd >= 0) {
		g_source_remove(dhcp->sfd_id);
		g_io_channel_unref(dhcp->sfd_chan);
		close(dhcp->sfd);
	}

	if (dhcp->loop)
		g_main_loop_unref(dhcp->loop);

	free(dhcp->iflabel);
}

static void sig_dummy(int sig)
{
}

static int owfd_dhcp_setup(struct owfd_dhcp *dhcp)
{
	static const int sigs[] = {
		SIGINT,
		SIGTERM,
		SIGQUIT,
		SIGHUP,
		SIGPIPE,
		0
	};
	int r, i;
	sigset_t mask;
	struct sigaction sig;
	GDHCPClientError cerr;

	if (geteuid())
		log_warning("not running as uid=0, dhcp might not work");

	dhcp->ifindex = if_name_to_index(dhcp->config.interface);
	if (dhcp->ifindex < 0) {
		r = -EINVAL;
		log_error("cannot find interface %s (%d)",
			  dhcp->config.interface, dhcp->ifindex);
		goto error;
	}

	r = asprintf(&dhcp->iflabel, "%s:openwfd", dhcp->config.interface);
	if (r < 0) {
		r = log_ERRNO();
		goto error;
	}

	dhcp->loop = g_main_loop_new(NULL, FALSE);

	sigemptyset(&mask);
	memset(&sig, 0, sizeof(sig));
	sig.sa_handler = sig_dummy;
	sig.sa_flags = SA_RESTART;

	for (i = 0; sigs[i]; ++i) {
		sigaddset(&mask, sigs[i]);
		r = sigaction(sigs[i], &sig, NULL);
		if (r < 0) {
			r = log_ERRNO();
			goto error;
		}
	}

	r = sigprocmask(SIG_BLOCK, &mask, NULL);
	if (r < 0) {
		r = log_ERRNO();
		goto error;
	}

	dhcp->sfd = signalfd(-1, &mask, SFD_CLOEXEC | SFD_NONBLOCK);
	if (dhcp->sfd < 0) {
		r = log_ERRNO();
		goto error;
	}

	dhcp->sfd_chan = g_io_channel_unix_new(dhcp->sfd);
	dhcp->sfd_id = g_io_add_watch(dhcp->sfd_chan,
				      G_IO_HUP | G_IO_ERR | G_IO_IN,
				      owfd_dhcp_sfd_fn,
				      dhcp);

	if (dhcp->config.client) {
		dhcp->client = g_dhcp_client_new(G_DHCP_IPV4, dhcp->ifindex,
						 &cerr);
		if (!dhcp->client) {
			r = -EINVAL;

			switch (cerr) {
			case G_DHCP_CLIENT_ERROR_INTERFACE_UNAVAILABLE:
				log_error("cannot create GDHCP client: interface %s unavailable",
					  dhcp->config.interface);
				break;
			case G_DHCP_CLIENT_ERROR_INTERFACE_IN_USE:
				log_error("cannot create GDHCP client: interface %s in use",
					  dhcp->config.interface);
				break;
			case G_DHCP_CLIENT_ERROR_INTERFACE_DOWN:
				log_error("cannot create GDHCP client: interface %s down",
					  dhcp->config.interface);
				break;
			case G_DHCP_CLIENT_ERROR_NOMEM:
				r = log_ENOMEM();
				break;
			case G_DHCP_CLIENT_ERROR_INVALID_INDEX:
				log_error("cannot create GDHCP client: invalid interface %s",
					  dhcp->config.interface);
				break;
			case G_DHCP_CLIENT_ERROR_INVALID_OPTION:
				log_error("cannot create GDHCP client: invalid options");
				break;
			default:
				log_error("cannot create GDHCP client (%d)",
					  cerr);
				break;
			}

			goto error;
		}

		g_dhcp_client_set_send(dhcp->client, G_DHCP_HOST_NAME,
				       "<hostname>");

		g_dhcp_client_set_request(dhcp->client, G_DHCP_SUBNET);
		g_dhcp_client_set_request(dhcp->client, G_DHCP_DNS_SERVER);
		g_dhcp_client_set_request(dhcp->client, G_DHCP_ROUTER);

		g_dhcp_client_register_event(dhcp->client,
					     G_DHCP_CLIENT_EVENT_LEASE_AVAILABLE,
					     client_lease_fn, dhcp);
		g_dhcp_client_register_event(dhcp->client,
					     G_DHCP_CLIENT_EVENT_NO_LEASE,
					     client_no_lease_fn, dhcp);
	} else {
	}

	return 0;

error:
	owfd_dhcp_teardown(dhcp);
	return r;
}

int main(int argc, char **argv)
{
	struct owfd_dhcp dhcp;
	int r;

	memset(&dhcp, 0, sizeof(dhcp));
	dhcp.sfd = -1;
	owfd_dhcp_init_config(&dhcp.config);

	r = owfd_dhcp_parse_argv(&dhcp.config, argc, argv);
	if (r < 0)
		goto err_out;

	if (dhcp.config.debug)
		log_max_sev = LOG_DEBUG;
	else if (dhcp.config.verbose)
		log_max_sev = LOG_INFO;
	else if (dhcp.config.silent)
		log_max_sev = LOG_ERROR;

	if (dhcp.config.silent)
		log_debug("-");
	else
		log_format(LOG_DEFAULT_BASE, NULL, LOG_SEV_NUM,
			   "openwfd_dhcp - revision %s %s %s",
			   "some-rev-TODO-xyz", __DATE__, __TIME__);

	log_info("initializing");
	r = owfd_dhcp_setup(&dhcp);
	if (r < 0)
		goto err_conf;

	r = owfd_dhcp_run(&dhcp);

	owfd_dhcp_teardown(&dhcp);
err_conf:
	owfd_dhcp_clear_config(&dhcp.config);
	if (r < 0) {
		errno = -r;
		log_error("initialization failed (%d): %m", r);
	}
	log_info("exiting");
err_out:
	return -r;
}