xref: /dragonfly/sbin/udevd/udevd.c (revision 6e278935)
1 /*
2  * Copyright (c) 2010 The DragonFly Project.  All rights reserved.
3  *
4  * This code is derived from software contributed to The DragonFly Project
5  * by Alex Hornung <ahornung@gmail.com>
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  *
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in
15  *    the documentation and/or other materials provided with the
16  *    distribution.
17  * 3. Neither the name of The DragonFly Project nor the names of its
18  *    contributors may be used to endorse or promote products derived
19  *    from this software without specific, prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
24  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
25  * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
26  * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
27  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
28  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
29  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
30  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
31  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  */
34 #include <sys/types.h>
35 #include <sys/device.h>
36 #include <sys/wait.h>
37 #include <sys/socket.h>
38 #include <sys/ioctl.h>
39 #include <sys/poll.h>
40 #include <sys/queue.h>
41 #include <sys/un.h>
42 #include <cpu/inttypes.h>
43 
44 #include <err.h>
45 #include <errno.h>
46 #include <fcntl.h>
47 #include <libgen.h>
48 #include <regex.h>
49 #include <signal.h>
50 #include <stdarg.h>
51 #include <stdio.h>
52 #include <stdlib.h>
53 #include <string.h>
54 #include <syslog.h>
55 #include <unistd.h>
56 #include <pthread.h>
57 
58 #include <libprop/proplib.h>
59 #include <sys/udev.h>
60 #include "udevd.h"
61 
62 int debugopt = 0;
63 
64 static int udevfd;
65 static int hangup_ongoing = 0;
66 static struct pollfd fds[NFDS];
67 
68 extern pthread_mutex_t	monitor_lock;
69 extern TAILQ_HEAD(udev_monitor_list_head, udev_monitor)	udev_monitor_list;
70 extern TAILQ_HEAD(pdev_array_list_head, pdev_array_entry)	pdev_array_list;
71 
72 static void usage(void);
73 
74 int match_dev_dict(prop_dictionary_t, prop_dictionary_t);
75 prop_dictionary_t find_dev_dict(int64_t, prop_dictionary_t, int *);
76 
77 void udev_read_event(int);
78 prop_array_t udev_getdevs(int);
79 
80 static
81 void
82 usage(void)
83 {
84 	fprintf(stderr, "usage: udevd [-d]\n");
85 	exit(1);
86 }
87 
88 int
89 match_dev_dict(prop_dictionary_t dict, prop_dictionary_t match_dict)
90 {
91 	prop_number_t	pn, pn2;
92 	prop_string_t	ps, ps2;
93 
94 	if (dict == NULL)
95 		return 0;
96 
97 	if ((ps = prop_dictionary_get(dict, "name")) == NULL)
98 		return 0;
99 	if ((ps2 = prop_dictionary_get(match_dict, "name")) == NULL)
100 		return 0;
101 	if (!prop_string_equals(ps, ps2))
102 		return 0;
103 
104 	if ((pn = prop_dictionary_get(dict, "devnum")) == NULL)
105 		return 0;
106 	if ((pn2 = prop_dictionary_get(match_dict, "devnum")) == NULL)
107 		return 0;
108 	if (!prop_number_equals(pn, pn2))
109 		return 0;
110 
111 	if ((pn = prop_dictionary_get(dict, "kptr")) == NULL)
112 		return 0;
113 	if ((pn2 = prop_dictionary_get(match_dict, "kptr")) == NULL)
114 		return 0;
115 	if (!prop_number_equals(pn, pn2))
116 		return 0;
117 
118 	return 1;
119 }
120 
121 prop_dictionary_t
122 find_dev_dict(int64_t generation, prop_dictionary_t match_dict, int *idx)
123 {
124 	struct pdev_array_entry	*pae;
125 	prop_array_t		pa;
126 	prop_object_iterator_t	iter;
127 	prop_dictionary_t	dict;
128 	int i = 0;
129 
130 	if (generation == -1)
131 		pae = pdev_array_entry_get_last();
132 	else
133 		pae = pdev_array_entry_get(generation);
134 
135 	if (pae == NULL)
136 		return NULL;
137 
138 	pa = pae->pdev_array;
139 
140 	iter = prop_array_iterator(pa);
141 	if (iter == NULL) {
142 		pdev_array_entry_unref(pae);
143 		return NULL;
144 	}
145 
146 	while ((dict = prop_object_iterator_next(iter)) != NULL) {
147 		if (match_dev_dict(dict, match_dict))
148 			break;
149 		++i;
150 	}
151 
152 	prop_object_iterator_release(iter);
153 
154 	if (idx != NULL)
155 		*idx = i;
156 
157 	pdev_array_entry_unref(pae);
158 	return dict;
159 }
160 
161 void
162 udev_read_event(int fd)
163 {
164 	struct pdev_array_entry	*pae;
165 	prop_dictionary_t	dict, evdict, devdict;
166 	prop_number_t		pn;
167 	prop_string_t		ps;
168 	prop_object_t		po;
169 	prop_array_t		pa;
170 	char	*xml;
171 	int	n, idx, evtype;
172 	size_t	sz;
173 
174 	sz = 4096 * 1024;
175 
176 	xml = malloc(sz); /* 4 MB */
177 again:
178 	if ((n = read(fd, xml, sz)) <= 0) {
179 		if (errno == ENOMEM) {
180 			sz <<= 2;
181 			realloc(xml, sz);
182 			goto again;
183 		}
184 		free(xml);
185 		return;
186 	}
187 
188 	dict = prop_dictionary_internalize(xml);
189 	free(xml);
190 	if (dict == NULL) {
191 		syslog(LOG_ERR, "internalization of xml failed");
192 		return;
193 	}
194 
195 	pn = prop_dictionary_get(dict, "evtype");
196 	if (pn == NULL) {
197 		syslog(LOG_ERR, "read_event: no key evtype");
198 		goto out;
199 	}
200 
201 	evtype = prop_number_integer_value(pn);
202 
203 	evdict = prop_dictionary_get(dict, "evdict");
204 	if (evdict == NULL) {
205 		syslog(LOG_ERR, "read_event: no key evdict");
206 		goto out;
207 	}
208 
209 	switch (evtype) {
210 	case UDEV_EVENT_ATTACH:
211 		monitor_queue_event(dict);
212 		pae = pdev_array_entry_get_last();
213 		pa = prop_array_copy(pae->pdev_array);
214 		pdev_array_entry_unref(pae);
215 		if (pa == NULL)
216 			goto out;
217 		prop_array_add(pa, evdict);
218 		pdev_array_entry_insert(pa);
219 		break;
220 
221 	case UDEV_EVENT_DETACH:
222 		monitor_queue_event(dict);
223 		if ((devdict = find_dev_dict(-1, evdict, &idx)) == NULL)
224 			goto out;
225 		pae = pdev_array_entry_get_last();
226 		pa = prop_array_copy(pae->pdev_array);
227 		pdev_array_entry_unref(pae);
228 		if (pa == NULL)
229 			goto out;
230 		prop_array_remove(pa, idx);
231 		pdev_array_entry_insert(pa);
232 		break;
233 
234 	case UDEV_EV_KEY_UPDATE:
235 		if ((devdict = find_dev_dict(-1, evdict, NULL)) == NULL)
236 			goto out;
237 		if ((ps = prop_dictionary_get(evdict, "key")) == NULL)
238 			goto out;
239 		if ((po = prop_dictionary_get(evdict, "value")) == NULL)
240 			goto out;
241 		/* prop_object_retain(po); */ /* not necessary afaik */
242 		prop_dictionary_set(devdict, prop_string_cstring_nocopy(ps), po);
243 		break;
244 
245 	case UDEV_EV_KEY_REMOVE:
246 		if ((devdict = find_dev_dict(-1, evdict, NULL)) == NULL)
247 			goto out;
248 		if ((ps = prop_dictionary_get(evdict, "key")) == NULL)
249 			goto out;
250 		prop_dictionary_remove(devdict, prop_string_cstring_nocopy(ps));
251 		break;
252 
253 	default:
254 		syslog(LOG_ERR, "read_event: unknown evtype %d", evtype);
255 	}
256 
257 out:
258 	prop_object_release(dict);
259 	return;
260 }
261 
262 prop_array_t
263 udev_getdevs(int devfd)
264 {
265 	prop_dictionary_t	pd, rpd;
266 	prop_string_t		ps;
267 	prop_array_t		pa;
268 
269 	pd = prop_dictionary_create();
270 	if (pd == NULL) {
271 		err(1, "prop_dictionary_create()");
272 	}
273 
274 	ps = prop_string_create_cstring("getdevs");
275 	if (ps == NULL) {
276 		prop_object_release(pd);
277 		err(1, "prop_string_create_cstring()");
278 	}
279 
280 	if (prop_dictionary_set(pd, "command", ps) == false) {
281 		prop_object_release(ps);
282 		prop_object_release(pd);
283 		err(1, "prop_dictionary_set()");
284 	}
285 
286 	prop_object_release(ps);
287 
288 	/* Send dictionary to kernel space */
289 	if (prop_dictionary_sendrecv_ioctl(pd, devfd, UDEVPROP, &rpd) != 0)
290 		err(1, "prop_array_recv_ioctl()");
291 
292 	prop_object_release(pd);
293 
294 	pa = prop_dictionary_get(rpd, "array");
295 	if (pa == NULL)
296 		goto out;
297 	prop_object_retain(pa);
298 
299 out:
300 	prop_object_release(rpd);
301 	return pa;
302 }
303 
304 static void
305 killed(int sig __unused)
306 {
307 	syslog(LOG_ERR, "udevd stopped");
308 	unlink("/var/run/udevd.pid");
309 	pdev_array_clean();
310 	exit(0);
311 }
312 
313 static void
314 hangup(int sig __unused)
315 {
316 	FILE *pidf;
317 	int s;
318 
319 	syslog(LOG_ERR, "udevd hangup+resume");
320 
321 	pidf = fopen("/var/run/udevd.pid", "w");
322 	if (pidf != NULL) {
323 		fprintf(pidf, "%ld\n", (long)getpid());
324 		fclose(pidf);
325 	}
326 
327 	hangup_ongoing = 1;
328 	close(fds[UDEV_SOCKET_FD_IDX].fd);
329 	pdev_array_clean();
330 	s = init_local_server(LISTEN_SOCKET_FILE, SOCK_STREAM, 0);
331 	if (s < 0)
332 		err(1, "init_local_server");
333 
334 	fds[UDEV_SOCKET_FD_IDX].fd = s;
335 	pdev_array_entry_insert(udev_getdevs(udevfd));
336 	hangup_ongoing = 0;
337 }
338 
339 int
340 ignore_signal(int signum)
341 {
342 	struct sigaction act;
343 	int ret;
344 
345 	act.sa_handler = SIG_IGN;
346 	sigemptyset(&act.sa_mask);
347 	act.sa_flags = 0;
348 
349 	ret = sigaction(signum, &act, NULL);
350 	return ret;
351 }
352 
353 static int
354 set_signal(int signum, sig_t sig_func)
355 {
356 	struct sigaction act;
357 	int ret;
358 
359 	act.sa_handler = sig_func;
360 	sigemptyset(&act.sa_mask);
361 	act.sa_flags = 0;
362 
363 	ret = sigaction(signum, &act, NULL);
364 	return ret;
365 }
366 
367 int main(int argc, char *argv[])
368 {
369 	int error __unused, i, r, s;
370 	FILE *pidf;
371 	int ch = 0;
372 
373 	while ((ch = getopt(argc, argv, "d")) != -1) {
374 		switch(ch) {
375 		case 'd':
376 			debugopt = 1;
377 			break;
378 		default:
379 			usage();
380 			/* NOT REACHED */
381 		}
382 	}
383 	argc -= optind;
384 	argv += optind;
385 
386 	TAILQ_INIT(&pdev_array_list);
387 	TAILQ_INIT(&udev_monitor_list);
388 
389 	r = ignore_signal(SIGPIPE);
390 	if (r != 0)
391 		err(1, "could not ignore_signal SIGPIPE");
392 
393 	r = pthread_mutex_init(&(monitor_lock), NULL);
394 	if (r != 0)
395 		err(1, "could not allocate a pthread_mutex");
396 
397 	if ((udevfd = open(UDEV_DEVICE_PATH, O_RDWR | O_NONBLOCK)) == -1)
398 		err(1, "%s", UDEV_DEVICE_PATH);
399 	unblock_descriptor(udevfd);
400 
401 	s = init_local_server(LISTEN_SOCKET_FILE, SOCK_STREAM, 0);
402 	if (s < 0)
403 		err(1, "init_local_server");
404 
405 	pidf = fopen("/var/run/udevd.pid", "w");
406 #if 0
407 	if (pidf == NULL)
408 		err(1, "pidfile");
409 #endif
410 
411 	set_signal(SIGTERM, killed);
412 	set_signal(SIGHUP, hangup);
413 
414 	if (debugopt == 0)
415 		if (daemon(0, 0) == -1)
416 			err(1, "daemon");
417 
418 	if (pidf != NULL) {
419 		fprintf(pidf, "%ld\n", (long)getpid());
420 		fclose(pidf);
421 	}
422 
423 	syslog(LOG_ERR, "udevd started");
424 
425 	pdev_array_entry_insert(udev_getdevs(udevfd));
426 
427 	memset(fds, 0 , sizeof(fds));
428 	fds[UDEV_DEVICE_FD_IDX].fd = udevfd;
429 	fds[UDEV_DEVICE_FD_IDX].events = POLLIN;
430 	fds[UDEV_SOCKET_FD_IDX].fd = s;
431 	fds[UDEV_SOCKET_FD_IDX].events = POLLIN | POLLPRI;
432 
433 	for (;;) {
434 		r = poll(fds, NFDS, -1);
435 		if (r < 0) {
436 			if (hangup_ongoing == 0) {
437 				if (errno == EINTR) {
438 					usleep(5000);
439 					continue;
440 				} else {
441 					err(1, "polling...");
442 				}
443 			} else {
444 				usleep(20000); /* 20 ms */
445 				continue;
446 			}
447 		}
448 
449 		for (i = 0; (i < NFDS) && (r > 0); i++) {
450 			if (fds[i].revents == 0)
451 				continue;
452 
453 			--r;
454 			switch (i) {
455 			case UDEV_DEVICE_FD_IDX:
456 				udev_read_event(udevfd);
457 				break;
458 			case UDEV_SOCKET_FD_IDX:
459 				handle_new_connection(s);
460 				break;
461 			default:
462 				break;
463 			}
464 		}
465 	}
466 
467 	syslog(LOG_ERR, "udevd is exiting normally");
468 	return 0;
469 }
470