Merge branch 'vendor/TNFTP'
[dragonfly.git] / sbin / udevd / udevd.c
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 }
311
312 static void
313 hangup(int sig __unused)
314 {
315         FILE *pidf;
316         int s;
317
318         syslog(LOG_ERR, "udevd hangup+resume");
319
320         pidf = fopen("/var/run/udevd.pid", "w");
321         if (pidf != NULL) {
322                 fprintf(pidf, "%ld\n", (long)getpid());
323                 fclose(pidf);
324         }
325
326         hangup_ongoing = 1;
327         close(fds[UDEV_SOCKET_FD_IDX].fd);
328         pdev_array_clean();
329         s = init_local_server(LISTEN_SOCKET_FILE, SOCK_STREAM, 0);
330         if (s < 0)
331                 err(1, "init_local_server");
332
333         fds[UDEV_SOCKET_FD_IDX].fd = s;
334         pdev_array_entry_insert(udev_getdevs(udevfd));
335         hangup_ongoing = 0;
336 }
337
338 int
339 ignore_signal(int signum)
340 {
341         struct sigaction act;
342         int ret;
343
344         act.sa_handler = SIG_IGN;
345         sigemptyset(&act.sa_mask);
346         act.sa_flags = 0;
347
348         ret = sigaction(signum, &act, NULL);
349         return ret;
350 }
351
352 static int
353 set_signal(int signum, sig_t sig_func)
354 {
355         struct sigaction act;
356         int ret;
357
358         act.sa_handler = sig_func;
359         sigemptyset(&act.sa_mask);
360         act.sa_flags = 0;
361
362         ret = sigaction(signum, &act, NULL);
363         return ret;
364 }
365
366 int main(int argc, char *argv[])
367 {
368         int error __unused, i, r, s;
369         FILE *pidf;
370         int ch = 0;
371
372         while ((ch = getopt(argc, argv, "d")) != -1) {
373                 switch(ch) {
374                 case 'd':
375                         debugopt = 1;
376                         break;
377                 default:
378                         usage();
379                         /* NOT REACHED */
380                 }
381         }
382         argc -= optind;
383         argv += optind;
384
385         TAILQ_INIT(&pdev_array_list);
386         TAILQ_INIT(&udev_monitor_list);
387
388         r = ignore_signal(SIGPIPE);
389         if (r != 0)
390                 err(1, "could not ignore_signal SIGPIPE");
391
392         r = pthread_mutex_init(&(monitor_lock), NULL);
393         if (r != 0)
394                 err(1, "could not allocate a pthread_mutex");
395
396         if ((udevfd = open(UDEV_DEVICE_PATH, O_RDWR | O_NONBLOCK)) == -1)
397                 err(1, "%s", UDEV_DEVICE_PATH);
398         unblock_descriptor(udevfd);
399
400         s = init_local_server(LISTEN_SOCKET_FILE, SOCK_STREAM, 0);
401         if (s < 0)
402                 err(1, "init_local_server");
403
404         pidf = fopen("/var/run/udevd.pid", "w");
405 #if 0
406         if (pidf == NULL)
407                 err(1, "pidfile");
408 #endif
409
410         set_signal(SIGTERM, killed);
411         set_signal(SIGHUP, hangup);
412
413         if (debugopt == 0)
414                 if (daemon(0, 0) == -1)
415                         err(1, "daemon");
416
417         if (pidf != NULL) {
418                 fprintf(pidf, "%ld\n", (long)getpid());
419                 fclose(pidf);
420         }
421
422         syslog(LOG_ERR, "udevd started");
423
424         pdev_array_entry_insert(udev_getdevs(udevfd));
425
426         memset(fds, 0 , sizeof(fds));
427         fds[UDEV_DEVICE_FD_IDX].fd = udevfd;
428         fds[UDEV_DEVICE_FD_IDX].events = POLLIN;
429         fds[UDEV_SOCKET_FD_IDX].fd = s;
430         fds[UDEV_SOCKET_FD_IDX].events = POLLIN | POLLPRI;
431
432         for (;;) {
433                 r = poll(fds, NFDS, -1);
434                 if (r < 0) {
435                         if (hangup_ongoing == 0) {
436                                 if (errno == EINTR) {
437                                         usleep(5000);
438                                         continue;
439                                 } else {
440                                         err(1, "polling...");
441                                 }
442                         } else {
443                                 usleep(20000); /* 20 ms */
444                                 continue;
445                         }
446                 }
447
448                 for (i = 0; (i < NFDS) && (r > 0); i++) {
449                         if (fds[i].revents == 0)
450                                 continue;
451
452                         --r;
453                         switch (i) {
454                         case UDEV_DEVICE_FD_IDX:
455                                 udev_read_event(udevfd);
456                                 break;
457                         case UDEV_SOCKET_FD_IDX:
458                                 handle_new_connection(s);
459                                 break;
460                         default:
461                                 break;
462                         }
463                 }
464         }
465
466         syslog(LOG_ERR, "udevd is exiting normally");
467         return 0;
468 }