summaryrefslogtreecommitdiff
path: root/src/p2pd_interface.c
blob: ec9066235977915b997506c24fd0ed87bfb27024 (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
/*
 * 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.
 */

#include <errno.h>
#include <fcntl.h>
#include <getopt.h>
#include <poll.h>
#include <signal.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/epoll.h>
#include <sys/inotify.h>
#include <sys/wait.h>
#include <unistd.h>
#include "p2pd.h"
#include "shared.h"
#include "shl_log.h"
#include "wpa_ctrl.h"

struct owfd_p2pd_interface {
	struct owfd_wpa_ctrl *wpa;
	pid_t pid;
};

/*
 * Execute wpa_supplicant. This is called after fork(). It shall initialize the
 * environment for wpa_supplicant and then execve() it. This should not return.
 * If it does, exit(1) is called for this child.
 */
static void run_child(struct owfd_p2pd_interface *iface,
		      struct owfd_p2pd_config *config)
{
	char *argv[64];
	int i, r;
	sigset_t mask;

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

	/* redirect stdout to stderr for wpa_supplicant */
	r = dup2(2, 1);
	if (r < 0)
		return;

	/* initialize wpa_supplicant args */
	i = 0;
	argv[i++] = config->wpa_binary;
	argv[i++] = "-Dnl80211";
	argv[i++] = "-qq";
	argv[i++] = "-C";
	argv[i++] = config->wpa_ctrldir;
	argv[i++] = "-i";
	argv[i++] = config->interface;
	argv[i] = NULL;

	/* execute wpa_supplicant; if it fails, the caller issues exit(1) */
	execve(argv[0], argv, environ);
}

/*
 * Test whether child with pid @pid is still running. This is a non-blocking
 * call which drains the ECHLD queue in case it already died!
 */
static bool is_child_alive(pid_t pid)
{
	return !waitpid(pid, NULL, WNOHANG);
}

/*
 * Wait for wpa_supplicant startup.
 * We create an inotify-fd to wait for creation of /run/wpa_supplicant/wlan1.
 * Then we wait for wlan1 to be opened and after that we open it ourselves.
 *
 * Note that inotify-fds must always be created before testing the condition.
 * Otherwise, there's a race between testing the condition and starting the
 * inotify-watch.
 */
static int wait_for_wpa(struct owfd_p2pd_interface *iface,
			struct owfd_p2pd_config *config,
			const char *file)
{
	int fd, r, w;
	int64_t t, start;
	struct pollfd fds[1];
	char ev[sizeof(struct inotify_event) + 1024];
	struct inotify_event *e;

	/* create inotify-fd */
	fd = inotify_init1(IN_CLOEXEC | IN_NONBLOCK);
	if (fd < 0)
		return log_ERRNO();

	/* set 10s timeout and init poll-events */
	t = 10LL * 1000LL * 1000LL;
	fds[0].fd = fd;
	fds[0].events = POLLHUP | POLLERR | POLLIN;

try_again:
	/* add /run/wpa_supplicant watch */
	w = inotify_add_watch(fd, config->wpa_ctrldir,
			      IN_CREATE | IN_MOVED_TO | IN_ONLYDIR);
	if (w < 0) {
		r = log_ERRNO();
		goto err_close;
	}

	/* verify wpa_supplicant is still alive */
	if (!is_child_alive(iface->pid)) {
		log_error("wpa_supplicant died unexpectedly");
		r = -ENODEV;
		goto err_close;
	}

	/* If /run/wpa_supplicant/<iface> does not exist, start waiting for
	 * inotify events. Otherwise, skip waiting. */
	if (access(file, F_OK) < 0) {
		while (1) {
			start = get_time_us();
			fds[0].revents = 0;

			/* poll for inotify events */
			r = poll(fds, 1, t / 1000LL);
			if (r < 0) {
				r = log_ERRNO();
				goto err_close;
			} else if (r == 1 && fds[0].revents & (POLLHUP | POLLERR)) {
				r = log_EPIPE();
				goto err_close;
			}

			/* update timeout */
			t = t - (get_time_us() - start);

			/* verify wpa_supplicant is still alive */
			if (!is_child_alive(iface->pid)) {
				log_error("wpa_supplicant died unexpectedly");
				r = -ENODEV;
				goto err_close;
			}

			/* bail out if ctrl-sock is avilable */
			if (!access(file, F_OK))
				break;

			/* drain input queue */
			read(fd, ev, sizeof(ev));

			/* check for timeout and then continue polling */
			if (t <= 0) {
				r = -ETIMEDOUT;
				log_error("waiting for wpa_supplicant startup timed out");
				goto err_close;
			}
		}
	}

	/* remove directory watch */
	inotify_rm_watch(fd, w);

	/* add socket watch */
	w = inotify_add_watch(fd, file,
			      IN_OPEN | IN_DELETE_SELF | IN_MOVE_SELF);
	if (w < 0) {
		r = log_ERRNO();
		goto err_close;
	}

	/* verify wpa_supplicant is still alive */
	if (!is_child_alive(iface->pid)) {
		log_error("wpa_supplicant died unexpectedly");
		r = -ENODEV;
		goto err_close;
	}

	/* try opening socket and bail out if we succeed */
	r = owfd_wpa_ctrl_open(iface->wpa, file, NULL);
	if (r >= 0)
		goto done;

	/* Socket is not initialized by wpa_supplicant, yet. Start polling for
	 * inotify events and wait until _someone_ opens it. */
	while (1) {
		start = get_time_us();
		fds[0].revents = 0;

		/* poll for events */
		r = poll(fds, 1, t / 1000LL);
		if (r < 0) {
			r = log_ERRNO();
			goto err_close;
		} else if (r == 1 && fds[0].revents & (POLLHUP | POLLERR)) {
			r = log_EPIPE();
			goto err_close;
		}

		/* update timeout */
		t = t - (get_time_us() - start);

		/* verify wpa_supplicant is still alive */
		if (!is_child_alive(iface->pid)) {
			log_error("wpa_supplicant died unexpectedly");
			r = -ENODEV;
			goto err_close;
		}

		/* drain input queue */
		r = read(fd, ev, sizeof(ev));
		if (r < 0 && errno != EAGAIN) {
			r = log_ERRNO();
			goto err_close;
		} else if (r > 0) {
			e = (void*)ev;
			if (e->wd == w) {
				/* Yey! Startup should be clear now */
				if (e->mask & IN_OPEN)
					break;

				/* Socket removed? Bail out and retry */
				if (e->mask & (IN_DELETE_SELF |
					       IN_MOVE_SELF |
					       IN_IGNORED |
					       IN_UNMOUNT))
					break;
			}
		}

		/* check for timeout and then continue polling */
		if (t <= 0) {
			r = -ETIMEDOUT;
			log_error("waiting for wpa_supplicant startup timed out");
			goto err_close;
		}
	}

	/* remove directory watch */
	inotify_rm_watch(fd, w);

	/* retry opening socket */
	r = owfd_wpa_ctrl_open(iface->wpa, file, NULL);
	if (r < 0) {
		/* The ctrl-file may be a left-over of a previous start. Start
		 * all over again. */
		goto try_again;
	}

done:
	r = 0;
err_close:
	close(fd);
	return r;
}

/*
 * Fork and exec wpa_supplicant. This waits for wpa_supplicant startup and
 * connects the wpa_ctrl socket. If this returns (even with an error), you
 * _must_ call kill_wpa() to stop the wpa_supplicant process later.
 */
static int fork_wpa(struct owfd_p2pd_interface *iface,
		    struct owfd_p2pd_config *config)
{
	pid_t pid;
	int r;
	char *ctrl;
	sigset_t mask, old;

	pid = fork();
	if (pid < 0) {
		return log_ERRNO();
	} else if (!pid) {
		/* child */
		run_child(iface, config);
		exit(1);
	}

	/* parent; wait for control-socket to be available */

	iface->pid = pid;

	r = asprintf(&ctrl, "%s/%s", config->wpa_ctrldir, config->interface);
	if (r < 0)
		return -ENOMEM;

	log_info("waiting for wpa_supplicant startup on: %s", ctrl);

	/* allow fatal signals during blocking startup */
	sigemptyset(&mask);
	sigaddset(&mask, SIGINT);
	sigaddset(&mask, SIGTERM);
	sigaddset(&mask, SIGQUIT);
	sigaddset(&mask, SIGHUP);
	sigaddset(&mask, SIGCHLD);
	sigprocmask(SIG_UNBLOCK, &mask, &old);

	r = wait_for_wpa(iface, config, ctrl);

	sigprocmask(SIG_SETMASK, &old, NULL);

	if (r < 0) {
		log_error("wpa_supplicant startup failed");
		free(ctrl);
		return r;
	}

	free(ctrl);
	return 0;
}

/*
 * Stop running wpa_supplicant. This tries to send a synchronous TERMINATE
 * message. If it fails, we send a signal to stop the child.
 */
static void kill_wpa(struct owfd_p2pd_interface *iface)
{
	int r;

	if (iface->pid <= 0)
		return;

	if (owfd_wpa_ctrl_is_open(iface->wpa)) {
		r = owfd_wpa_ctrl_request_ok(iface->wpa, "TERMINATE", 9, -1);
		if (r >= 0) {
			log_info("wpa_supplicant acknowledged termination request");
			return;
		}

		log_error("cannot send termination request to wpa_supplicant (%d)", r);
	}

	log_info("sending SIGTERM to wpa_supplicant");
	r = kill(iface->pid, SIGTERM);
	if (r < 0)
		log_error("cannot send SIGTERM to wpa_supplicant (%d)", r);
}

int owfd_p2pd_interface_new(struct owfd_p2pd_interface **out,
			    struct owfd_p2pd_config *conf, int efd)
{
	struct owfd_p2pd_interface *iface;
	int r;

	log_info("using interface: %s", conf->interface);

	iface = calloc(1, sizeof(*iface));
	if (!iface)
		return log_ENOMEM();

	r = owfd_wpa_ctrl_new(&iface->wpa);
	if (r < 0) {
		errno = -r;
		log_vERRNO();
		goto err_iface;
	}

	r = fork_wpa(iface, conf);
	if (r < 0)
		goto err_kill;

	*out = iface;
	return 0;

err_kill:
	kill_wpa(iface);
	owfd_wpa_ctrl_close(iface->wpa);
	owfd_wpa_ctrl_unref(iface->wpa);
err_iface:
	free(iface);
	return r;
}

void owfd_p2pd_interface_free(struct owfd_p2pd_interface *iface)
{
	if (!iface)
		return;

	kill_wpa(iface);
	owfd_wpa_ctrl_close(iface->wpa);
	owfd_wpa_ctrl_unref(iface->wpa);
	free(iface);
}

int owfd_p2pd_interface_dispatch(struct owfd_p2pd_interface *iface,
				 struct owfd_p2pd_ep *ep)
{
	return 0;
}

int owfd_p2pd_interface_dispatch_chld(struct owfd_p2pd_interface *iface,
				      struct signalfd_siginfo *info)
{
	if (iface->pid <= 0 || info->ssi_pid != iface->pid)
		return OWFD_P2PD_EP_NOT_HANDLED;

	log_info("wpa_supplicant exited");

	owfd_wpa_ctrl_close(iface->wpa);
	iface->pid = 0;

	return OWFD_P2PD_EP_QUIT;
}