chiark / gitweb /
Sync up the Debian rules files
[elogind.git] / udevd.c
1 /*
2  * udevd.c - hotplug event 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 <sys/select.h>
34 #include <sys/wait.h>
35 #include <sys/time.h>
36 #include <sys/types.h>
37 #include <sys/socket.h>
38 #include <sys/un.h>
39 #include <sys/sysinfo.h>
40 #include <sys/stat.h>
41 #include <linux/netlink.h>
42
43 #include "list.h"
44 #include "udev_libc_wrapper.h"
45 #include "udev.h"
46 #include "udev_version.h"
47 #include "udev_utils.h"
48 #include "udevd.h"
49 #include "logging.h"
50
51 #ifndef NETLINK_KOBJECT_UEVENT
52 #define NETLINK_KOBJECT_UEVENT 15
53 #endif
54
55 /* global variables*/
56 static int udevd_sock;
57 static int uevent_netlink_sock;
58 static pid_t sid;
59
60 static int pipefds[2];
61 static volatile int sigchilds_waiting;
62 static volatile int run_msg_q;
63 static volatile int sig_flag;
64 static int init_phase = 1;
65 static int run_exec_q;
66 static int stop_exec_q;
67
68 static LIST_HEAD(msg_list);
69 static LIST_HEAD(exec_list);
70 static LIST_HEAD(running_list);
71
72 static void exec_queue_manager(void);
73 static void msg_queue_manager(void);
74 static void user_sighandler(void);
75 static void reap_sigchilds(void);
76
77 static char *udev_bin;
78 static unsigned long long expected_seqnum;
79 static int event_timeout;
80 static int max_childs;
81 static int max_childs_running;
82
83
84 #ifdef USE_LOG
85 void log_message (int priority, const char *format, ...)
86 {
87         va_list args;
88
89         if (priority > udev_log_priority)
90                 return;
91
92         va_start(args, format);
93         vsyslog(priority, format, args);
94         va_end(args);
95 }
96 #endif
97
98 static void msg_dump_queue(void)
99 {
100 #ifdef DEBUG
101         struct uevent_msg *msg;
102
103         list_for_each_entry(msg, &msg_list, node)
104                 dbg("sequence %llu in queue", msg->seqnum);
105 #endif
106 }
107
108 static void msg_queue_delete(struct uevent_msg *msg)
109 {
110         list_del(&msg->node);
111         free(msg);
112 }
113
114 /* orders the message in the queue by sequence number */
115 static void msg_queue_insert(struct uevent_msg *msg)
116 {
117         struct uevent_msg *loop_msg;
118         struct sysinfo info;
119
120         if (msg->seqnum == 0) {
121                 dbg("no SEQNUM, move straight to the exec queue");
122                 list_add(&msg->node, &exec_list);
123                 run_exec_q = 1;
124                 return;
125         }
126
127         /* store timestamp of queuing */
128         sysinfo(&info);
129         msg->queue_time = info.uptime;
130
131         /* with the first event we provide a phase of shorter timeout */
132         if (init_phase) {
133                 static long init_time;
134
135                 if (init_time == 0)
136                         init_time = info.uptime;
137                 if (info.uptime - init_time >= UDEVD_INIT_TIME)
138                         init_phase = 0;
139         }
140
141         /* don't delay messages with timeout set */
142         if (msg->timeout) {
143                 dbg("move seq %llu with timeout %u to exec queue", msg->seqnum, msg->timeout);
144                 list_add(&msg->node, &exec_list);
145                 run_exec_q = 1;
146                 return;
147         }
148
149         /* sort message by sequence number into list */
150         list_for_each_entry_reverse(loop_msg, &msg_list, node) {
151                 if (loop_msg->seqnum < msg->seqnum)
152                         break;
153
154                 if (loop_msg->seqnum == msg->seqnum) {
155                         dbg("ignoring duplicate message seq %llu", msg->seqnum);
156                         free(msg);
157                         return;
158                 }
159         }
160         list_add(&msg->node, &loop_msg->node);
161         info("seq %llu queued, devpath '%s'", msg->seqnum, msg->devpath);
162
163         /* run msg queue manager */
164         run_msg_q = 1;
165
166         return;
167 }
168
169 /* forks event and removes event from run queue when finished */
170 static void execute_udev(struct uevent_msg *msg)
171 {
172         char *const argv[] = { "udev", msg->subsystem, NULL };
173         pid_t pid;
174         struct sysinfo info;
175
176         pid = fork();
177         switch (pid) {
178         case 0:
179                 /* child */
180                 if (uevent_netlink_sock != -1)
181                         close(uevent_netlink_sock);
182                 close(udevd_sock);
183                 logging_close();
184
185                 setpriority(PRIO_PROCESS, 0, UDEV_PRIORITY);
186                 execve(udev_bin, argv, msg->envp);
187                 err("exec of child failed");
188                 _exit(1);
189                 break;
190         case -1:
191                 err("fork of child failed");
192                 msg_queue_delete(msg);
193                 break;
194         default:
195                 /* get SIGCHLD in main loop */
196                 sysinfo(&info);
197                 info("seq %llu forked, pid %d, %ld seconds old",
198                      msg->seqnum, pid, info.uptime - msg->queue_time);
199                 msg->pid = pid;
200         }
201 }
202
203 static int running_processes(void)
204 {
205         int f;
206         static char buf[4096];
207         int len;
208         int running;
209         const char *pos;
210
211         f = open("/proc/stat", O_RDONLY);
212         if (f == -1)
213                 return -1;
214
215         len = read(f, buf, sizeof(buf));
216         close(f);
217
218         if (len <= 0)
219                 return -1;
220         else
221                 buf[len] = '\0';
222
223         pos = strstr(buf, "procs_running ");
224         if (pos == NULL)
225                 return -1;
226
227         if (sscanf(pos, "procs_running %u", &running) != 1)
228                 return -1;
229
230         return running;
231 }
232
233 /* return the number of process es in our session, count only until limit */
234 static int running_processes_in_session(pid_t session, int limit)
235 {
236         DIR *dir;
237         struct dirent *dent;
238         int running = 0;
239
240         dir = opendir("/proc");
241         if (!dir)
242                 return -1;
243
244         /* read process info from /proc */
245         for (dent = readdir(dir); dent != NULL; dent = readdir(dir)) {
246                 int f;
247                 char procdir[64];
248                 char line[256];
249                 const char *pos;
250                 char state;
251                 pid_t ppid, pgrp, sess;
252                 int len;
253
254                 if (!isdigit(dent->d_name[0]))
255                         continue;
256
257                 snprintf(procdir, sizeof(procdir), "/proc/%s/stat", dent->d_name);
258                 procdir[sizeof(procdir)-1] = '\0';
259
260                 f = open(procdir, O_RDONLY);
261                 if (f == -1)
262                         continue;
263
264                 len = read(f, line, sizeof(line));
265                 close(f);
266
267                 if (len <= 0)
268                         continue;
269                 else
270                         line[len] = '\0';
271
272                 /* skip ugly program name */
273                 pos = strrchr(line, ')') + 2;
274                 if (pos == NULL)
275                         continue;
276
277                 if (sscanf(pos, "%c %d %d %d ", &state, &ppid, &pgrp, &sess) != 4)
278                         continue;
279
280                 /* count only processes in our session */
281                 if (sess != session)
282                         continue;
283
284                 /* count only running, no sleeping processes */
285                 if (state != 'R')
286                         continue;
287
288                 running++;
289                 if (limit > 0 && running >= limit)
290                         break;
291         }
292         closedir(dir);
293
294         return running;
295 }
296
297 static int compare_devpath(const char *running, const char *waiting)
298 {
299         int i;
300
301         for (i = 0; i < PATH_SIZE; i++) {
302                 /* identical device event found */
303                 if (running[i] == '\0' && waiting[i] == '\0')
304                         return 1;
305
306                 /* parent device event found */
307                 if (running[i] == '\0' && waiting[i] == '/')
308                         return 2;
309
310                 /* child device event found */
311                 if (running[i] == '/' && waiting[i] == '\0')
312                         return 3;
313
314                 /* no matching event */
315                 if (running[i] != waiting[i])
316                         break;
317         }
318
319         return 0;
320 }
321
322 /* returns still running task for the same device, its parent or its physical device */
323 static int running_with_devpath(struct uevent_msg *msg, int limit)
324 {
325         struct uevent_msg *loop_msg;
326         int childs_count = 0;
327
328         if (msg->devpath == NULL)
329                 return 0;
330
331         /* skip any events with a timeout set */
332         if (msg->timeout != 0)
333                 return 0;
334
335         list_for_each_entry(loop_msg, &running_list, node) {
336                 if (limit && childs_count++ > limit) {
337                         dbg("%llu, maximum number (%i) of child reached", msg->seqnum, childs_count);
338                         return 1;
339                 }
340                 if (loop_msg->devpath == NULL)
341                         continue;
342
343                 /* return running parent/child device event */
344                 if (compare_devpath(loop_msg->devpath, msg->devpath) != 0) {
345                         dbg("%llu, child device event still running %llu (%s)",
346                             msg->seqnum, loop_msg->seqnum, loop_msg->devpath);
347                         return 2;
348                 }
349
350                 /* return running physical device event */
351                 if (msg->physdevpath && msg->action && strcmp(msg->action, "add") == 0)
352                         if (compare_devpath(loop_msg->devpath, msg->physdevpath) != 0) {
353                                 dbg("%llu, physical device event still running %llu (%s)",
354                                     msg->seqnum, loop_msg->seqnum, loop_msg->devpath);
355                                 return 3;
356                         }
357         }
358
359         return 0;
360 }
361
362 /* exec queue management routine executes the events and serializes events in the same sequence */
363 static void exec_queue_manager(void)
364 {
365         struct uevent_msg *loop_msg;
366         struct uevent_msg *tmp_msg;
367         int running;
368
369         if (list_empty(&exec_list))
370                 return;
371
372         running = running_processes();
373         dbg("%d processes runnning on system", running);
374         if (running < 0)
375                 running = max_childs_running;
376
377         list_for_each_entry_safe(loop_msg, tmp_msg, &exec_list, node) {
378                 /* check running processes in our session and possibly throttle */
379                 if (running >= max_childs_running) {
380                         running = running_processes_in_session(sid, max_childs_running+10);
381                         dbg("at least %d processes running in session", running);
382                         if (running >= max_childs_running) {
383                                 dbg("delay seq %llu, cause too many processes already running",
384                                     loop_msg->seqnum);
385                                 return;
386                         }
387                 }
388
389                 if (running_with_devpath(loop_msg, max_childs) == 0) {
390                         /* move event to run list */
391                         list_move_tail(&loop_msg->node, &running_list);
392                         execute_udev(loop_msg);
393                         running++;
394                         dbg("moved seq %llu to running list", loop_msg->seqnum);
395                 } else
396                         dbg("delay seq %llu (%s)", loop_msg->seqnum, loop_msg->devpath);
397         }
398 }
399
400 static void msg_move_exec(struct uevent_msg *msg)
401 {
402         list_move_tail(&msg->node, &exec_list);
403         run_exec_q = 1;
404         expected_seqnum = msg->seqnum+1;
405         dbg("moved seq %llu to exec, next expected is %llu",
406                 msg->seqnum, expected_seqnum);
407 }
408
409 /* msg queue management routine handles the timeouts and dispatches the events */
410 static void msg_queue_manager(void)
411 {
412         struct uevent_msg *loop_msg;
413         struct uevent_msg *tmp_msg;
414         struct sysinfo info;
415         long msg_age = 0;
416         int timeout = event_timeout;
417
418         dbg("msg queue manager, next expected is %llu", expected_seqnum);
419 recheck:
420         sysinfo(&info);
421         list_for_each_entry_safe(loop_msg, tmp_msg, &msg_list, node) {
422                 /* move event with expected sequence to the exec list */
423                 if (loop_msg->seqnum == expected_seqnum) {
424                         msg_move_exec(loop_msg);
425                         continue;
426                 }
427
428                 /* limit timeout during initialization phase */
429                 if (init_phase) {
430                         timeout = UDEVD_INIT_EVENT_TIMEOUT;
431                         dbg("initialization phase, limit timeout to %i seconds", UDEVD_INIT_EVENT_TIMEOUT);
432                 }
433
434                 /* move event with expired timeout to the exec list */
435                 msg_age = info.uptime - loop_msg->queue_time;
436                 dbg("seq %llu is %li seconds old", loop_msg->seqnum, msg_age);
437                 if (msg_age >= timeout) {
438                         msg_move_exec(loop_msg);
439                         goto recheck;
440                 } else {
441                         break;
442                 }
443         }
444
445         msg_dump_queue();
446
447         /* set timeout for remaining queued events */
448         if (list_empty(&msg_list) == 0) {
449                 struct itimerval itv = {{0, 0}, {timeout - msg_age, 0}};
450                 dbg("next event expires in %li seconds", timeout - msg_age);
451                 setitimer(ITIMER_REAL, &itv, NULL);
452         }
453 }
454
455 static struct uevent_msg *get_msg_from_envbuf(const char *buf, int buf_size)
456 {
457         int bufpos;
458         int i;
459         struct uevent_msg *msg;
460         int major = 0;
461         int minor = 0;
462
463         msg = malloc(sizeof(struct uevent_msg) + buf_size);
464         if (msg == NULL)
465                 return NULL;
466         memset(msg, 0x00, sizeof(struct uevent_msg) + buf_size);
467
468         /* copy environment buffer and reconstruct envp */
469         memcpy(msg->envbuf, buf, buf_size);
470         bufpos = 0;
471         for (i = 0; (bufpos < buf_size) && (i < UEVENT_NUM_ENVP-2); i++) {
472                 int keylen;
473                 char *key;
474
475                 key = &msg->envbuf[bufpos];
476                 keylen = strlen(key);
477                 msg->envp[i] = key;
478                 bufpos += keylen + 1;
479                 dbg("add '%s' to msg.envp[%i]", msg->envp[i], i);
480
481                 /* remember some keys for further processing */
482                 if (strncmp(key, "ACTION=", 7) == 0)
483                         msg->action = &key[7];
484                 else if (strncmp(key, "DEVPATH=", 8) == 0)
485                         msg->devpath = &key[8];
486                 else if (strncmp(key, "SUBSYSTEM=", 10) == 0)
487                         msg->subsystem = &key[10];
488                 else if (strncmp(key, "SEQNUM=", 7) == 0)
489                         msg->seqnum = strtoull(&key[7], NULL, 10);
490                 else if (strncmp(key, "PHYSDEVPATH=", 12) == 0)
491                         msg->physdevpath = &key[12];
492                 else if (strncmp(key, "MAJOR=", 6) == 0)
493                         major = strtoull(&key[6], NULL, 10);
494                 else if (strncmp(key, "MINOR=", 6) == 0)
495                         minor = strtoull(&key[6], NULL, 10);
496                 else if (strncmp(key, "TIMEOUT=", 8) == 0)
497                         msg->timeout = strtoull(&key[8], NULL, 10);
498         }
499         msg->devt = makedev(major, minor);
500         msg->envp[i++] = "UDEVD_EVENT=1";
501         msg->envp[i] = NULL;
502
503         return msg;
504 }
505
506 /* receive the udevd message from userspace */
507 static struct uevent_msg *get_udevd_msg(void)
508 {
509         static struct udevd_msg usend_msg;
510         struct uevent_msg *msg;
511         ssize_t size;
512         struct msghdr smsg;
513         struct cmsghdr *cmsg;
514         struct iovec iov;
515         struct ucred *cred;
516         char cred_msg[CMSG_SPACE(sizeof(struct ucred))];
517         int envbuf_size;
518         int *intval;
519
520         memset(&usend_msg, 0x00, sizeof(struct udevd_msg));
521         iov.iov_base = &usend_msg;
522         iov.iov_len = sizeof(struct udevd_msg);
523
524         memset(&smsg, 0x00, sizeof(struct msghdr));
525         smsg.msg_iov = &iov;
526         smsg.msg_iovlen = 1;
527         smsg.msg_control = cred_msg;
528         smsg.msg_controllen = sizeof(cred_msg);
529
530         size = recvmsg(udevd_sock, &smsg, 0);
531         if (size <  0) {
532                 if (errno != EINTR)
533                         dbg("unable to receive udevd message");
534                 return NULL;
535         }
536         cmsg = CMSG_FIRSTHDR(&smsg);
537         cred = (struct ucred *) CMSG_DATA(cmsg);
538
539         if (cmsg == NULL || cmsg->cmsg_type != SCM_CREDENTIALS) {
540                 info("no sender credentials received, message ignored");
541                 return NULL;
542         }
543
544         if (cred->uid != 0) {
545                 info("sender uid=%i, message ignored", cred->uid);
546                 return NULL;
547         }
548
549         if (strncmp(usend_msg.magic, UDEV_MAGIC, sizeof(UDEV_MAGIC)) != 0 ) {
550                 info("message magic '%s' doesn't match, ignore it", usend_msg.magic);
551                 return NULL;
552         }
553
554         switch (usend_msg.type) {
555         case UDEVD_UEVENT_UDEVSEND:
556         case UDEVD_UEVENT_INITSEND:
557                 info("udevd event message received");
558                 envbuf_size = size - offsetof(struct udevd_msg, envbuf);
559                 dbg("envbuf_size=%i", envbuf_size);
560                 msg = get_msg_from_envbuf(usend_msg.envbuf, envbuf_size);
561                 if (msg == NULL)
562                         return NULL;
563                 msg->type = usend_msg.type;
564                 return msg;
565         case UDEVD_STOP_EXEC_QUEUE:
566                 info("udevd message (STOP_EXEC_QUEUE) received");
567                 stop_exec_q = 1;
568                 break;
569         case UDEVD_START_EXEC_QUEUE:
570                 info("udevd message (START_EXEC_QUEUE) received");
571                 stop_exec_q = 0;
572                 exec_queue_manager();
573                 break;
574         case UDEVD_SET_LOG_LEVEL:
575                 intval = (int *) usend_msg.envbuf;
576                 info("udevd message (SET_LOG_PRIORITY) received, udev_log_priority=%i", *intval);
577                 udev_log_priority = *intval;
578                 break;
579         case UDEVD_SET_MAX_CHILDS:
580                 intval = (int *) usend_msg.envbuf;
581                 info("udevd message (UDEVD_SET_MAX_CHILDS) received, max_childs=%i", *intval);
582                 max_childs = *intval;
583                 break;
584         default:
585                 dbg("unknown message type");
586         }
587         return NULL;
588 }
589
590 /* receive the kernel user event message and do some sanity checks */
591 static struct uevent_msg *get_netlink_msg(void)
592 {
593         struct uevent_msg *msg;
594         int bufpos;
595         ssize_t size;
596         static char buffer[UEVENT_BUFFER_SIZE + 512];
597         char *pos;
598
599         size = recv(uevent_netlink_sock, &buffer, sizeof(buffer), 0);
600         if (size <  0) {
601                 if (errno != EINTR)
602                         dbg("unable to receive udevd message");
603                 return NULL;
604         }
605
606         if ((size_t)size > sizeof(buffer)-1)
607                 size = sizeof(buffer)-1;
608         buffer[size] = '\0';
609         dbg("uevent_size=%zi", size);
610
611         /* start of event payload */
612         bufpos = strlen(buffer)+1;
613         msg = get_msg_from_envbuf(&buffer[bufpos], size-bufpos);
614         if (msg == NULL)
615                 return NULL;
616         msg->type = UDEVD_UEVENT_NETLINK;
617
618         /* validate message */
619         pos = strchr(buffer, '@');
620         if (pos == NULL) {
621                 dbg("invalid uevent '%s'", buffer);
622                 free(msg);
623                 return NULL;
624         }
625         pos[0] = '\0';
626
627         if (msg->action == NULL) {
628                 dbg("no ACTION in payload found, skip event '%s'", buffer);
629                 free(msg);
630                 return NULL;
631         }
632
633         if (strcmp(msg->action, buffer) != 0) {
634                 dbg("ACTION in payload does not match uevent, skip event '%s'", buffer);
635                 free(msg);
636                 return NULL;
637         }
638
639         return msg;
640 }
641
642 static void asmlinkage sig_handler(int signum)
643 {
644         int rc;
645
646         switch (signum) {
647                 case SIGINT:
648                 case SIGTERM:
649                         exit(20 + signum);
650                         break;
651                 case SIGALRM:
652                         /* set flag, then write to pipe if needed */
653                         run_msg_q = 1;
654                         goto do_write;
655                         break;
656                 case SIGCHLD:
657                         /* set flag, then write to pipe if needed */
658                         sigchilds_waiting = 1;
659                         goto do_write;
660                         break;
661         }
662
663 do_write:
664         /* if pipe is empty, write to pipe to force select to return
665          * immediately when it gets called
666          */
667         if (!sig_flag) {
668                 rc = write(pipefds[1],&signum,sizeof(signum));
669                 if (rc >= 0)
670                         sig_flag = 1;
671         }
672 }
673
674 static void udev_done(int pid)
675 {
676         /* find msg associated with pid and delete it */
677         struct uevent_msg *msg;
678         struct sysinfo info;
679
680         list_for_each_entry(msg, &running_list, node) {
681                 if (msg->pid == pid) {
682                         sysinfo(&info);
683                         info("seq %llu exit, %ld seconds old", msg->seqnum, info.uptime - msg->queue_time);
684                         msg_queue_delete(msg);
685
686                         /* we want to run the exec queue manager since there may
687                          * be events waiting with the devpath of the one that
688                          * just finished
689                          */
690                         run_exec_q = 1;
691                         return;
692                 }
693         }
694 }
695
696 static void reap_sigchilds(void)
697 {
698         while(1) {
699                 int pid = waitpid(-1, NULL, WNOHANG);
700                 if ((pid == -1) || (pid == 0))
701                         break;
702                 udev_done(pid);
703         }
704 }
705
706 /* just read everything from the pipe and clear the flag,
707  * the flags was set in the signal handler
708  */
709 static void user_sighandler(void)
710 {
711         int sig;
712
713         while(1) {
714                 int rc = read(pipefds[0], &sig, sizeof(sig));
715                 if (rc < 0)
716                         break;
717
718                 sig_flag = 0;
719         }
720 }
721
722 static int init_udevd_socket(void)
723 {
724         struct sockaddr_un saddr;
725         socklen_t addrlen;
726         const int feature_on = 1;
727         int retval;
728
729         memset(&saddr, 0x00, sizeof(saddr));
730         saddr.sun_family = AF_LOCAL;
731         /* use abstract namespace for socket path */
732         strcpy(&saddr.sun_path[1], UDEVD_SOCK_PATH);
733         addrlen = offsetof(struct sockaddr_un, sun_path) + strlen(saddr.sun_path+1) + 1;
734
735         udevd_sock = socket(AF_LOCAL, SOCK_DGRAM, 0);
736         if (udevd_sock == -1) {
737                 err("error getting socket, %s", strerror(errno));
738                 return -1;
739         }
740
741         /* the bind takes care of ensuring only one copy running */
742         retval = bind(udevd_sock, (struct sockaddr *) &saddr, addrlen);
743         if (retval < 0) {
744                 err("bind failed, %s", strerror(errno));
745                 close(udevd_sock);
746                 return -1;
747         }
748
749         /* enable receiving of the sender credentials */
750         setsockopt(udevd_sock, SOL_SOCKET, SO_PASSCRED, &feature_on, sizeof(feature_on));
751
752         return 0;
753 }
754
755 static int init_uevent_netlink_sock(void)
756 {
757         struct sockaddr_nl snl;
758         int retval;
759
760         memset(&snl, 0x00, sizeof(struct sockaddr_nl));
761         snl.nl_family = AF_NETLINK;
762         snl.nl_pid = getpid();
763         snl.nl_groups = 0xffffffff;
764
765         uevent_netlink_sock = socket(PF_NETLINK, SOCK_DGRAM, NETLINK_KOBJECT_UEVENT);
766         if (uevent_netlink_sock == -1) {
767                 dbg("error getting socket, %s", strerror(errno));
768                 return -1;
769         }
770
771         retval = bind(uevent_netlink_sock, (struct sockaddr *) &snl,
772                       sizeof(struct sockaddr_nl));
773         if (retval < 0) {
774                 dbg("bind failed, %s", strerror(errno));
775                 close(uevent_netlink_sock);
776                 uevent_netlink_sock = -1;
777                 return -1;
778         }
779
780         return 0;
781 }
782
783 int main(int argc, char *argv[], char *envp[])
784 {
785         int maxsockplus;
786         int retval;
787         int fd;
788         struct sigaction act;
789         fd_set readfds;
790         const char *value;
791         int uevent_netlink_active = 0;
792         int daemonize = 0;
793         int i;
794
795         logging_init("udevd");
796         udev_init_config();
797         dbg("version %s", UDEV_VERSION);
798
799         if (getuid() != 0) {
800                 err("need to be root, exit");
801                 goto exit;
802         }
803
804         for (i = 1 ; i < argc; i++) {
805                 char *arg = argv[i];
806                 if (strcmp(arg, "--daemon") == 0 || strcmp(arg, "-d") == 0) {
807                         info("will daemonize");
808                         daemonize = 1;
809                 }
810                 if (strcmp(arg, "--stop-exec-queue") == 0) {
811                         info("will not execute events until START_EXEC_QUEUE is received");
812                         stop_exec_q = 1;
813                 }
814         }
815         if (daemonize) {
816                 pid_t pid;
817
818                 pid = fork();
819                 switch (pid) {
820                 case 0:
821                         dbg("damonized fork running");
822                         break;
823                 case -1:
824                         err("fork of daemon failed");
825                         goto exit;
826                 default:
827                         logging_close();
828                         exit(0);
829                 }
830         }
831
832         /* become session leader */
833         sid = setsid();
834         dbg("our session is %d", sid);
835
836         chdir("/");
837         umask(umask(077) | 022);
838
839         /*set a reasonable scheduling priority for the daemon */
840         setpriority(PRIO_PROCESS, 0, UDEVD_PRIORITY);
841
842         /* Set fds to dev/null */
843         fd = open( "/dev/null", O_RDWR );
844         if (fd >= 0)  {
845                 dup2(fd, 0);
846                 dup2(fd, 1);
847                 dup2(fd, 2);
848                 if (fd > 2)
849                         close(fd);
850         } else
851                 err("error opening /dev/null %s", strerror(errno));
852
853         /* setup signal handler pipe */
854         retval = pipe(pipefds);
855         if (retval < 0) {
856                 err("error getting pipes: %s", strerror(errno));
857                 goto exit;
858         }
859
860         retval = fcntl(pipefds[0], F_SETFL, O_NONBLOCK);
861         if (retval < 0) {
862                 err("error fcntl on read pipe: %s", strerror(errno));
863                 goto exit;
864         }
865         retval = fcntl(pipefds[0], F_SETFD, FD_CLOEXEC);
866         if (retval < 0)
867                 err("error fcntl on read pipe: %s", strerror(errno));
868
869         retval = fcntl(pipefds[1], F_SETFL, O_NONBLOCK);
870         if (retval < 0) {
871                 err("error fcntl on write pipe: %s", strerror(errno));
872                 goto exit;
873         }
874         retval = fcntl(pipefds[1], F_SETFD, FD_CLOEXEC);
875         if (retval < 0)
876                 err("error fcntl on write pipe: %s", strerror(errno));
877
878         /* set signal handlers */
879         memset(&act, 0x00, sizeof(struct sigaction));
880         act.sa_handler = (void (*)(int)) sig_handler;
881         sigemptyset(&act.sa_mask);
882         act.sa_flags = SA_RESTART;
883         sigaction(SIGINT, &act, NULL);
884         sigaction(SIGTERM, &act, NULL);
885         sigaction(SIGALRM, &act, NULL);
886         sigaction(SIGCHLD, &act, NULL);
887
888         if (init_uevent_netlink_sock() < 0) {
889                 dbg("uevent socket not available");
890         }
891
892         if (init_udevd_socket() < 0) {
893                 if (errno == EADDRINUSE)
894                         dbg("another udevd running, exit");
895                 else
896                         dbg("error initialising udevd socket: %s", strerror(errno));
897
898                 goto exit;
899         }
900
901         /* override of forked udev binary, used for testing */
902         udev_bin = getenv("UDEV_BIN");
903         if (udev_bin != NULL)
904                 info("udev binary is set to '%s'", udev_bin);
905         else
906                 udev_bin = UDEV_BIN;
907
908         /* init of expected_seqnum value */
909         value = getenv("UDEVD_EXPECTED_SEQNUM");
910         if (value) {
911                 expected_seqnum = strtoull(value, NULL, 10);
912                 info("initialize expected_seqnum to %llu", expected_seqnum);
913         }
914
915         /* timeout to wait for missing events */
916         value = getenv("UDEVD_EVENT_TIMEOUT");
917         if (value)
918                 event_timeout = strtoul(value, NULL, 10);
919         else
920                 event_timeout = UDEVD_EVENT_TIMEOUT;
921         info("initialize event_timeout to %u", event_timeout);
922
923         /* maximum limit of forked childs */
924         value = getenv("UDEVD_MAX_CHILDS");
925         if (value)
926                 max_childs = strtoul(value, NULL, 10);
927         else
928                 max_childs = UDEVD_MAX_CHILDS;
929         info("initialize max_childs to %u", max_childs);
930
931         /* start to throttle forking if maximum number of _running_ childs is reached */
932         value = getenv("UDEVD_MAX_CHILDS_RUNNING");
933         if (value)
934                 max_childs_running = strtoull(value, NULL, 10);
935         else
936                 max_childs_running = UDEVD_MAX_CHILDS_RUNNING;
937         info("initialize max_childs_running to %u", max_childs_running);
938
939         FD_ZERO(&readfds);
940         FD_SET(udevd_sock, &readfds);
941         if (uevent_netlink_sock != -1)
942                 FD_SET(uevent_netlink_sock, &readfds);
943         FD_SET(pipefds[0], &readfds);
944         maxsockplus = udevd_sock+1;
945         while (1) {
946                 struct uevent_msg *msg;
947
948                 fd_set workreadfds = readfds;
949                 retval = select(maxsockplus, &workreadfds, NULL, NULL, NULL);
950
951                 if (retval < 0) {
952                         if (errno != EINTR)
953                                 dbg("error in select: %s", strerror(errno));
954                         continue;
955                 }
956
957                 if (FD_ISSET(udevd_sock, &workreadfds)) {
958                         msg = get_udevd_msg();
959                         if (msg) {
960                                 /* discard kernel messages if netlink is active */
961                                 if (uevent_netlink_active && msg->type == UDEVD_UEVENT_UDEVSEND && msg->seqnum != 0) {
962                                         dbg("skip uevent_helper message, netlink is active");
963                                         free(msg);
964                                         continue;
965                                 }
966                                 msg_queue_insert(msg);
967                         }
968                 }
969
970                 if (FD_ISSET(uevent_netlink_sock, &workreadfds)) {
971                         msg = get_netlink_msg();
972                         if (msg) {
973                                 msg_queue_insert(msg);
974                                 /* disable udevsend with first netlink message */
975                                 if (!uevent_netlink_active) {
976                                         info("uevent_nl message received, disable udevsend messages");
977                                         uevent_netlink_active = 1;
978                                 }
979                         }
980                 }
981
982                 if (FD_ISSET(pipefds[0], &workreadfds))
983                         user_sighandler();
984
985                 if (sigchilds_waiting) {
986                         sigchilds_waiting = 0;
987                         reap_sigchilds();
988                 }
989
990                 if (run_msg_q) {
991                         run_msg_q = 0;
992                         msg_queue_manager();
993                 }
994
995                 if (run_exec_q) {
996                          /* clean up running_list before calling exec_queue_manager() */
997                         if (sigchilds_waiting) {
998                                 sigchilds_waiting = 0;
999                                 reap_sigchilds();
1000                         }
1001
1002                         run_exec_q = 0;
1003                         if (!stop_exec_q)
1004                                 exec_queue_manager();
1005                 }
1006         }
1007
1008 exit:
1009         logging_close();
1010         return 1;
1011 }