chiark / gitweb /
pass CROSS_COMPILE to AR and RANLIB down to extras/
[elogind.git] / udevd.c
1 /*
2  * udevd.c - event listener and serializer
3  *
4  * Copyright (C) 2004-2005 Kay Sievers <kay.sievers@vrfy.org>
5  * Copyright (C) 2004 Chris Friesen <chris_friesen@sympatico.ca>
6  *
7  *
8  *      This program is free software; you can redistribute it and/or modify it
9  *      under the terms of the GNU General Public License as published by the
10  *      Free Software Foundation version 2 of the License.
11  *
12  *      This program is distributed in the hope that it will be useful, but
13  *      WITHOUT ANY WARRANTY; without even the implied warranty of
14  *      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  *      General Public License for more details.
16  *
17  *      You should have received a copy of the GNU General Public License along
18  *      with this program; if not, write to the Free Software Foundation, Inc.,
19  *      675 Mass Ave, Cambridge, MA 02139, USA.
20  *
21  */
22
23 #include <stddef.h>
24 #include <signal.h>
25 #include <unistd.h>
26 #include <errno.h>
27 #include <stdio.h>
28 #include <stdlib.h>
29 #include <string.h>
30 #include <ctype.h>
31 #include <dirent.h>
32 #include <fcntl.h>
33 #include <syslog.h>
34 #include <time.h>
35 #include <sys/select.h>
36 #include <sys/wait.h>
37 #include <sys/types.h>
38 #include <sys/socket.h>
39 #include <sys/un.h>
40 #include <sys/stat.h>
41 #include <sys/ioctl.h>
42 #include <linux/types.h>
43 #include <linux/netlink.h>
44
45 #include "udev.h"
46 #include "udev_rules.h"
47 #include "udevd.h"
48
49 static struct udev_rules rules;
50 static int udevd_sock;
51 static int uevent_netlink_sock;
52 static int inotify_fd;
53 static pid_t sid;
54
55 static int signal_pipe[2] = {-1, -1};
56 static volatile int sigchilds_waiting;
57 static volatile int udev_exit;
58 static volatile int reload_config;
59 static int run_exec_q;
60 static int stop_exec_q;
61 static int max_childs;
62 static int max_childs_running;
63 static char udev_log[32];
64
65 static LIST_HEAD(exec_list);
66 static LIST_HEAD(running_list);
67
68
69 #ifdef USE_LOG
70 void log_message(int priority, const char *format, ...)
71 {
72         va_list args;
73
74         if (priority > udev_log_priority)
75                 return;
76
77         va_start(args, format);
78         vsyslog(priority, format, args);
79         va_end(args);
80 }
81 #endif
82
83 static void asmlinkage udev_event_sig_handler(int signum)
84 {
85         if (signum == SIGALRM)
86                 exit(1);
87 }
88
89 static int udev_event_process(struct uevent_msg *msg)
90 {
91         struct sigaction act;
92         struct udevice *udev;
93         int i;
94         int retval;
95
96         /* set signal handlers */
97         memset(&act, 0x00, sizeof(act));
98         act.sa_handler = (void (*)(int)) udev_event_sig_handler;
99         sigemptyset (&act.sa_mask);
100         act.sa_flags = 0;
101         sigaction(SIGALRM, &act, NULL);
102
103         /* reset to default */
104         act.sa_handler = SIG_DFL;
105         sigaction(SIGINT, &act, NULL);
106         sigaction(SIGTERM, &act, NULL);
107         sigaction(SIGCHLD, &act, NULL);
108         sigaction(SIGHUP, &act, NULL);
109
110         /* trigger timeout to prevent hanging processes */
111         alarm(UDEV_ALARM_TIMEOUT);
112
113         /* reconstruct event environment from message */
114         for (i = 0; msg->envp[i]; i++)
115                 putenv(msg->envp[i]);
116
117         udev = udev_device_init();
118         if (udev == NULL)
119                 return -1;
120         strlcpy(udev->action, msg->action, sizeof(udev->action));
121         sysfs_device_set_values(udev->dev, msg->devpath, msg->subsystem);
122         udev->devt = msg->devt;
123
124         retval = udev_device_event(&rules, udev);
125
126         /* run programs collected by RUN-key*/
127         if (retval == 0 && !udev->ignore_device && udev_run) {
128                 struct name_entry *name_loop;
129
130                 dbg("executing run list");
131                 list_for_each_entry(name_loop, &udev->run_list, node) {
132                         if (strncmp(name_loop->name, "socket:", strlen("socket:")) == 0)
133                                 pass_env_to_socket(&name_loop->name[strlen("socket:")], msg->devpath, msg->action);
134                         else {
135                                 char program[PATH_SIZE];
136
137                                 strlcpy(program, name_loop->name, sizeof(program));
138                                 udev_rules_apply_format(udev, program, sizeof(program));
139                                 if (run_program(program, udev->dev->subsystem, NULL, 0, NULL,
140                                                 (udev_log_priority >= LOG_INFO)))
141                                         retval = -1;
142                         }
143                 }
144         }
145
146         udev_device_cleanup(udev);
147         return retval;
148 }
149
150 enum event_state {
151         EVENT_QUEUED,
152         EVENT_FINISHED,
153         EVENT_FAILED,
154 };
155
156 static void export_event_state(struct uevent_msg *msg, enum event_state state)
157 {
158         char filename[PATH_SIZE];
159         char filename_failed[PATH_SIZE];
160         char target[PATH_SIZE];
161         size_t start, end, i;
162         struct uevent_msg *loop_msg;
163
164         /* add location of queue files */
165         strlcpy(filename, udev_root, sizeof(filename));
166         strlcat(filename, "/", sizeof(filename));
167         start = strlcat(filename, EVENT_QUEUE_DIR, sizeof(filename));
168         end = strlcat(filename, msg->devpath, sizeof(filename));
169         if (end > sizeof(filename))
170                 end = sizeof(filename);
171
172         /* replace '/' to transform path into a filename */
173         for (i = start+1; i < end; i++)
174                 if (filename[i] == '/')
175                         filename[i] = PATH_TO_NAME_CHAR;
176
177         /* add location of failed files */
178         strlcpy(filename_failed, udev_root, sizeof(filename_failed));
179         strlcat(filename_failed, "/", sizeof(filename_failed));
180         start = strlcat(filename_failed, EVENT_FAILED_DIR, sizeof(filename_failed));
181         end = strlcat(filename_failed, msg->devpath, sizeof(filename_failed));
182         if (end > sizeof(filename_failed))
183                 end = sizeof(filename_failed);
184
185         /* replace '/' to transform path into a filename */
186         for (i = start+1; i < end; i++)
187                 if (filename_failed[i] == '/')
188                         filename_failed[i] = PATH_TO_NAME_CHAR;
189
190         switch (state) {
191         case EVENT_QUEUED:
192                 unlink(filename_failed);
193                 delete_path(filename_failed);
194
195                 strlcpy(target, sysfs_path, sizeof(target));
196                 strlcat(target, msg->devpath, sizeof(target));
197                 create_path(filename);
198                 symlink(target, filename);
199                 return;
200         case EVENT_FINISHED:
201         case EVENT_FAILED:
202                 unlink(filename_failed);
203                 delete_path(filename_failed);
204
205                 /* don't remove, if events for the same path are still pending */
206                 list_for_each_entry(loop_msg, &running_list, node)
207                         if (loop_msg->devpath && strcmp(loop_msg->devpath, msg->devpath) == 0)
208                                 return;
209
210                 list_for_each_entry(loop_msg, &exec_list, node)
211                         if (loop_msg->devpath && strcmp(loop_msg->devpath, msg->devpath) == 0)
212                                 return;
213
214                 /* move failed events to the failed directory */
215                 if (state == EVENT_FAILED) {
216                         create_path(filename_failed);
217                         rename(filename, filename_failed);
218                 } else {
219                         unlink(filename);
220                 }
221
222                 /* clean up the queue directory */
223                 delete_path(filename);
224
225                 return;
226         }
227 }
228
229 static void msg_queue_delete(struct uevent_msg *msg)
230 {
231         list_del(&msg->node);
232
233         /* mark as failed, if add event returns non-zero */
234         if (msg->exitstatus && strcmp(msg->action, "add") == 0)
235                 export_event_state(msg, EVENT_FAILED);
236         else
237                 export_event_state(msg, EVENT_FINISHED);
238
239         free(msg);
240 }
241
242 static void udev_event_run(struct uevent_msg *msg)
243 {
244         pid_t pid;
245         int retval;
246
247         pid = fork();
248         switch (pid) {
249         case 0:
250                 /* child */
251                 close(uevent_netlink_sock);
252                 close(udevd_sock);
253                 if (inotify_fd > 0)
254                         close(inotify_fd);
255                 close(signal_pipe[READ_END]);
256                 close(signal_pipe[WRITE_END]);
257                 logging_close();
258
259                 logging_init("udevd-event");
260                 setpriority(PRIO_PROCESS, 0, UDEV_PRIORITY);
261                 retval = udev_event_process(msg);
262                 info("seq %llu finished", msg->seqnum);
263
264                 logging_close();
265                 if (retval)
266                         exit(1);
267                 exit(0);
268         case -1:
269                 err("fork of child failed: %s", strerror(errno));
270                 msg_queue_delete(msg);
271                 break;
272         default:
273                 /* get SIGCHLD in main loop */
274                 info("seq %llu forked, pid [%d], '%s' '%s', %ld seconds old",
275                      msg->seqnum, pid,  msg->action, msg->subsystem, time(NULL) - msg->queue_time);
276                 msg->pid = pid;
277         }
278 }
279
280 static void msg_queue_insert(struct uevent_msg *msg)
281 {
282         msg->queue_time = time(NULL);
283
284         export_event_state(msg, EVENT_QUEUED);
285
286         /* run all events with a timeout set immediately */
287         if (msg->timeout != 0) {
288                 list_add_tail(&msg->node, &running_list);
289                 udev_event_run(msg);
290                 return;
291         }
292
293         list_add_tail(&msg->node, &exec_list);
294         run_exec_q = 1;
295 }
296
297 /* runs event and removes event from run queue when finished */
298 static int running_processes(void)
299 {
300         int f;
301         static char buf[4096];
302         int len;
303         int running;
304         const char *pos;
305
306         f = open("/proc/stat", O_RDONLY);
307         if (f == -1)
308                 return -1;
309
310         len = read(f, buf, sizeof(buf)-1);
311         close(f);
312
313         if (len <= 0)
314                 return -1;
315         else
316                 buf[len] = '\0';
317
318         pos = strstr(buf, "procs_running ");
319         if (pos == NULL)
320                 return -1;
321
322         if (sscanf(pos, "procs_running %u", &running) != 1)
323                 return -1;
324
325         return running;
326 }
327
328 /* return the number of process es in our session, count only until limit */
329 static int running_processes_in_session(pid_t session, int limit)
330 {
331         DIR *dir;
332         struct dirent *dent;
333         int running = 0;
334
335         dir = opendir("/proc");
336         if (!dir)
337                 return -1;
338
339         /* read process info from /proc */
340         for (dent = readdir(dir); dent != NULL; dent = readdir(dir)) {
341                 int f;
342                 char procdir[64];
343                 char line[256];
344                 const char *pos;
345                 char state;
346                 pid_t ppid, pgrp, sess;
347                 int len;
348
349                 if (!isdigit(dent->d_name[0]))
350                         continue;
351
352                 snprintf(procdir, sizeof(procdir), "/proc/%s/stat", dent->d_name);
353                 procdir[sizeof(procdir)-1] = '\0';
354
355                 f = open(procdir, O_RDONLY);
356                 if (f == -1)
357                         continue;
358
359                 len = read(f, line, sizeof(line)-1);
360                 close(f);
361
362                 if (len <= 0)
363                         continue;
364                 else
365                         line[len] = '\0';
366
367                 /* skip ugly program name */
368                 pos = strrchr(line, ')') + 2;
369                 if (pos == NULL)
370                         continue;
371
372                 if (sscanf(pos, "%c %d %d %d ", &state, &ppid, &pgrp, &sess) != 4)
373                         continue;
374
375                 /* count only processes in our session */
376                 if (sess != session)
377                         continue;
378
379                 /* count only running, no sleeping processes */
380                 if (state != 'R')
381                         continue;
382
383                 running++;
384                 if (limit > 0 && running >= limit)
385                         break;
386         }
387         closedir(dir);
388
389         return running;
390 }
391
392 static int compare_devpath(const char *running, const char *waiting)
393 {
394         int i;
395
396         for (i = 0; i < PATH_SIZE; i++) {
397                 /* identical device event found */
398                 if (running[i] == '\0' && waiting[i] == '\0')
399                         return 1;
400
401                 /* parent device event found */
402                 if (running[i] == '\0' && waiting[i] == '/')
403                         return 2;
404
405                 /* child device event found */
406                 if (running[i] == '/' && waiting[i] == '\0')
407                         return 3;
408
409                 /* no matching event */
410                 if (running[i] != waiting[i])
411                         break;
412         }
413
414         return 0;
415 }
416
417 /* returns still running task for the same device, its parent or its physical device */
418 static int running_with_devpath(struct uevent_msg *msg, int limit)
419 {
420         struct uevent_msg *loop_msg;
421         int childs_count = 0;
422
423         list_for_each_entry(loop_msg, &running_list, node) {
424                 if (limit && childs_count++ > limit) {
425                         dbg("%llu, maximum number (%i) of child reached", msg->seqnum, childs_count);
426                         return 1;
427                 }
428
429                 /* return running parent/child device event */
430                 if (compare_devpath(loop_msg->devpath, msg->devpath) != 0) {
431                         dbg("%llu, child device event still running %llu (%s)",
432                             msg->seqnum, loop_msg->seqnum, loop_msg->devpath);
433                         return 2;
434                 }
435
436                 /* return running physical device event */
437                 if (msg->physdevpath && msg->action && strcmp(msg->action, "add") == 0)
438                         if (compare_devpath(loop_msg->devpath, msg->physdevpath) != 0) {
439                                 dbg("%llu, physical device event still running %llu (%s)",
440                                     msg->seqnum, loop_msg->seqnum, loop_msg->devpath);
441                                 return 3;
442                         }
443         }
444
445         return 0;
446 }
447
448 /* exec queue management routine executes the events and serializes events in the same sequence */
449 static void msg_queue_manager(void)
450 {
451         struct uevent_msg *loop_msg;
452         struct uevent_msg *tmp_msg;
453         int running;
454
455         if (list_empty(&exec_list))
456                 return;
457
458         running = running_processes();
459         dbg("%d processes runnning on system", running);
460         if (running < 0)
461                 running = max_childs_running;
462
463         list_for_each_entry_safe(loop_msg, tmp_msg, &exec_list, node) {
464                 /* check running processes in our session and possibly throttle */
465                 if (running >= max_childs_running) {
466                         running = running_processes_in_session(sid, max_childs_running+10);
467                         dbg("at least %d processes running in session", running);
468                         if (running >= max_childs_running) {
469                                 dbg("delay seq %llu, too many processes already running", loop_msg->seqnum);
470                                 return;
471                         }
472                 }
473
474                 /* don't run two processes for the same devpath and wait for the parent*/
475                 if (running_with_devpath(loop_msg, max_childs)) {
476                         dbg("delay seq %llu (%s)", loop_msg->seqnum, loop_msg->devpath);
477                         continue;
478                 }
479
480                 /* move event to run list */
481                 list_move_tail(&loop_msg->node, &running_list);
482                 udev_event_run(loop_msg);
483                 running++;
484                 dbg("moved seq %llu to running list", loop_msg->seqnum);
485         }
486 }
487
488 static struct uevent_msg *get_msg_from_envbuf(const char *buf, int buf_size)
489 {
490         int bufpos;
491         int i;
492         struct uevent_msg *msg;
493         int major = 0;
494         int minor = 0;
495
496         msg = malloc(sizeof(struct uevent_msg) + buf_size);
497         if (msg == NULL)
498                 return NULL;
499         memset(msg, 0x00, sizeof(struct uevent_msg) + buf_size);
500
501         /* copy environment buffer and reconstruct envp */
502         memcpy(msg->envbuf, buf, buf_size);
503         bufpos = 0;
504         for (i = 0; (bufpos < buf_size) && (i < UEVENT_NUM_ENVP-2); i++) {
505                 int keylen;
506                 char *key;
507
508                 key = &msg->envbuf[bufpos];
509                 keylen = strlen(key);
510                 msg->envp[i] = key;
511                 bufpos += keylen + 1;
512                 dbg("add '%s' to msg.envp[%i]", msg->envp[i], i);
513
514                 /* remember some keys for further processing */
515                 if (strncmp(key, "ACTION=", 7) == 0)
516                         msg->action = &key[7];
517                 else if (strncmp(key, "DEVPATH=", 8) == 0)
518                         msg->devpath = &key[8];
519                 else if (strncmp(key, "SUBSYSTEM=", 10) == 0)
520                         msg->subsystem = &key[10];
521                 else if (strncmp(key, "SEQNUM=", 7) == 0)
522                         msg->seqnum = strtoull(&key[7], NULL, 10);
523                 else if (strncmp(key, "PHYSDEVPATH=", 12) == 0)
524                         msg->physdevpath = &key[12];
525                 else if (strncmp(key, "MAJOR=", 6) == 0)
526                         major = strtoull(&key[6], NULL, 10);
527                 else if (strncmp(key, "MINOR=", 6) == 0)
528                         minor = strtoull(&key[6], NULL, 10);
529                 else if (strncmp(key, "TIMEOUT=", 8) == 0)
530                         msg->timeout = strtoull(&key[8], NULL, 10);
531         }
532         msg->devt = makedev(major, minor);
533         msg->envp[i++] = "UDEVD_EVENT=1";
534         msg->envp[i] = NULL;
535
536         if (msg->devpath == NULL || msg->action == NULL) {
537                 info("DEVPATH or ACTION missing, ignore message");
538                 free(msg);
539                 return NULL;
540         }
541         return msg;
542 }
543
544 /* receive the udevd message from userspace */
545 static struct uevent_msg *get_udevd_msg(void)
546 {
547         static struct udevd_msg usend_msg;
548         struct uevent_msg *msg;
549         ssize_t size;
550         struct msghdr smsg;
551         struct cmsghdr *cmsg;
552         struct iovec iov;
553         struct ucred *cred;
554         char cred_msg[CMSG_SPACE(sizeof(struct ucred))];
555         int envbuf_size;
556         int *intval;
557
558         memset(&usend_msg, 0x00, sizeof(struct udevd_msg));
559         iov.iov_base = &usend_msg;
560         iov.iov_len = sizeof(struct udevd_msg);
561
562         memset(&smsg, 0x00, sizeof(struct msghdr));
563         smsg.msg_iov = &iov;
564         smsg.msg_iovlen = 1;
565         smsg.msg_control = cred_msg;
566         smsg.msg_controllen = sizeof(cred_msg);
567
568         size = recvmsg(udevd_sock, &smsg, 0);
569         if (size <  0) {
570                 if (errno != EINTR)
571                         err("unable to receive user udevd message: %s", strerror(errno));
572                 return NULL;
573         }
574         cmsg = CMSG_FIRSTHDR(&smsg);
575         cred = (struct ucred *) CMSG_DATA(cmsg);
576
577         if (cmsg == NULL || cmsg->cmsg_type != SCM_CREDENTIALS) {
578                 err("no sender credentials received, message ignored");
579                 return NULL;
580         }
581
582         if (cred->uid != 0) {
583                 err("sender uid=%i, message ignored", cred->uid);
584                 return NULL;
585         }
586
587         if (strncmp(usend_msg.magic, UDEV_MAGIC, sizeof(UDEV_MAGIC)) != 0 ) {
588                 err("message magic '%s' doesn't match, ignore it", usend_msg.magic);
589                 return NULL;
590         }
591
592         switch (usend_msg.type) {
593         case UDEVD_UEVENT_UDEVSEND:
594                 info("udevd event message received");
595                 envbuf_size = size - offsetof(struct udevd_msg, envbuf);
596                 dbg("envbuf_size=%i", envbuf_size);
597                 msg = get_msg_from_envbuf(usend_msg.envbuf, envbuf_size);
598                 if (msg == NULL)
599                         return NULL;
600                 msg->type = usend_msg.type;
601                 return msg;
602         case UDEVD_STOP_EXEC_QUEUE:
603                 info("udevd message (STOP_EXEC_QUEUE) received");
604                 stop_exec_q = 1;
605                 break;
606         case UDEVD_START_EXEC_QUEUE:
607                 info("udevd message (START_EXEC_QUEUE) received");
608                 stop_exec_q = 0;
609                 msg_queue_manager();
610                 break;
611         case UDEVD_SET_LOG_LEVEL:
612                 intval = (int *) usend_msg.envbuf;
613                 info("udevd message (SET_LOG_PRIORITY) received, udev_log_priority=%i", *intval);
614                 udev_log_priority = *intval;
615                 sprintf(udev_log, "UDEV_LOG=%i", udev_log_priority);
616                 putenv(udev_log);
617                 break;
618         case UDEVD_SET_MAX_CHILDS:
619                 intval = (int *) usend_msg.envbuf;
620                 info("udevd message (UDEVD_SET_MAX_CHILDS) received, max_childs=%i", *intval);
621                 max_childs = *intval;
622                 break;
623         case UDEVD_RELOAD_RULES:
624                 info("udevd message (RELOAD_RULES) received");
625                 reload_config = 1;
626                 break;
627         default:
628                 dbg("unknown message type");
629         }
630         return NULL;
631 }
632
633 /* receive the kernel user event message and do some sanity checks */
634 static struct uevent_msg *get_netlink_msg(void)
635 {
636         struct uevent_msg *msg;
637         int bufpos;
638         ssize_t size;
639         static char buffer[UEVENT_BUFFER_SIZE+512];
640         char *pos;
641
642         size = recv(uevent_netlink_sock, &buffer, sizeof(buffer), 0);
643         if (size <  0) {
644                 if (errno != EINTR)
645                         err("unable to receive kernel netlink message: %s", strerror(errno));
646                 return NULL;
647         }
648
649         if ((size_t)size > sizeof(buffer)-1)
650                 size = sizeof(buffer)-1;
651         buffer[size] = '\0';
652         dbg("uevent_size=%zi", size);
653
654         /* start of event payload */
655         bufpos = strlen(buffer)+1;
656         msg = get_msg_from_envbuf(&buffer[bufpos], size-bufpos);
657         if (msg == NULL)
658                 return NULL;
659         msg->type = UDEVD_UEVENT_NETLINK;
660
661         /* validate message */
662         pos = strchr(buffer, '@');
663         if (pos == NULL) {
664                 err("invalid uevent '%s'", buffer);
665                 free(msg);
666                 return NULL;
667         }
668         pos[0] = '\0';
669
670         if (msg->action == NULL) {
671                 info("no ACTION in payload found, skip event '%s'", buffer);
672                 free(msg);
673                 return NULL;
674         }
675
676         if (strcmp(msg->action, buffer) != 0) {
677                 err("ACTION in payload does not match uevent, skip event '%s'", buffer);
678                 free(msg);
679                 return NULL;
680         }
681
682         return msg;
683 }
684
685 static void asmlinkage sig_handler(int signum)
686 {
687         switch (signum) {
688                 case SIGINT:
689                 case SIGTERM:
690                         udev_exit = 1;
691                         break;
692                 case SIGCHLD:
693                         /* set flag, then write to pipe if needed */
694                         sigchilds_waiting = 1;
695                         break;
696                 case SIGHUP:
697                         reload_config = 1;
698                         break;
699         }
700
701         /* write to pipe, which will wakeup select() in our mainloop */
702         write(signal_pipe[WRITE_END], "", 1);
703 }
704
705 static void udev_done(int pid, int exitstatus)
706 {
707         /* find msg associated with pid and delete it */
708         struct uevent_msg *msg;
709
710         list_for_each_entry(msg, &running_list, node) {
711                 if (msg->pid == pid) {
712                         info("seq %llu, pid [%d] exit with %i, %ld seconds old", msg->seqnum, msg->pid,
713                              exitstatus, time(NULL) - msg->queue_time);
714                         msg->exitstatus = exitstatus;
715                         msg_queue_delete(msg);
716
717                         /* there may be events waiting with the same devpath */
718                         run_exec_q = 1;
719                         return;
720                 }
721         }
722 }
723
724 static void reap_sigchilds(void)
725 {
726         pid_t pid;
727         int status;
728
729         while (1) {
730                 pid = waitpid(-1, &status, WNOHANG);
731                 if (pid <= 0)
732                         break;
733                 if (WIFEXITED(status))
734                         status = WEXITSTATUS(status);
735                 else if (WIFSIGNALED(status))
736                         status = WTERMSIG(status) + 128;
737                 else
738                         status = 0;
739                 udev_done(pid, status);
740         }
741 }
742
743 static int init_udevd_socket(void)
744 {
745         struct sockaddr_un saddr;
746         const int buffersize = 16 * 1024 * 1024;
747         socklen_t addrlen;
748         const int feature_on = 1;
749         int retval;
750
751         memset(&saddr, 0x00, sizeof(saddr));
752         saddr.sun_family = AF_LOCAL;
753         /* use abstract namespace for socket path */
754         strcpy(&saddr.sun_path[1], UDEVD_SOCK_PATH);
755         addrlen = offsetof(struct sockaddr_un, sun_path) + strlen(saddr.sun_path+1) + 1;
756
757         udevd_sock = socket(AF_LOCAL, SOCK_DGRAM, 0);
758         if (udevd_sock == -1) {
759                 err("error getting socket: %s", strerror(errno));
760                 return -1;
761         }
762
763         /* set receive buffersize */
764         setsockopt(udevd_sock, SOL_SOCKET, SO_RCVBUFFORCE, &buffersize, sizeof(buffersize));
765
766         /* the bind takes care of ensuring only one copy running */
767         retval = bind(udevd_sock, (struct sockaddr *) &saddr, addrlen);
768         if (retval < 0) {
769                 err("bind failed: %s", strerror(errno));
770                 return -1;
771         }
772
773         /* enable receiving of the sender credentials */
774         setsockopt(udevd_sock, SOL_SOCKET, SO_PASSCRED, &feature_on, sizeof(feature_on));
775
776         return 0;
777 }
778
779 static int init_uevent_netlink_sock(void)
780 {
781         struct sockaddr_nl snl;
782         const int buffersize = 16 * 1024 * 1024;
783         int retval;
784
785         memset(&snl, 0x00, sizeof(struct sockaddr_nl));
786         snl.nl_family = AF_NETLINK;
787         snl.nl_pid = getpid();
788         snl.nl_groups = 0xffffffff;
789
790         uevent_netlink_sock = socket(PF_NETLINK, SOCK_DGRAM, NETLINK_KOBJECT_UEVENT);
791         if (uevent_netlink_sock == -1) {
792                 err("error getting socket: %s", strerror(errno));
793                 return -1;
794         }
795
796         /* set receive buffersize */
797         setsockopt(uevent_netlink_sock, SOL_SOCKET, SO_RCVBUFFORCE, &buffersize, sizeof(buffersize));
798
799         retval = bind(uevent_netlink_sock, (struct sockaddr *) &snl, sizeof(struct sockaddr_nl));
800         if (retval < 0) {
801                 err("bind failed: %s", strerror(errno));
802                 close(uevent_netlink_sock);
803                 uevent_netlink_sock = -1;
804                 return -1;
805         }
806         return 0;
807 }
808
809 int main(int argc, char *argv[], char *envp[])
810 {
811         int retval;
812         int fd;
813         struct sigaction act;
814         fd_set readfds;
815         const char *value;
816         int daemonize = 0;
817         int i;
818         int rc = 0;
819         int maxfd;
820
821         /* redirect std fd's, if the kernel forks us, we don't have them at all */
822         fd = open("/dev/null", O_RDWR);
823         if (fd >= 0) {
824                 if (fd != STDIN_FILENO)
825                         dup2(fd, STDIN_FILENO);
826                 if (fd != STDOUT_FILENO)
827                         dup2(fd, STDOUT_FILENO);
828                 if (fd != STDERR_FILENO)
829                         dup2(fd, STDERR_FILENO);
830                 if (fd > STDERR_FILENO)
831                         close(fd);
832         }
833
834         logging_init("udevd");
835         if (fd < 0)
836                 err("fatal, could not open /dev/null: %s", strerror(errno));
837
838         udev_config_init();
839         dbg("version %s", UDEV_VERSION);
840
841         if (getuid() != 0) {
842                 err("need to be root, exit");
843                 goto exit;
844         }
845
846         /* parse commandline options */
847         for (i = 1 ; i < argc; i++) {
848                 char *arg = argv[i];
849                 if (strcmp(arg, "--daemon") == 0 || strcmp(arg, "-d") == 0) {
850                         info("will daemonize");
851                         daemonize = 1;
852                 }
853                 if (strcmp(arg, "--stop-exec-queue") == 0) {
854                         info("will not execute events until START_EXEC_QUEUE is received");
855                         stop_exec_q = 1;
856                 }
857         }
858
859         /* init sockets to receive events */
860         if (init_udevd_socket() < 0) {
861                 if (errno == EADDRINUSE) {
862                         err("another udevd running, exit");
863                         rc = 1;
864                 } else {
865                         err("error initializing udevd socket: %s", strerror(errno));
866                         rc = 2;
867                 }
868                 goto exit;
869         }
870
871         if (init_uevent_netlink_sock() < 0) {
872                 err("uevent socket not available");
873                 rc = 3;
874                 goto exit;
875         }
876
877         /* parse the rules and keep it in memory */
878         sysfs_init();
879         udev_rules_init(&rules, 1);
880
881         if (daemonize) {
882                 pid_t pid;
883
884                 pid = fork();
885                 switch (pid) {
886                 case 0:
887                         dbg("daemonized fork running");
888                         break;
889                 case -1:
890                         err("fork of daemon failed: %s", strerror(errno));
891                         rc = 4;
892                         goto exit;
893                 default:
894                         dbg("child [%u] running, parent exits", pid);
895                         goto exit;
896                 }
897         }
898
899         /* set scheduling priority for the daemon */
900         setpriority(PRIO_PROCESS, 0, UDEVD_PRIORITY);
901
902         chdir("/");
903         umask(022);
904
905         /* become session leader */
906         sid = setsid();
907         dbg("our session is %d", sid);
908
909         /* OOM_DISABLE == -17 */
910         fd = open("/proc/self/oom_adj", O_RDWR);
911         if (fd < 0)
912                 err("error disabling OOM: %s", strerror(errno));
913         else {
914                 write(fd, "-17", 3);
915                 close(fd);
916         }
917
918         /* setup signal handler pipe */
919         retval = pipe(signal_pipe);
920         if (retval < 0) {
921                 err("error getting pipes: %s", strerror(errno));
922                 goto exit;
923         }
924
925         retval = fcntl(signal_pipe[READ_END], F_GETFL, 0);
926         if (retval < 0) {
927                 err("error fcntl on read pipe: %s", strerror(errno));
928                 goto exit;
929         }
930         retval = fcntl(signal_pipe[READ_END], F_SETFL, retval | O_NONBLOCK);
931         if (retval < 0) {
932                 err("error fcntl on read pipe: %s", strerror(errno));
933                 goto exit;
934         }
935
936         retval = fcntl(signal_pipe[WRITE_END], F_GETFL, 0);
937         if (retval < 0) {
938                 err("error fcntl on write pipe: %s", strerror(errno));
939                 goto exit;
940         }
941         retval = fcntl(signal_pipe[WRITE_END], F_SETFL, retval | O_NONBLOCK);
942         if (retval < 0) {
943                 err("error fcntl on write pipe: %s", strerror(errno));
944                 goto exit;
945         }
946
947         /* set signal handlers */
948         memset(&act, 0x00, sizeof(struct sigaction));
949         act.sa_handler = (void (*)(int)) sig_handler;
950         sigemptyset(&act.sa_mask);
951         act.sa_flags = SA_RESTART;
952         sigaction(SIGINT, &act, NULL);
953         sigaction(SIGTERM, &act, NULL);
954         sigaction(SIGCHLD, &act, NULL);
955         sigaction(SIGHUP, &act, NULL);
956
957         /* watch rules directory */
958         inotify_fd = inotify_init();
959         if (inotify_fd > 0)
960                 inotify_add_watch(inotify_fd, udev_rules_filename, IN_CREATE | IN_DELETE | IN_MOVE | IN_CLOSE_WRITE);
961
962         /* maximum limit of forked childs */
963         value = getenv("UDEVD_MAX_CHILDS");
964         if (value)
965                 max_childs = strtoul(value, NULL, 10);
966         else
967                 max_childs = UDEVD_MAX_CHILDS;
968         info("initialize max_childs to %u", max_childs);
969
970         /* start to throttle forking if maximum number of _running_ childs is reached */
971         value = getenv("UDEVD_MAX_CHILDS_RUNNING");
972         if (value)
973                 max_childs_running = strtoull(value, NULL, 10);
974         else
975                 max_childs_running = UDEVD_MAX_CHILDS_RUNNING;
976         info("initialize max_childs_running to %u", max_childs_running);
977
978         /* clear environment for forked event processes */
979         clearenv();
980
981         /* export log_priority , as called programs may want to follow that setting */
982         sprintf(udev_log, "UDEV_LOG=%i", udev_log_priority);
983         putenv(udev_log);
984
985         maxfd = udevd_sock;
986         maxfd = UDEV_MAX(maxfd, uevent_netlink_sock);
987         maxfd = UDEV_MAX(maxfd, signal_pipe[READ_END]);
988         maxfd = UDEV_MAX(maxfd, inotify_fd);
989
990         while (!udev_exit) {
991                 struct uevent_msg *msg;
992                 int fdcount;
993
994                 FD_ZERO(&readfds);
995                 FD_SET(signal_pipe[READ_END], &readfds);
996                 FD_SET(udevd_sock, &readfds);
997                 FD_SET(uevent_netlink_sock, &readfds);
998                 if (inotify_fd > 0)
999                         FD_SET(inotify_fd, &readfds);
1000
1001                 fdcount = select(maxfd+1, &readfds, NULL, NULL, NULL);
1002                 if (fdcount < 0) {
1003                         if (errno != EINTR)
1004                                 err("error in select: %s", strerror(errno));
1005                         continue;
1006                 }
1007
1008                 /* get user socket message */
1009                 if (FD_ISSET(udevd_sock, &readfds)) {
1010                         msg = get_udevd_msg();
1011                         if (msg)
1012                                 msg_queue_insert(msg);
1013                 }
1014
1015                 /* get kernel netlink message */
1016                 if (FD_ISSET(uevent_netlink_sock, &readfds)) {
1017                         msg = get_netlink_msg();
1018                         if (msg)
1019                                 msg_queue_insert(msg);
1020                 }
1021
1022                 /* received a signal, clear our notification pipe */
1023                 if (FD_ISSET(signal_pipe[READ_END], &readfds)) {
1024                         char buf[256];
1025
1026                         read(signal_pipe[READ_END], &buf, sizeof(buf));
1027                 }
1028
1029                 /* rules directory inotify watch */
1030                 if ((inotify_fd > 0) && FD_ISSET(inotify_fd, &readfds)) {
1031                         int nbytes;
1032
1033                         /* discard all possible events, we can just reload the config */
1034                         if ((ioctl(inotify_fd, FIONREAD, &nbytes) == 0) && nbytes) {
1035                                 char *buf;
1036
1037                                 reload_config = 1;
1038                                 buf = malloc(nbytes);
1039                                 if (!buf) {
1040                                         err("error getting buffer for inotify, disable watching");
1041                                         close(inotify_fd);
1042                                         inotify_fd = -1;
1043                                 }
1044                                 read(inotify_fd, buf, nbytes);
1045                                 free(buf);
1046                         }
1047                 }
1048
1049                 /* rules changed, set by inotify or a signal*/
1050                 if (reload_config) {
1051                         reload_config = 0;
1052                         udev_rules_cleanup(&rules);
1053                         udev_rules_init(&rules, 1);
1054                 }
1055
1056                 /* forked child has returned */
1057                 if (sigchilds_waiting) {
1058                         sigchilds_waiting = 0;
1059                         reap_sigchilds();
1060                 }
1061
1062                 if (run_exec_q) {
1063                         run_exec_q = 0;
1064                         if (!stop_exec_q)
1065                                 msg_queue_manager();
1066                 }
1067         }
1068
1069 exit:
1070         udev_rules_cleanup(&rules);
1071         sysfs_cleanup();
1072
1073         if (signal_pipe[READ_END] > 0)
1074                 close(signal_pipe[READ_END]);
1075         if (signal_pipe[WRITE_END] > 0)
1076                 close(signal_pipe[WRITE_END]);
1077
1078         if (udevd_sock > 0)
1079                 close(udevd_sock);
1080         if (inotify_fd > 0)
1081                 close(inotify_fd);
1082         if (uevent_netlink_sock > 0)
1083                 close(uevent_netlink_sock);
1084
1085         logging_close();
1086
1087         return rc;
1088 }