devfsd: fix formatting (Tito <farmatito@tiscali.it>)
[oweals/busybox.git] / miscutils / devfsd.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
4  */
5
6 /*
7         devfsd implementation for busybox
8
9         Copyright (C) 2003 by Tito Ragusa <farmatito@tiscali.it>
10
11         Busybox version is based on some previous work and ideas
12         Copyright (C) [2003] by [Matteo Croce] <3297627799@wind.it>
13
14         devfsd.c
15
16         Main file for  devfsd  (devfs daemon for Linux).
17
18     Copyright (C) 1998-2002  Richard Gooch
19
20         devfsd.h
21
22     Header file for  devfsd  (devfs daemon for Linux).
23
24     Copyright (C) 1998-2000  Richard Gooch
25
26         compat_name.c
27
28     Compatibility name file for  devfsd  (build compatibility names).
29
30     Copyright (C) 1998-2002  Richard Gooch
31
32         expression.c
33
34     This code provides Borne Shell-like expression expansion.
35
36     Copyright (C) 1997-1999  Richard Gooch
37
38         This program is free software; you can redistribute it and/or modify
39     it under the terms of the GNU General Public License as published by
40     the Free Software Foundation; either version 2 of the License, or
41     (at your option) any later version.
42
43     This program is distributed in the hope that it will be useful,
44     but WITHOUT ANY WARRANTY; without even the implied warranty of
45     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
46     GNU General Public License for more details.
47
48     You should have received a copy of the GNU General Public License
49     along with this program; if not, write to the Free Software
50     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
51
52     Richard Gooch may be reached by email at  rgooch@atnf.csiro.au
53     The postal address is:
54       Richard Gooch, c/o ATNF, P. O. Box 76, Epping, N.S.W., 2121, Australia.
55 */
56
57 //#include <sys/wait.h>
58 //#include <sys/ioctl.h>
59 //#include <sys/socket.h>
60 #include <sys/un.h>
61 #include <dirent.h>
62 #include <syslog.h>
63 #include <sys/sysmacros.h>
64 #include "libbb.h"
65 #include "xregex.h"
66
67
68 /* Various defines taken from linux/major.h */
69 #define IDE0_MAJOR      3
70 #define IDE1_MAJOR      22
71 #define IDE2_MAJOR      33
72 #define IDE3_MAJOR      34
73 #define IDE4_MAJOR      56
74 #define IDE5_MAJOR      57
75 #define IDE6_MAJOR      88
76 #define IDE7_MAJOR      89
77 #define IDE8_MAJOR      90
78 #define IDE9_MAJOR      91
79
80
81 /* Various defines taken from linux/devfs_fs.h */
82 #define DEVFSD_PROTOCOL_REVISION_KERNEL  5
83 #define DEVFSD_IOCTL_BASE       'd'
84 /*  These are the various ioctls  */
85 #define DEVFSDIOC_GET_PROTO_REV         _IOR(DEVFSD_IOCTL_BASE, 0, int)
86 #define DEVFSDIOC_SET_EVENT_MASK        _IOW(DEVFSD_IOCTL_BASE, 2, int)
87 #define DEVFSDIOC_RELEASE_EVENT_QUEUE   _IOW(DEVFSD_IOCTL_BASE, 3, int)
88 #define DEVFSDIOC_SET_CONFIG_DEBUG_MASK _IOW(DEVFSD_IOCTL_BASE, 4, int)
89 #define DEVFSD_NOTIFY_REGISTERED    0
90 #define DEVFSD_NOTIFY_UNREGISTERED  1
91 #define DEVFSD_NOTIFY_ASYNC_OPEN    2
92 #define DEVFSD_NOTIFY_CLOSE         3
93 #define DEVFSD_NOTIFY_LOOKUP        4
94 #define DEVFSD_NOTIFY_CHANGE        5
95 #define DEVFSD_NOTIFY_CREATE        6
96 #define DEVFSD_NOTIFY_DELETE        7
97 #define DEVFS_PATHLEN               1024
98 /*  Never change this otherwise the binary interface will change   */
99
100 struct devfsd_notify_struct
101 {   /*  Use native C types to ensure same types in kernel and user space     */
102     unsigned int type;           /*  DEVFSD_NOTIFY_* value                   */
103     unsigned int mode;           /*  Mode of the inode or device entry       */
104     unsigned int major;          /*  Major number of device entry            */
105     unsigned int minor;          /*  Minor number of device entry            */
106     unsigned int uid;            /*  Uid of process, inode or device entry   */
107     unsigned int gid;            /*  Gid of process, inode or device entry   */
108     unsigned int overrun_count;  /*  Number of lost events                   */
109     unsigned int namelen;        /*  Number of characters not including '\0' */
110     /*  The device name MUST come last                                       */
111     char devname[DEVFS_PATHLEN]; /*  This will be '\0' terminated            */
112 };
113
114 #define BUFFER_SIZE 16384
115 #define DEVFSD_VERSION "1.3.25"
116 #define CONFIG_FILE  "/etc/devfsd.conf"
117 #define MODPROBE                "/sbin/modprobe"
118 #define MODPROBE_SWITCH_1 "-k"
119 #define MODPROBE_SWITCH_2 "-C"
120 #define CONFIG_MODULES_DEVFS "/etc/modules.devfs"
121 #define MAX_ARGS     (6 + 1)
122 #define MAX_SUBEXPR  10
123 #define STRING_LENGTH 255
124
125 /* for get_uid_gid() */
126 #define UID                     0
127 #define GID                     1
128
129 /* fork_and_execute() */
130 # define DIE                    1
131 # define NO_DIE                 0
132
133 /* for dir_operation() */
134 #define RESTORE         0
135 #define SERVICE         1
136 #define READ_CONFIG 2
137
138 /*  Update only after changing code to reflect new protocol  */
139 #define DEVFSD_PROTOCOL_REVISION_DAEMON  5
140
141 /*  Compile-time check  */
142 #if DEVFSD_PROTOCOL_REVISION_KERNEL != DEVFSD_PROTOCOL_REVISION_DAEMON
143 #error protocol version mismatch. Update your kernel headers
144 #endif
145
146 #define AC_PERMISSIONS                          0
147 #define AC_MODLOAD                                      1
148 #define AC_EXECUTE                                      2
149 #define AC_MFUNCTION                            3       /* not supported by busybox */
150 #define AC_CFUNCTION                            4       /* not supported by busybox */
151 #define AC_COPY                                         5
152 #define AC_IGNORE                                       6
153 #define AC_MKOLDCOMPAT                          7
154 #define AC_MKNEWCOMPAT                          8
155 #define AC_RMOLDCOMPAT                          9
156 #define AC_RMNEWCOMPAT                          10
157 #define AC_RESTORE                                      11
158
159 struct permissions_type
160 {
161         mode_t mode;
162         uid_t uid;
163         gid_t gid;
164 };
165
166 struct execute_type
167 {
168         char *argv[MAX_ARGS + 1];  /*  argv[0] must always be the programme  */
169 };
170
171 struct copy_type
172 {
173         const char *source;
174         const char *destination;
175 };
176
177 struct action_type
178 {
179         unsigned int what;
180         unsigned int when;
181 };
182
183 struct config_entry_struct
184 {
185         struct action_type action;
186         regex_t preg;
187         union
188         {
189         struct permissions_type permissions;
190         struct execute_type execute;
191         struct copy_type copy;
192         }
193         u;
194         struct config_entry_struct *next;
195 };
196
197 struct get_variable_info
198 {
199         const struct devfsd_notify_struct *info;
200         const char *devname;
201         char devpath[STRING_LENGTH];
202 };
203
204 static void dir_operation(int , const char * , int,  unsigned long*);
205 static void service(struct stat statbuf, char *path);
206 static int st_expr_expand(char *, unsigned, const char *, const char *(*)(const char *, void *), void *);
207 static const char *get_old_name(const char *, unsigned, char *, unsigned, unsigned);
208 static int mksymlink(const char *oldpath, const char *newpath);
209 static void read_config_file(char *path, int optional, unsigned long *event_mask);
210 static void process_config_line(const char *, unsigned long *);
211 static int  do_servicing(int, unsigned long);
212 static void service_name(const struct devfsd_notify_struct *);
213 static void action_permissions(const struct devfsd_notify_struct *, const struct config_entry_struct *);
214 static void action_execute(const struct devfsd_notify_struct *, const struct config_entry_struct *,
215                                                         const regmatch_t *, unsigned);
216 static void action_modload(const struct devfsd_notify_struct *info, const struct config_entry_struct *entry);
217 static void action_copy(const struct devfsd_notify_struct *, const struct config_entry_struct *,
218                                                  const regmatch_t *, unsigned);
219 static void action_compat(const struct devfsd_notify_struct *, unsigned);
220 static void free_config(void);
221 static void restore(char *spath, struct stat source_stat, int rootlen);
222 static int copy_inode(const char *, const struct stat *, mode_t, const char *, const struct stat *);
223 static mode_t get_mode(const char *);
224 static void signal_handler(int);
225 static const char *get_variable(const char *, void *);
226 static int make_dir_tree(const char *);
227 static int expand_expression(char *, unsigned, const char *, const char *(*)(const char *, void *), void *,
228                                                          const char *, const regmatch_t *, unsigned);
229 static void expand_regexp(char *, size_t, const char *, const char *, const regmatch_t *, unsigned);
230 static const char *expand_variable(     char *, unsigned, unsigned *, const char *,
231                                                                         const char *(*)(const char *, void *), void *);
232 static const char *get_variable_v2(const char *, const char *(*)(const char *, void *), void *);
233 static char get_old_ide_name(unsigned , unsigned);
234 static char *write_old_sd_name(char *, unsigned, unsigned, const char *);
235
236 /* busybox functions */
237 static void msg_logger(int pri, const char * fmt, ...)__attribute__((format(printf, 2, 3)));
238 static void msg_logger_and_die(int pri, const char * fmt, ...)__attribute__((noreturn, format(printf, 2, 3)));
239 static void do_ioctl_and_die(int fd, int request, unsigned long event_mask_flag);
240 static void fork_and_execute(int die, char *arg0, char **arg);
241 static int get_uid_gid(int, const char *);
242 static void safe_memcpy(char * dest, const char * src, int len);
243 static unsigned int scan_dev_name_common(const char *d, unsigned int n, int addendum, char *ptr);
244 static unsigned int scan_dev_name(const char *d, unsigned int n, char *ptr);
245
246 /* Structs and vars */
247 static struct config_entry_struct *first_config = NULL;
248 static struct config_entry_struct *last_config = NULL;
249 static const char *mount_point = NULL;
250 static volatile int caught_signal = FALSE;
251 static volatile int caught_sighup = FALSE;
252 static struct initial_symlink_struct
253 {
254         const char *dest;
255         const char *name;
256 } initial_symlinks[] =
257 {
258         {"/proc/self/fd", "fd"},
259         {"fd/0", "stdin"},
260         {"fd/1", "stdout"},
261         {"fd/2", "stderr"},
262         {NULL, NULL},
263 };
264
265 static struct event_type
266 {
267         unsigned int type;        /*  The DEVFSD_NOTIFY_* value                  */
268         const char *config_name;  /*  The name used in the config file           */
269 } event_types[] =
270 {
271         {DEVFSD_NOTIFY_REGISTERED,   "REGISTER"},
272         {DEVFSD_NOTIFY_UNREGISTERED, "UNREGISTER"},
273         {DEVFSD_NOTIFY_ASYNC_OPEN,   "ASYNC_OPEN"},
274         {DEVFSD_NOTIFY_CLOSE,        "CLOSE"},
275         {DEVFSD_NOTIFY_LOOKUP,       "LOOKUP"},
276         {DEVFSD_NOTIFY_CHANGE,       "CHANGE"},
277         {DEVFSD_NOTIFY_CREATE,       "CREATE"},
278         {DEVFSD_NOTIFY_DELETE,       "DELETE"},
279         {0xffffffff,                 NULL}
280 };
281
282 /* Busybox messages */
283
284 static const char * const bb_msg_proto_rev                      = "protocol revision";
285 static const char * const bb_msg_bad_config             = "bad %s config file: %s";
286 static const char * const bb_msg_small_buffer           = "buffer too small";
287 static const char * const bb_msg_variable_not_found = "variable: %s not found";
288
289 /* Busybox functions  */
290 static void msg_logger(int pri, const char * fmt, ...)
291 {
292         va_list ap;
293         int ret;
294
295         va_start(ap, fmt);
296         ret = access("/dev/log", F_OK);
297         if (ret == 0) {
298                 openlog(applet_name, 0, LOG_DAEMON);
299                 vsyslog(pri , fmt, ap);
300                 /* Man: A trailing newline is added when needed. */
301                 closelog();
302         }
303         /* ENABLE_DEVFSD_VERBOSE is always enabled if msg_logger is used */
304         if ((ENABLE_DEVFSD_VERBOSE && ret) || ENABLE_DEBUG) {
305                 bb_error_msg(fmt, ap);
306         }
307         va_end(ap);
308 }
309
310 static void msg_logger_and_die(int pri, const char* fmt, ...)
311 {
312         va_list ap;
313
314         va_start(ap, fmt);
315         msg_logger(pri, fmt, ap);
316         va_end(ap);
317         exit(EXIT_FAILURE);
318 }
319
320 /* Busybox stuff */
321 #if defined(CONFIG_DEVFSD_VERBOSE) || defined(CONFIG_DEBUG)
322 #define devfsd_error_msg(fmt, args...)                bb_error_msg(fmt, ## args)
323 #define devfsd_perror_msg_and_die(fmt, args...)       bb_perror_msg_and_die(fmt, ## args)
324 #define devfsd_error_msg_and_die(fmt, args...)        bb_error_msg_and_die(fmt, ## args)
325 #if defined(CONFIG_DEBUG)
326 #define debug_msg_logger(x, fmt, args...)             msg_logger(x, fmt, ## args)
327 #else
328 #define debug_msg_logger(x, fmt, args...)
329 #endif
330 #else
331 #define debug_msg_logger(x, fmt, args...)
332 #define msg_logger(p, fmt, args...)
333 #define msg_logger_and_die(p, fmt, args...)           exit(1)
334 #define devfsd_perror_msg_and_die(fmt, args...)       exit(1)
335 #define devfsd_error_msg_and_die(fmt, args...)        exit(1)
336 #define devfsd_error_msg(fmt, args...)
337 #endif
338
339 static void do_ioctl_and_die(int fd, int request, unsigned long event_mask_flag)
340 {
341         if (ioctl(fd, request, event_mask_flag) == -1)
342                 msg_logger_and_die(LOG_ERR, "ioctl");
343 }
344
345 static void fork_and_execute(int die, char *arg0, char **arg)
346 {
347         switch (fork()) {
348                 case 0:
349                         /*  Child  */
350                         break;
351                 case -1:
352                         /*  Parent: Error  : die or return */
353                         msg_logger(LOG_ERR,(char *)bb_msg_memory_exhausted);
354                         if (die)
355                                 exit(EXIT_FAILURE);
356                         return;
357                 default:
358                         /*  Parent : ok : return or exit  */
359                         if (arg0 != NULL) {
360                                 wait(NULL);
361                                 return;
362                         }
363                         exit(EXIT_SUCCESS);
364         }
365          /* Child : if arg0 != NULL do execvp */
366         if (arg0 != NULL) {
367                 BB_EXECVP(arg0, arg);
368                 msg_logger_and_die(LOG_ERR, "execvp");
369         }
370 }
371
372 static void safe_memcpy(char *dest, const char *src, int len)
373 {
374         memcpy(dest , src, len);
375         dest[len] = '\0';
376 }
377
378 static unsigned int scan_dev_name_common(const char *d, unsigned int n, int addendum, char *ptr)
379 {
380         if (d[n - 4] == 'd' && d[n - 3] == 'i' && d[n - 2] == 's' && d[n - 1] == 'c')
381                 return 2 + addendum;
382         if (d[n - 2] == 'c' && d[n - 1] == 'd')
383                 return 3 + addendum;
384         if (ptr[0] == 'p' && ptr[1] == 'a' && ptr[2] == 'r' && ptr[3] == 't')
385                 return 4 + addendum;
386         if (ptr[n - 2] == 'm' && ptr[n - 1] == 't')
387                 return 5 + addendum;
388         return 0;
389 }
390
391 static unsigned int scan_dev_name(const char *d, unsigned int n, char *ptr)
392 {
393         if (d[0] == 's' && d[1] == 'c' && d[2] == 's' && d[3] == 'i' && d[4] == '/') {
394                 if (d[n - 7] == 'g' && d[n - 6] == 'e' && d[n - 5] == 'n'
395                         && d[n - 4] == 'e' && d[n - 3] == 'r' && d[n - 2] == 'i' && d[n - 1] == 'c'
396                 )
397                         return 1;
398                 return scan_dev_name_common(d, n, 0, ptr);
399         }
400         if (d[0] == 'i' && d[1] == 'd' && d[2] == 'e' && d[3] == '/'
401                 && d[4] == 'h' && d[5] == 'o' && d[6] == 's' && d[7] == 't'
402         )
403                 return scan_dev_name_common(d, n, 4, ptr);
404         if (d[0] == 's' && d[1] == 'b' && d[2] == 'p' && d[3] == '/')
405                 return 10;
406         if (d[0] == 'v' && d[1] == 'c' && d[2] == 'c' && d[3] == '/')
407                 return 11;
408         if (d[0] == 'p' && d[1] == 't' && d[2] == 'y' && d[3] == '/')
409                 return 12;
410         return 0;
411 }
412
413 /*  Public functions follow  */
414
415 int devfsd_main(int argc, char **argv);
416 int devfsd_main(int argc, char **argv)
417 {
418         int print_version = FALSE;
419         int do_daemon = TRUE;
420         int no_polling = FALSE;
421         int do_scan;
422         int fd, proto_rev, count;
423         unsigned long event_mask = 0;
424         struct sigaction new_action;
425         struct initial_symlink_struct *curr;
426
427         if (argc < 2)
428                 bb_show_usage();
429
430         for (count = 2; count < argc; ++count) {
431                 if (argv[count][0] == '-') {
432                         if (argv[count][1] == 'v' && !argv[count][2]) /* -v */
433                                         print_version = TRUE;
434                         else if (ENABLE_DEVFSD_FG_NP && argv[count][1] == 'f'
435                                         && argv[count][2] == 'g' && !argv[count][3]) /* -fg */
436                                         do_daemon = FALSE;
437                         else if (ENABLE_DEVFSD_FG_NP && argv[count][1] == 'n'
438                                         && argv[count][2] == 'p' && !argv[count][3]) /* -np */
439                                         no_polling = TRUE;
440                         else
441                                 bb_show_usage();
442                 }
443         }
444
445         /* strip last / from mount point, so we don't need to check for it later */
446         while (argv[1][1] != '\0' && argv[1][strlen(argv[1]) - 1] == '/')
447                 argv[1][strlen(argv[1]) - 1] = '\0';
448
449         mount_point = argv[1];
450
451         if (chdir(mount_point) != 0)
452                 devfsd_perror_msg_and_die(mount_point);
453
454         fd = xopen(".devfsd", O_RDONLY);
455
456         if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0)
457                 devfsd_perror_msg_and_die("FD_CLOEXEC");
458
459         if (ioctl(fd, DEVFSDIOC_GET_PROTO_REV, &proto_rev) == -1)
460                 msg_logger_and_die(LOG_ERR, "ioctl");
461
462         /*setup initial entries */
463     for (curr = initial_symlinks; curr->dest != NULL; ++curr)
464                 symlink(curr->dest, curr->name);
465
466         /* NB: The check for CONFIG_FILE is done in read_config_file() */
467
468         if (print_version ||(DEVFSD_PROTOCOL_REVISION_DAEMON != proto_rev)) {
469                 printf("%s v%s\nDaemon %s:\t%d\nKernel-side %s:\t%d\n",
470                                 applet_name, DEVFSD_VERSION, bb_msg_proto_rev,
471                                 DEVFSD_PROTOCOL_REVISION_DAEMON,bb_msg_proto_rev, proto_rev);
472                 if (DEVFSD_PROTOCOL_REVISION_DAEMON != proto_rev)
473                         bb_error_msg_and_die("%s mismatch!", bb_msg_proto_rev);
474                 exit(EXIT_SUCCESS); /* -v */
475         }
476         /*  Tell kernel we are special(i.e. we get to see hidden entries)  */
477         do_ioctl_and_die(fd, DEVFSDIOC_SET_EVENT_MASK, 0);
478
479         sigemptyset(&new_action.sa_mask);
480         new_action.sa_flags = 0;
481
482         /*  Set up SIGHUP and SIGUSR1 handlers  */
483         new_action.sa_handler = signal_handler;
484         if (sigaction(SIGHUP, &new_action, NULL) != 0 || sigaction(SIGUSR1, &new_action, NULL) != 0)
485                 devfsd_error_msg_and_die("sigaction");
486
487         printf("%s v%s  started for %s\n",applet_name, DEVFSD_VERSION, mount_point);
488
489         /*  Set umask so that mknod(2), open(2) and mkdir(2) have complete control over permissions  */
490         umask(0);
491         read_config_file((char*)CONFIG_FILE, FALSE, &event_mask);
492         /*  Do the scan before forking, so that boot scripts see the finished product  */
493         dir_operation(SERVICE, mount_point, 0, NULL);
494
495         if (ENABLE_DEVFSD_FG_NP && no_polling)
496                 exit(0);
497         if (do_daemon) {
498                 /*  Release so that the child can grab it  */
499                 do_ioctl_and_die(fd, DEVFSDIOC_RELEASE_EVENT_QUEUE, 0);
500                 fork_and_execute(DIE, NULL, NULL);
501                 setsid();        /*  Prevent hangups and become pgrp leader         */
502         } else if (ENABLE_DEVFSD_FG_NP) {
503                 setpgid(0, 0);  /*  Become process group leader                    */
504         }
505
506         while (TRUE) {
507                 do_scan = do_servicing(fd, event_mask);
508
509                 free_config();
510                 read_config_file((char*)CONFIG_FILE, FALSE, &event_mask);
511                 if (do_scan)
512                         dir_operation(SERVICE,mount_point,0,NULL);
513         }
514 }   /*  End Function main  */
515
516
517 /*  Private functions follow  */
518
519 static void read_config_file(char *path, int optional, unsigned long *event_mask)
520 /*  [SUMMARY] Read a configuration database.
521     <path> The path to read the database from. If this is a directory, all
522     entries in that directory will be read(except hidden entries).
523     <optional> If TRUE, the routine will silently ignore a missing config file.
524     <event_mask> The event mask is written here. This is not initialised.
525     [RETURNS] Nothing.
526 */
527 {
528         struct stat statbuf;
529         FILE *fp;
530         char buf[STRING_LENGTH];
531         char *line = NULL;
532
533         debug_msg_logger(LOG_INFO, "%s: %s", __FUNCTION__, path);
534
535         if (stat(path, &statbuf) == 0) {
536                 /* Don't read 0 length files: ignored */
537                 /*if (statbuf.st_size == 0)
538                                 return;*/
539                 if (S_ISDIR(statbuf.st_mode)) {
540                         /* strip last / from dirname so we don't need to check for it later */
541                         while (path && path[1] != '\0' && path[strlen(path) - 1] == '/')
542                                 path[strlen(path) - 1] = '\0';
543
544                         dir_operation(READ_CONFIG, path, 0, event_mask);
545                         return;
546                 }
547                 if ((fp = fopen(path, "r")) != NULL) {
548                         while (fgets(buf, STRING_LENGTH, fp) != NULL) {
549                                 /*  Skip whitespace  */
550                                 for (line = buf; isspace(*line); ++line)
551                                         /*VOID*/;
552                                 if (line[0] == '\0' || line[0] == '#')
553                                         continue;
554                                 process_config_line(line, event_mask);
555                         }
556                         fclose(fp);
557                 } else {
558                         goto read_config_file_err;
559                 }
560         } else {
561 read_config_file_err:
562         if (optional ==  0  && errno == ENOENT)
563                 msg_logger_and_die(LOG_ERR, "read config file: %s: %m", path);
564         }
565 }   /*  End Function read_config_file   */
566
567 static void process_config_line(const char *line, unsigned long *event_mask)
568 /*  [SUMMARY] Process a line from a configuration file.
569     <line> The configuration line.
570     <event_mask> The event mask is written here. This is not initialised.
571     [RETURNS] Nothing.
572 */
573 {
574         int  num_args, count;
575         struct config_entry_struct *new;
576         char p[MAX_ARGS][STRING_LENGTH];
577         char when[STRING_LENGTH], what[STRING_LENGTH];
578         char name[STRING_LENGTH];
579         const char *msg = "";
580         char *ptr;
581         int i;
582
583         /* !!!! Only Uppercase Keywords in devsfd.conf */
584         static const char *const options[] = {
585                 "CLEAR_CONFIG", "INCLUDE", "OPTIONAL_INCLUDE",
586                 "RESTORE", "PERMISSIONS", "MODLOAD", "EXECUTE",
587                 "COPY", "IGNORE", "MKOLDCOMPAT", "MKNEWCOMPAT",
588                 "RMOLDCOMPAT", "RMNEWCOMPAT", 0
589         };
590
591         debug_msg_logger(LOG_INFO, __FUNCTION__);
592
593         for (count = 0; count < MAX_ARGS; ++count) p[count][0] = '\0';
594         num_args = sscanf(line, "%s %s %s %s %s %s %s %s %s %s",
595                         when, name, what,
596                         p[0], p[1], p[2], p[3], p[4], p[5], p[6]);
597
598         i = index_in_str_array(options, when);
599
600         /*"CLEAR_CONFIG"*/
601         if (i == 0) {
602                 free_config();
603                 *event_mask = 0;
604                 return;
605         }
606
607         if (num_args < 2)
608                 goto process_config_line_err;
609
610         /* "INCLUDE" & "OPTIONAL_INCLUDE" */
611         if (i == 1 || i == 2) {
612                 st_expr_expand(name, STRING_LENGTH, name, get_variable, NULL);
613                 msg_logger(LOG_INFO, "%sinclude: %s", (toupper(when[0]) == 'I') ? "": "optional_", name);
614                 read_config_file(name, (toupper(when[0]) == 'I') ? FALSE : TRUE, event_mask);
615                 return;
616         }
617         /* "RESTORE" */
618         if (i == 3) {
619                 dir_operation(RESTORE,name, strlen(name),NULL);
620                 return;
621         }
622         if (num_args < 3)
623                 goto process_config_line_err;
624
625         new = xmalloc(sizeof *new);
626         memset(new, 0, sizeof *new);
627
628         for (count = 0; event_types[count].config_name != NULL; ++count) {
629                 if (strcasecmp(when, event_types[count].config_name) != 0)
630                         continue;
631                 new->action.when = event_types[count].type;
632                 break;
633         }
634         if (event_types[count].config_name == NULL) {
635                 msg="WHEN in";
636                 goto process_config_line_err;
637         }
638
639         i = index_in_str_array(options, what);
640
641         switch (i) {
642                 case 4: /* "PERMISSIONS" */
643                         new->action.what = AC_PERMISSIONS;
644                         /*  Get user and group  */
645                         if ((ptr = strchr(p[0], '.')) == NULL) {
646                                 msg="UID.GID";
647                                 goto process_config_line_err; /*"missing '.' in UID.GID"*/
648                         }
649
650                         *ptr++ = '\0';
651                         new->u.permissions.uid = get_uid_gid(UID, p[0]);
652                         new->u.permissions.gid = get_uid_gid(GID, ptr);
653                         /*  Get mode  */
654                         new->u.permissions.mode = get_mode(p[1]);
655                         break;
656                 case 5: /*  MODLOAD */
657                         /*This  action will pass "/dev/$devname"(i.e. "/dev/" prefixed to
658                         the device name) to the module loading  facility.  In  addition,
659                         the /etc/modules.devfs configuration file is used.*/
660                          if (ENABLE_DEVFSD_MODLOAD)
661                                 new->action.what = AC_MODLOAD;
662                          break;
663                 case 6: /* EXECUTE */
664                         new->action.what = AC_EXECUTE;
665                         num_args -= 3;
666
667                         for (count = 0; count < num_args; ++count)
668                                 new->u.execute.argv[count] = xstrdup(p[count]);
669
670                         new->u.execute.argv[num_args] = NULL;
671                         break;
672                 case 7: /* COPY */
673                         new->action.what = AC_COPY;
674                         num_args -= 3;
675                         if (num_args != 2)
676                                 goto process_config_line_err; /* missing path and function in line */
677
678                         new->u.copy.source = xstrdup(p[0]);
679                         new->u.copy.destination = xstrdup(p[1]);
680                         break;
681                 case 8: /* IGNORE */
682                 /* FALLTROUGH */
683                 case 9: /* MKOLDCOMPAT */
684                 /* FALLTROUGH */
685                 case 10: /* MKNEWCOMPAT */
686                 /* FALLTROUGH */
687                 case 11:/* RMOLDCOMPAT */
688                 /* FALLTROUGH */
689                 case 12: /* RMNEWCOMPAT */
690                 /*      AC_IGNORE                                       6
691                         AC_MKOLDCOMPAT                          7
692                         AC_MKNEWCOMPAT                          8
693                         AC_RMOLDCOMPAT                          9
694                         AC_RMNEWCOMPAT                          10*/
695                         new->action.what = i - 2;
696                         break;
697                 default:
698                         msg ="WHAT in";
699                         goto process_config_line_err;
700                 /*esac*/
701         } /* switch (i) */
702
703         xregcomp(&new->preg, name, REG_EXTENDED);
704
705         *event_mask |= 1 << new->action.when;
706         new->next = NULL;
707         if (first_config == NULL)
708                 first_config = new;
709         else
710                 last_config->next = new;
711         last_config = new;
712         return;
713 process_config_line_err:
714         msg_logger_and_die(LOG_ERR, bb_msg_bad_config, msg , line);
715 }  /*  End Function process_config_line   */
716
717 static int do_servicing(int fd, unsigned long event_mask)
718 /*  [SUMMARY] Service devfs changes until a signal is received.
719     <fd> The open control file.
720     <event_mask> The event mask.
721     [RETURNS] TRUE if SIGHUP was caught, else FALSE.
722 */
723 {
724         ssize_t bytes;
725         struct devfsd_notify_struct info;
726         unsigned long tmp_event_mask;
727
728         debug_msg_logger(LOG_INFO, __FUNCTION__);
729
730         /*  Tell devfs what events we care about  */
731         tmp_event_mask = event_mask;
732         do_ioctl_and_die(fd, DEVFSDIOC_SET_EVENT_MASK, tmp_event_mask);
733         while (!caught_signal) {
734                 errno = 0;
735                 bytes = read(fd,(char *) &info, sizeof info);
736                 if (caught_signal)
737                         break;      /*  Must test for this first     */
738                 if (errno == EINTR)
739                         continue;  /*  Yes, the order is important  */
740                 if (bytes < 1)
741                         break;
742                 service_name(&info);
743         }
744         if (caught_signal) {
745                 int c_sighup = caught_sighup;
746
747                 caught_signal = FALSE;
748                 caught_sighup = FALSE;
749                 return c_sighup;
750         }
751         msg_logger_and_die(LOG_ERR, "read error on control file");
752 }   /*  End Function do_servicing  */
753
754 static void service_name(const struct devfsd_notify_struct *info)
755 /*  [SUMMARY] Service a single devfs change.
756     <info> The devfs change.
757     [RETURNS] Nothing.
758 */
759 {
760         unsigned int n;
761         regmatch_t mbuf[MAX_SUBEXPR];
762         struct config_entry_struct *entry;
763
764         debug_msg_logger(LOG_INFO, __FUNCTION__);
765         if (ENABLE_DEBUG && info->overrun_count > 0)
766                 debug_msg_logger(LOG_ERR, "lost %u events", info->overrun_count);
767
768         /*  Discard lookups on "/dev/log" and "/dev/initctl"  */
769         if (info->type == DEVFSD_NOTIFY_LOOKUP 
770                 && ((info->devname[0] == 'l' && info->devname[1] == 'o'
771                 && info->devname[2] == 'g' && !info->devname[3]) 
772                 || (info->devname[0] == 'i' && info->devname[1] == 'n'
773                 && info->devname[2] == 'i' && info->devname[3] == 't'
774                 && info->devname[4] == 'c' && info->devname[5] == 't'
775                 && info->devname[6] == 'l' && !info->devname[7]))
776         )
777                 return;
778
779         for (entry = first_config; entry != NULL; entry = entry->next) {
780                 /*  First check if action matches the type, then check if name matches */
781                 if (info->type != entry->action.when 
782                 || regexec(&entry->preg, info->devname, MAX_SUBEXPR, mbuf, 0) != 0)
783                         continue;
784                 for (n = 0;(n < MAX_SUBEXPR) && (mbuf[n].rm_so != -1); ++n)
785                         /* VOID */;
786
787                 debug_msg_logger(LOG_INFO, "%s: action.what %d", __FUNCTION__, entry->action.what);
788
789                 switch (entry->action.what) {
790                         case AC_PERMISSIONS:
791                                 action_permissions(info, entry);
792                                 break;
793                         case AC_MODLOAD:
794                                 if (ENABLE_DEVFSD_MODLOAD)
795                                         action_modload(info, entry);
796                                 break;
797                         case AC_EXECUTE:
798                                 action_execute(info, entry, mbuf, n);
799                                 break;
800                         case AC_COPY:
801                                 action_copy(info, entry, mbuf, n);
802                                 break;
803                         case AC_IGNORE:
804                                 return;
805                                 /*break;*/
806                         case AC_MKOLDCOMPAT:
807                         case AC_MKNEWCOMPAT:
808                         case AC_RMOLDCOMPAT:
809                         case AC_RMNEWCOMPAT:
810                                 action_compat(info, entry->action.what);
811                                 break;
812                         default:
813                                 msg_logger_and_die(LOG_ERR, "Unknown action");
814                 }
815         }
816 }   /*  End Function service_name  */
817
818 static void action_permissions(const struct devfsd_notify_struct *info,
819                                 const struct config_entry_struct *entry)
820 /*  [SUMMARY] Update permissions for a device entry.
821     <info> The devfs change.
822     <entry> The config file entry.
823     [RETURNS] Nothing.
824 */
825 {
826         struct stat statbuf;
827
828         debug_msg_logger(LOG_INFO, __FUNCTION__);
829
830         if (stat(info->devname, &statbuf) != 0  ||
831                  chmod(info->devname,(statbuf.st_mode & S_IFMT) |(entry->u.permissions.mode & ~S_IFMT)) != 0 ||
832                  chown(info->devname, entry->u.permissions.uid, entry->u.permissions.gid) != 0) {
833                 msg_logger(LOG_ERR, "Can't chmod or chown: %s: %m",info->devname);
834         }
835 }   /*  End Function action_permissions  */
836
837 static void action_modload(const struct devfsd_notify_struct *info,
838                             const struct config_entry_struct *entry ATTRIBUTE_UNUSED)
839 /*  [SUMMARY] Load a module.
840     <info> The devfs change.
841     <entry> The config file entry.
842     [RETURNS] Nothing.
843 */
844 {
845         char *argv[6];
846         char device[STRING_LENGTH];
847
848         argv[0] =(char*)MODPROBE;
849         argv[1] =(char*)MODPROBE_SWITCH_1; /* "-k" */
850         argv[2] =(char*)MODPROBE_SWITCH_2; /* "-C" */
851         argv[3] =(char*)CONFIG_MODULES_DEVFS;
852         argv[4] = device;
853         argv[5] = NULL;
854
855         snprintf(device, sizeof(device), "/dev/%s", info->devname);
856         debug_msg_logger(LOG_INFO, "%s: %s %s %s %s %s",__FUNCTION__, argv[0],argv[1],argv[2],argv[3],argv[4]);
857         fork_and_execute(DIE, argv[0], argv);
858 }  /*  End Function action_modload  */
859
860 static void action_execute(const struct devfsd_notify_struct *info,
861                             const struct config_entry_struct *entry,
862                             const regmatch_t *regexpr, unsigned int numexpr)
863 /*  [SUMMARY] Execute a programme.
864     <info> The devfs change.
865     <entry> The config file entry.
866     <regexpr> The number of subexpression(start, end) offsets within the
867     device name.
868     <numexpr> The number of elements within <<regexpr>>.
869     [RETURNS] Nothing.
870 */
871 {
872         unsigned int count;
873         struct get_variable_info gv_info;
874         char *argv[MAX_ARGS + 1];
875         char largv[MAX_ARGS + 1][STRING_LENGTH];
876
877         debug_msg_logger(LOG_INFO ,__FUNCTION__);
878         gv_info.info = info;
879         gv_info.devname = info->devname;
880         snprintf(gv_info.devpath, sizeof(gv_info.devpath), "%s/%s", mount_point, info->devname);
881         for (count = 0; entry->u.execute.argv[count] != NULL; ++count) {
882                 expand_expression(largv[count], STRING_LENGTH,
883                                 entry->u.execute.argv[count],
884                                 get_variable, &gv_info,
885                                 gv_info.devname, regexpr, numexpr);
886                 argv[count] = largv[count];
887         }
888         argv[count] = NULL;
889         fork_and_execute(NO_DIE, argv[0], argv);
890 }   /*  End Function action_execute  */
891
892
893 static void action_copy(const struct devfsd_notify_struct *info,
894                          const struct config_entry_struct *entry,
895                          const regmatch_t *regexpr, unsigned int numexpr)
896 /*  [SUMMARY] Copy permissions.
897     <info> The devfs change.
898     <entry> The config file entry.
899     <regexpr> This list of subexpression(start, end) offsets within the
900     device name.
901     <numexpr> The number of elements in <<regexpr>>.
902     [RETURNS] Nothing.
903 */
904 {
905         mode_t new_mode;
906         struct get_variable_info gv_info;
907         struct stat source_stat, dest_stat;
908         char source[STRING_LENGTH], destination[STRING_LENGTH];
909         int ret = 0;
910
911         debug_msg_logger(LOG_INFO, __FUNCTION__);
912
913         dest_stat.st_mode = 0;
914
915         if ((info->type == DEVFSD_NOTIFY_CHANGE) && S_ISLNK(info->mode))
916                 return;
917         gv_info.info = info;
918         gv_info.devname = info->devname;
919
920         snprintf(gv_info.devpath, sizeof(gv_info.devpath), "%s/%s", mount_point, info->devname);
921         expand_expression(source, STRING_LENGTH, entry->u.copy.source,
922                                 get_variable, &gv_info, gv_info.devname,
923                                 regexpr, numexpr);
924
925         expand_expression(destination, STRING_LENGTH, entry->u.copy.destination,
926                                 get_variable, &gv_info, gv_info.devname,
927                                 regexpr, numexpr);
928
929         if (!make_dir_tree(destination) || lstat(source, &source_stat) != 0)
930                         return;
931         lstat(destination, &dest_stat);
932         new_mode = source_stat.st_mode & ~S_ISVTX;
933         if (info->type == DEVFSD_NOTIFY_CREATE)
934                 new_mode |= S_ISVTX;
935         else if ((info->type == DEVFSD_NOTIFY_CHANGE) &&(dest_stat.st_mode & S_ISVTX))
936                 new_mode |= S_ISVTX;
937         ret = copy_inode(destination, &dest_stat, new_mode, source, &source_stat);
938         if (ENABLE_DEBUG && ret &&(errno != EEXIST))
939                 debug_msg_logger(LOG_ERR, "copy_inode: %s to %s: %m", source, destination);
940 }   /*  End Function action_copy  */
941
942 static void action_compat(const struct devfsd_notify_struct *info, unsigned int action)
943 /*  [SUMMARY] Process a compatibility request.
944     <info> The devfs change.
945     <action> The action to take.
946     [RETURNS] Nothing.
947 */
948 {
949         int ret;
950         const char *compat_name = NULL;
951         const char *dest_name = info->devname;
952         char *ptr=NULL;
953         char compat_buf[STRING_LENGTH], dest_buf[STRING_LENGTH];
954         int mode, host, bus, target, lun;
955         unsigned int i;
956         char rewind_;
957         /* 1 to 5  "scsi/" , 6 to 9 "ide/host" */
958         static const char *const fmt[] = {
959                 NULL ,
960                 "sg/c%db%dt%du%d",              /* scsi/generic */
961                 "sd/c%db%dt%du%d",              /* scsi/disc */
962                 "sr/c%db%dt%du%d",              /* scsi/cd */
963                 "sd/c%db%dt%du%dp%d",           /* scsi/part */
964                 "st/c%db%dt%du%dm%d%c",         /* scsi/mt */
965                 "ide/hd/c%db%dt%du%d",          /* ide/host/disc */
966                 "ide/cd/c%db%dt%du%d",          /* ide/host/cd */
967                 "ide/hd/c%db%dt%du%dp%d",       /* ide/host/part */
968                 "ide/mt/c%db%dt%du%d%s",        /* ide/host/mt */
969                 NULL
970         };
971
972         /*  First construct compatibility name  */
973         switch (action) {
974                 case AC_MKOLDCOMPAT:
975                 case AC_RMOLDCOMPAT:
976                         compat_name = get_old_name(info->devname, info->namelen, compat_buf, info->major, info->minor);
977                         break;
978                 case AC_MKNEWCOMPAT:
979                 case AC_RMNEWCOMPAT:
980                         ptr = strrchr(info->devname, '/') + 1;
981                         i=scan_dev_name(info->devname, info->namelen, ptr);
982
983                         debug_msg_logger(LOG_INFO, "%s: scan_dev_name = %d", __FUNCTION__, i);
984
985                         /* nothing found */
986                         if (i==0 || i > 9)
987                                 return;
988
989                         sscanf(info->devname +((i<6)?5:4), "host%d/bus%d/target%d/lun%d/", &host, &bus, &target, &lun);
990                         snprintf(dest_buf, sizeof(dest_buf), "../%s", info->devname +((i>5)?4:0));
991                         dest_name = dest_buf;
992                         compat_name = compat_buf;
993
994
995                         /* 1 == scsi/generic  2 == scsi/disc 3 == scsi/cd 6 == ide/host/disc 7 == ide/host/cd */
996                         if (i == 1 || i == 2 || i == 3 || i == 6 || i ==7)
997                                 sprintf(compat_buf, fmt[i], host, bus, target, lun);
998
999                         /* 4 == scsi/part 8 == ide/host/part */
1000                         if (i == 4 || i == 8)
1001                                 sprintf(compat_buf, fmt[i], host, bus, target, lun, atoi(ptr + 4));
1002
1003                         /* 5 == scsi/mt */
1004                         if (i == 5) {
1005                                 rewind_ = info->devname[info->namelen - 1];
1006                                 if (rewind_ != 'n')
1007                                         rewind_ = '\0';
1008                                 mode=0;
1009                                 if (ptr[2] ==  'l' /*108*/ || ptr[2] == 'm'/*109*/)
1010                                         mode = ptr[2] - 107; /* 1 or 2 */
1011                                 if (ptr[2] ==  'a')
1012                                         mode = 3;
1013                                 sprintf(compat_buf, fmt [i], host, bus, target, lun, mode, rewind_);
1014                         }
1015
1016                         /* 9 == ide/host/mt */
1017                         if (i ==  9)
1018                                 snprintf(compat_buf, sizeof(compat_buf), fmt[i], host, bus, target, lun, ptr + 2);
1019                 /* esac */
1020         } /* switch (action) */
1021
1022         if (compat_name == NULL)
1023                 return;
1024
1025         debug_msg_logger(LOG_INFO, "%s: %s", __FUNCTION__, compat_name);
1026
1027         /*  Now decide what to do with it  */
1028         switch (action) {
1029                 case AC_MKOLDCOMPAT:
1030                 case AC_MKNEWCOMPAT:
1031                         mksymlink(dest_name, compat_name);
1032                         break;
1033                 case AC_RMOLDCOMPAT:
1034                 case AC_RMNEWCOMPAT:
1035                         ret = unlink(compat_name);
1036                         if (ENABLE_DEBUG && ret)
1037                                 debug_msg_logger(LOG_ERR, "unlink: %s: %m", compat_name);
1038                         break;
1039                 /*esac*/
1040         } /* switch (action) */
1041 }   /*  End Function action_compat  */
1042
1043 static void restore(char *spath, struct stat source_stat, int rootlen)
1044 {
1045         char dpath[STRING_LENGTH];
1046         struct stat dest_stat;
1047
1048         debug_msg_logger(LOG_INFO, __FUNCTION__);
1049
1050         dest_stat.st_mode = 0;
1051         snprintf(dpath, sizeof dpath, "%s%s", mount_point, spath + rootlen);
1052         lstat(dpath, &dest_stat);
1053
1054         if (S_ISLNK(source_stat.st_mode) ||(source_stat.st_mode & S_ISVTX))
1055                 copy_inode(dpath, &dest_stat,(source_stat.st_mode & ~S_ISVTX) , spath, &source_stat);
1056
1057         if (S_ISDIR(source_stat.st_mode))
1058                 dir_operation(RESTORE, spath, rootlen,NULL);
1059 }
1060
1061
1062 static int copy_inode(const char *destpath, const struct stat *dest_stat,
1063                         mode_t new_mode,
1064                         const char *sourcepath, const struct stat *source_stat)
1065 /*  [SUMMARY] Copy an inode.
1066     <destpath> The destination path. An existing inode may be deleted.
1067     <dest_stat> The destination stat(2) information.
1068     <new_mode> The desired new mode for the destination.
1069     <sourcepath> The source path.
1070     <source_stat> The source stat(2) information.
1071     [RETURNS] TRUE on success, else FALSE.
1072 */
1073 {
1074         int source_len, dest_len;
1075         char source_link[STRING_LENGTH], dest_link[STRING_LENGTH];
1076         int fd, val;
1077         struct sockaddr_un un_addr;
1078         char symlink_val[STRING_LENGTH];
1079
1080         debug_msg_logger(LOG_INFO, __FUNCTION__);
1081
1082         if ((source_stat->st_mode & S_IFMT) ==(dest_stat->st_mode & S_IFMT)) {
1083                 /*  Same type  */
1084                 if (S_ISLNK(source_stat->st_mode)) {
1085                         if ((source_len = readlink(sourcepath, source_link, STRING_LENGTH - 1)) < 0
1086                                 || (dest_len   = readlink(destpath  , dest_link  , STRING_LENGTH - 1)) < 0
1087                         )
1088                                 return FALSE;
1089                         source_link[source_len] = '\0';
1090                         dest_link[dest_len]     = '\0';
1091                         if ((source_len != dest_len) || (strcmp(source_link, dest_link) != 0)) {
1092                                 unlink(destpath);
1093                                 symlink(source_link, destpath);
1094                         }
1095                         return TRUE;
1096                 }   /*  Else not a symlink  */
1097                 chmod(destpath, new_mode & ~S_IFMT);
1098                 chown(destpath, source_stat->st_uid, source_stat->st_gid);
1099                 return TRUE;
1100         }
1101         /*  Different types: unlink and create  */
1102         unlink(destpath);
1103         switch (source_stat->st_mode & S_IFMT) {
1104                 case S_IFSOCK:
1105                         if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0)
1106                                 break;
1107                         un_addr.sun_family = AF_UNIX;
1108                         snprintf(un_addr.sun_path, sizeof(un_addr.sun_path), "%s", destpath);
1109                         val = bind(fd,(struct sockaddr *) &un_addr,(int) sizeof un_addr);
1110                         close(fd);
1111                         if (val != 0 || chmod(destpath, new_mode & ~S_IFMT) != 0)
1112                                 break;
1113                         goto do_chown;
1114                 case S_IFLNK:
1115                         if ((val = readlink(sourcepath, symlink_val, STRING_LENGTH - 1)) < 0)
1116                                 break;
1117                         symlink_val[val] = '\0';
1118                         if (symlink(symlink_val, destpath) == 0)
1119                                 return TRUE;
1120                         break;
1121                 case S_IFREG:
1122                         if ((fd = open(destpath, O_RDONLY | O_CREAT, new_mode & ~S_IFMT)) < 0)
1123                                 break;
1124                         close(fd);
1125                         if (chmod(destpath, new_mode & ~S_IFMT) != 0)
1126                                 break;
1127                         goto do_chown;
1128                 case S_IFBLK:
1129                 case S_IFCHR:
1130                 case S_IFIFO:
1131                         if (mknod(destpath, new_mode, source_stat->st_rdev) != 0)
1132                                 break;
1133                         goto do_chown;
1134                 case S_IFDIR:
1135                         if (mkdir(destpath, new_mode & ~S_IFMT) != 0)
1136                                 break;
1137 do_chown:
1138                         if (chown(destpath, source_stat->st_uid, source_stat->st_gid) == 0)
1139                                 return TRUE;
1140                 /*break;*/
1141         }
1142         return FALSE;
1143 }   /*  End Function copy_inode  */
1144
1145 static void free_config(void)
1146 /*  [SUMMARY] Free the configuration information.
1147     [RETURNS] Nothing.
1148 */
1149 {
1150         struct config_entry_struct *c_entry;
1151         void *next;
1152
1153         debug_msg_logger(LOG_INFO, __FUNCTION__);
1154
1155         for (c_entry = first_config; c_entry != NULL; c_entry = next) {
1156                 unsigned int count;
1157
1158                 next = c_entry->next;
1159                 regfree(&c_entry->preg);
1160                 if (c_entry->action.what == AC_EXECUTE) {
1161                         for (count = 0; count < MAX_ARGS; ++count) {
1162                                 if (c_entry->u.execute.argv[count] == NULL)
1163                                         break;
1164                                 free(c_entry->u.execute.argv[count]);
1165                         }
1166                 }
1167                 free(c_entry);
1168         }
1169         first_config = NULL;
1170         last_config = NULL;
1171 }   /*  End Function free_config  */
1172
1173 static int get_uid_gid(int flag, const char *string)
1174 /*  [SUMMARY] Convert a string to a UID or GID value.
1175         <flag> "UID" or "GID".
1176         <string> The string.
1177     [RETURNS] The UID or GID value.
1178 */
1179 {
1180         struct passwd *pw_ent;
1181         struct group *grp_ent;
1182         static const char *msg;
1183
1184         if (ENABLE_DEVFSD_VERBOSE)
1185                 msg = "user";
1186
1187         debug_msg_logger(LOG_INFO, __FUNCTION__);
1188
1189         if (ENABLE_DEBUG && flag != UID && flag != GID)
1190                 msg_logger_and_die(LOG_ERR,"%s: flag != UID && flag != GID", __FUNCTION__);
1191
1192         if (isdigit(string[0]) ||((string[0] == '-') && isdigit(string[1])))
1193                 return atoi(string);
1194
1195         if (flag == UID && (pw_ent  = getpwnam(string)) != NULL)
1196                 return pw_ent->pw_uid;
1197
1198         if (flag == GID && (grp_ent = getgrnam(string)) != NULL)
1199                 return grp_ent->gr_gid;
1200         else if (ENABLE_DEVFSD_VERBOSE)
1201                 msg = "group";
1202
1203         if (ENABLE_DEVFSD_VERBOSE)
1204                 msg_logger(LOG_ERR,"unknown %s: %s, defaulting to %cid=0",  msg, string, msg[0]);
1205         return 0;
1206 }/*  End Function get_uid_gid  */
1207
1208 static mode_t get_mode(const char *string)
1209 /*  [SUMMARY] Convert a string to a mode value.
1210     <string> The string.
1211     [RETURNS] The mode value.
1212 */
1213 {
1214         mode_t mode;
1215         int i;
1216
1217         debug_msg_logger(LOG_INFO, __FUNCTION__);
1218
1219         if (isdigit(string[0]))
1220                 return strtoul(string, NULL, 8);
1221         if (strlen(string) != 9)
1222                 msg_logger_and_die(LOG_ERR, "bad mode: %s", string);
1223
1224         mode = 0;
1225         i = S_IRUSR;
1226         while (i > 0) {
1227                 if (string[0] == 'r' || string[0] == 'w' || string[0] == 'x')
1228                         mode += i;
1229                 i = i/2;
1230                 string++;
1231         }
1232         return mode;
1233 }   /*  End Function get_mode  */
1234
1235 static void signal_handler(int sig)
1236 {
1237         debug_msg_logger(LOG_INFO, __FUNCTION__);
1238
1239         caught_signal = TRUE;
1240         if (sig == SIGHUP)
1241                 caught_sighup = TRUE;
1242
1243         msg_logger(LOG_INFO, "Caught signal %d", sig);
1244 }   /*  End Function signal_handler  */
1245
1246 static const char *get_variable(const char *variable, void *info)
1247 {
1248         struct get_variable_info *gv_info = info;
1249         static char hostname[STRING_LENGTH], sbuf[STRING_LENGTH];
1250         const char *field_names[] = { "hostname", "mntpt", "devpath", "devname",
1251                                                                    "uid", "gid", "mode", hostname, mount_point,
1252                                                                    gv_info->devpath, gv_info->devname, 0 };
1253         int i;
1254
1255         debug_msg_logger(LOG_INFO, __FUNCTION__);
1256
1257         if (gethostname(hostname, STRING_LENGTH - 1) != 0)
1258                 msg_logger_and_die(LOG_ERR, "gethostname: %m");
1259
1260                 /* Here on error we should do exit(RV_SYS_ERROR), instead we do exit(EXIT_FAILURE) */
1261                 hostname[STRING_LENGTH - 1] = '\0';
1262
1263         /* index_in_str_array returns i>=0  */
1264         i = index_in_str_array(field_names, variable);
1265
1266         if (i > 6 || i < 0 || (i > 1 && gv_info == NULL))
1267                         return NULL;
1268         if (i >= 0 && i <= 3) {
1269                 debug_msg_logger(LOG_INFO, "%s: i=%d %s", __FUNCTION__, i, field_names[i + 7]);
1270                 return field_names[i + 7];
1271         }
1272
1273         if (i == 4)
1274                 sprintf(sbuf, "%u", gv_info->info->uid);
1275         else if (i == 5)
1276                 sprintf(sbuf, "%u", gv_info->info->gid);
1277         else if (i == 6)
1278                 sprintf(sbuf, "%o", gv_info->info->mode);
1279
1280         debug_msg_logger(LOG_INFO, "%s: %s", __FUNCTION__, sbuf);
1281
1282         return sbuf;
1283 }   /*  End Function get_variable  */
1284
1285 static void service(struct stat statbuf, char *path)
1286 {
1287         struct devfsd_notify_struct info;
1288
1289         debug_msg_logger(LOG_INFO, __FUNCTION__);
1290
1291         memset(&info, 0, sizeof info);
1292         info.type = DEVFSD_NOTIFY_REGISTERED;
1293         info.mode = statbuf.st_mode;
1294         info.major = major(statbuf.st_rdev);
1295         info.minor = minor(statbuf.st_rdev);
1296         info.uid = statbuf.st_uid;
1297         info.gid = statbuf.st_gid;
1298         snprintf(info.devname, sizeof(info.devname), "%s", path + strlen(mount_point) + 1);
1299         info.namelen = strlen(info.devname);
1300         service_name(&info);
1301         if (S_ISDIR(statbuf.st_mode))
1302                 dir_operation(SERVICE, path, 0, NULL);
1303 }
1304
1305 static void dir_operation(int type, const char * dir_name, int var, unsigned long *event_mask)
1306 /*  [SUMMARY] Scan a directory tree and generate register events on leaf nodes.
1307         <flag> To choose which function to perform
1308         <dp> The directory pointer. This is closed upon completion.
1309     <dir_name> The name of the directory.
1310         <rootlen> string length parameter.
1311     [RETURNS] Nothing.
1312 */
1313 {
1314         struct stat statbuf;
1315         DIR *dp;
1316         struct dirent *de;
1317         char path[STRING_LENGTH];
1318
1319         debug_msg_logger(LOG_INFO, __FUNCTION__);
1320
1321         if ((dp = opendir(dir_name))==NULL) {
1322                 debug_msg_logger(LOG_ERR, "opendir: %s: %m", dir_name);
1323                 return;
1324         }
1325
1326         while ((de = readdir(dp)) != NULL) {
1327
1328                 if (de->d_name && DOT_OR_DOTDOT(de->d_name))
1329                         continue;
1330                 snprintf(path, sizeof(path), "%s/%s", dir_name, de->d_name);
1331                 debug_msg_logger(LOG_ERR, "%s: %s", __FUNCTION__, path);
1332
1333                 if (lstat(path, &statbuf) != 0) {
1334                         debug_msg_logger(LOG_ERR, "%s: %s: %m", __FUNCTION__, path);
1335                         continue;
1336                 }
1337                 switch (type) {
1338                         case SERVICE:
1339                                 service(statbuf, path);
1340                                 break;
1341                         case RESTORE:
1342                                 restore(path, statbuf, var);
1343                                 break;
1344                         case READ_CONFIG:
1345                                 read_config_file(path, var, event_mask);
1346                                 break;
1347                 }
1348         }
1349         closedir(dp);
1350 }   /*  End Function do_scan_and_service  */
1351
1352 static int mksymlink(const char *oldpath, const char *newpath)
1353 /*  [SUMMARY] Create a symlink, creating intervening directories as required.
1354     <oldpath> The string contained in the symlink.
1355     <newpath> The name of the new symlink.
1356     [RETURNS] 0 on success, else -1.
1357 */
1358 {
1359         debug_msg_logger(LOG_INFO, __FUNCTION__);
1360
1361         if (!make_dir_tree(newpath))
1362                 return -1;
1363
1364         if (symlink(oldpath, newpath) != 0) {
1365                 if (errno != EEXIST) {
1366                         debug_msg_logger(LOG_ERR, "%s: %s to %s: %m", __FUNCTION__, oldpath, newpath);
1367                         return -1;
1368                 }
1369         }
1370         return 0;
1371 }   /*  End Function mksymlink  */
1372
1373
1374 static int make_dir_tree(const char *path)
1375 /*  [SUMMARY] Creating intervening directories for a path as required.
1376     <path> The full pathname(including the leaf node).
1377     [RETURNS] TRUE on success, else FALSE.
1378 */
1379 {
1380         debug_msg_logger(LOG_INFO, __FUNCTION__);
1381
1382         if (bb_make_directory(dirname((char *)path), -1, FILEUTILS_RECUR) == -1) {
1383                 debug_msg_logger(LOG_ERR, "%s: %s: %m",__FUNCTION__, path);
1384                 return FALSE;
1385         }
1386         return TRUE;
1387 } /*  End Function make_dir_tree  */
1388
1389 static int expand_expression(char *output, unsigned int outsize,
1390                               const char *input,
1391                               const char *(*get_variable_func)(const char *variable, void *info),
1392                               void *info,
1393                               const char *devname,
1394                               const regmatch_t *ex, unsigned int numexp)
1395 /*  [SUMMARY] Expand environment variables and regular subexpressions in string.
1396     <output> The output expanded expression is written here.
1397     <length> The size of the output buffer.
1398     <input> The input expression. This may equal <<output>>.
1399     <get_variable> A function which will be used to get variable values. If
1400     this returns NULL, the environment is searched instead. If this is NULL,
1401     only the environment is searched.
1402     <info> An arbitrary pointer passed to <<get_variable>>.
1403     <devname> Device name; specifically, this is the string that contains all
1404     of the regular subexpressions.
1405     <ex> Array of start / end offsets into info->devname for each subexpression
1406     <numexp> Number of regular subexpressions found in <<devname>>.
1407     [RETURNS] TRUE on success, else FALSE.
1408 */
1409 {
1410         char temp[STRING_LENGTH];
1411
1412         debug_msg_logger(LOG_INFO, __FUNCTION__);
1413
1414         if (!st_expr_expand(temp, STRING_LENGTH, input, get_variable_func, info))
1415                 return FALSE;
1416         expand_regexp(output, outsize, temp, devname, ex, numexp);
1417         return TRUE;
1418 }   /*  End Function expand_expression  */
1419
1420 static void expand_regexp(char *output, size_t outsize, const char *input,
1421                            const char *devname,
1422                            const regmatch_t *ex, unsigned int numex)
1423 /*  [SUMMARY] Expand all occurrences of the regular subexpressions \0 to \9.
1424     <output> The output expanded expression is written here.
1425     <outsize> The size of the output buffer.
1426     <input> The input expression. This may NOT equal <<output>>, because
1427     supporting that would require yet another string-copy. However, it's not
1428     hard to write a simple wrapper function to add this functionality for those
1429     few cases that need it.
1430     <devname> Device name; specifically, this is the string that contains all
1431     of the regular subexpressions.
1432     <ex> An array of start and end offsets into <<devname>>, one for each
1433     subexpression
1434     <numex> Number of subexpressions in the offset-array <<ex>>.
1435     [RETURNS] Nothing.
1436 */
1437 {
1438         const char last_exp = '0' - 1 + numex;
1439         int c = -1;
1440
1441         debug_msg_logger(LOG_INFO, __FUNCTION__);
1442
1443         /*  Guarantee NULL termination by writing an explicit '\0' character into
1444         the very last byte  */
1445         if (outsize)
1446                 output[--outsize] = '\0';
1447         /*  Copy the input string into the output buffer, replacing '\\' with '\'
1448         and '\0' .. '\9' with subexpressions 0 .. 9, if they exist. Other \x
1449         codes are deleted  */
1450         while ((c != '\0') && (outsize != 0)) {
1451                 c = *input;
1452                 ++input;
1453                 if (c == '\\') {
1454                         c = *input;
1455                         ++input;
1456                         if (c != '\\') {
1457                                 if ((c >= '0') && (c <= last_exp)) {
1458                                         const regmatch_t *subexp = ex + (c - '0');
1459                                         unsigned int sublen = subexp->rm_eo - subexp->rm_so;
1460
1461                                         /*  Range checking  */
1462                                         if (sublen > outsize)
1463                                                 sublen = outsize;
1464                                         strncpy(output, devname + subexp->rm_so, sublen);
1465                                         output += sublen;
1466                                         outsize -= sublen;
1467                                 }
1468                                 continue;
1469                         }
1470                 }
1471                 *output = c;
1472                 ++output;
1473                 --outsize;
1474         } /* while */
1475 }   /*  End Function expand_regexp  */
1476
1477
1478 /* from compat_name.c */
1479
1480 struct translate_struct
1481 {
1482         const char *match;    /*  The string to match to(up to length)                */
1483         const char *format;   /*  Format of output, "%s" takes data past match string,
1484                         NULL is effectively "%s"(just more efficient)       */
1485 };
1486
1487 static struct translate_struct translate_table[] =
1488 {
1489         {"sound/",     NULL},
1490         {"printers/",  "lp%s"},
1491         {"v4l/",       NULL},
1492         {"parports/",  "parport%s"},
1493         {"fb/",        "fb%s"},
1494         {"netlink/",   NULL},
1495         {"loop/",      "loop%s"},
1496         {"floppy/",    "fd%s"},
1497         {"rd/",        "ram%s"},
1498         {"md/",        "md%s"},         /*  Meta-devices                         */
1499         {"vc/",        "tty%s"},
1500         {"misc/",      NULL},
1501         {"isdn/",      NULL},
1502         {"pg/",        "pg%s"},         /*  Parallel port generic ATAPI interface*/
1503         {"i2c/",       "i2c-%s"},
1504         {"staliomem/", "staliomem%s"},  /*  Stallion serial driver control       */
1505         {"tts/E",      "ttyE%s"},       /*  Stallion serial driver               */
1506         {"cua/E",      "cue%s"},        /*  Stallion serial driver callout       */
1507         {"tts/R",      "ttyR%s"},       /*  Rocketport serial driver             */
1508         {"cua/R",      "cur%s"},        /*  Rocketport serial driver callout     */
1509         {"ip2/",       "ip2%s"},        /*  Computone serial driver control      */
1510         {"tts/F",      "ttyF%s"},       /*  Computone serial driver              */
1511         {"cua/F",      "cuf%s"},        /*  Computone serial driver callout      */
1512         {"tts/C",      "ttyC%s"},       /*  Cyclades serial driver               */
1513         {"cua/C",      "cub%s"},        /*  Cyclades serial driver callout       */
1514         {"tts/",       "ttyS%s"},       /*  Generic serial: must be after others */
1515         {"cua/",       "cua%s"},        /*  Generic serial: must be after others */
1516         {"input/js",   "js%s"},         /*  Joystick driver                      */
1517         {NULL,         NULL}
1518 };
1519
1520 const char *get_old_name(const char *devname, unsigned int namelen,
1521                           char *buffer, unsigned int major, unsigned int minor)
1522 /*  [SUMMARY] Translate a kernel-supplied name into an old name.
1523     <devname> The device name provided by the kernel.
1524     <namelen> The length of the name.
1525     <buffer> A buffer that may be used. This should be at least 128 bytes long.
1526     <major> The major number for the device.
1527     <minor> The minor number for the device.
1528     [RETURNS] A pointer to the old name if known, else NULL.
1529 */
1530 {
1531         const char *compat_name = NULL;
1532         char *ptr;
1533         struct translate_struct *trans;
1534         unsigned int i;
1535         char mode;
1536         int indexx;
1537         const char *pty1;
1538         const char *pty2;
1539         size_t len;
1540         /* 1 to 5  "scsi/" , 6 to 9 "ide/host", 10 sbp/, 11 vcc/, 12 pty/ */
1541         static const char *const fmt[] = {
1542                 NULL ,
1543                 "sg%u",                 /* scsi/generic */
1544                 NULL,                   /* scsi/disc */
1545                 "sr%u",                 /* scsi/cd */
1546                 NULL,                   /* scsi/part */
1547                 "nst%u%c",              /* scsi/mt */
1548                 "hd%c"  ,               /* ide/host/disc */
1549                 "hd%c"  ,               /* ide/host/cd */
1550                 "hd%c%s",               /* ide/host/part */
1551                 "%sht%d",               /* ide/host/mt */
1552                 "sbpcd%u",              /* sbp/ */
1553                 "vcs%s",                /* vcc/ */
1554                 "%cty%c%c",             /* pty/ */
1555                 NULL
1556         };
1557
1558         debug_msg_logger(LOG_INFO, __FUNCTION__);
1559
1560         for (trans = translate_table; trans->match != NULL; ++trans) {
1561                  len = strlen(trans->match);
1562
1563                 if (strncmp(devname, trans->match, len) == 0) {
1564                         if (trans->format == NULL)
1565                                 return devname + len;
1566                         sprintf(buffer, trans->format, devname + len);
1567                         return buffer;
1568                 }
1569         }
1570
1571         ptr = (strrchr(devname, '/') + 1);
1572         i = scan_dev_name(devname, namelen, ptr);
1573
1574         if (i > 0 && i < 13)
1575                 compat_name = buffer;
1576         else
1577                 return NULL;
1578
1579         debug_msg_logger(LOG_INFO, "%s: scan_dev_name = %d", __FUNCTION__, i);
1580
1581         /* 1 == scsi/generic, 3 == scsi/cd, 10 == sbp/ */
1582         if (i == 1 || i == 3 || i == 10)
1583                 sprintf(buffer, fmt[i], minor);
1584
1585         /* 2 ==scsi/disc, 4 == scsi/part */
1586         if (i == 2 || i == 4)
1587                 compat_name = write_old_sd_name(buffer, major, minor,((i == 2)?"":(ptr + 4)));
1588
1589         /* 5 == scsi/mt */
1590         if (i == 5) {
1591                 mode = ptr[2];
1592                 if (mode == 'n')
1593                         mode = '\0';
1594                 sprintf(buffer, fmt[i], minor & 0x1f, mode);
1595                 if (devname[namelen - 1] != 'n')
1596                         ++compat_name;
1597         }
1598         /* 6 == ide/host/disc, 7 == ide/host/cd, 8 == ide/host/part */
1599         if (i == 6 || i == 7 || i == 8)
1600                 /* last arg should be ignored for i == 6 or i== 7 */
1601                 sprintf(buffer, fmt[i] , get_old_ide_name(major, minor), ptr + 4);
1602
1603         /* 9 ==  ide/host/mt */
1604         if (i == 9)
1605                 sprintf(buffer, fmt[i], ptr + 2, minor & 0x7f);
1606
1607         /*  11 == vcc/ */
1608         if (i == 11) {
1609                 sprintf(buffer, fmt[i], devname + 4);
1610                 if (buffer[3] == '0')
1611                         buffer[3] = '\0';
1612         }
1613         /* 12 ==  pty/ */
1614         if (i == 12) {
1615                 pty1 = "pqrstuvwxyzabcde";
1616                 pty2 = "0123456789abcdef";
1617                 indexx = atoi(devname + 5);
1618                 sprintf(buffer, fmt[i], (devname[4] == 'm') ? 'p' : 't', pty1[indexx >> 4], pty2[indexx & 0x0f]);
1619         }
1620
1621         if (ENABLE_DEBUG && compat_name != NULL)
1622                 msg_logger(LOG_INFO, "%s: compat_name  %s", __FUNCTION__, compat_name);
1623
1624         return compat_name;
1625 }   /*  End Function get_old_name  */
1626
1627 static char get_old_ide_name(unsigned int major, unsigned int minor)
1628 /*  [SUMMARY] Get the old IDE name for a device.
1629     <major> The major number for the device.
1630     <minor> The minor number for the device.
1631     [RETURNS] The drive letter.
1632 */
1633 {
1634         char letter = 'y';      /* 121 */
1635         char c = 'a';           /*  97 */
1636         int i = IDE0_MAJOR;
1637
1638         debug_msg_logger(LOG_INFO, __FUNCTION__);
1639
1640         /* I hope it works like the previous code as it saves a few bytes. Tito ;P */
1641         do {
1642                 if (i == IDE0_MAJOR || i == IDE1_MAJOR || i == IDE2_MAJOR
1643                  || i == IDE3_MAJOR || i == IDE4_MAJOR || i == IDE5_MAJOR
1644                  || i == IDE6_MAJOR || i == IDE7_MAJOR || i == IDE8_MAJOR
1645                  || i == IDE9_MAJOR
1646                 ) {
1647                         if ((unsigned int)i == major) {
1648                                 letter = c;
1649                                 break;
1650                         }
1651                         c += 2;
1652                 }
1653                 i++;
1654         } while (i <= IDE9_MAJOR);
1655
1656         if (minor > 63)
1657                 ++letter;
1658         return letter;
1659 }   /*  End Function get_old_ide_name  */
1660
1661 static char *write_old_sd_name(char *buffer,
1662                                 unsigned int major, unsigned int minor,
1663                                 const char *part)
1664 /*  [SUMMARY] Write the old SCSI disc name to a buffer.
1665     <buffer> The buffer to write to.
1666     <major> The major number for the device.
1667     <minor> The minor number for the device.
1668     <part> The partition string. Must be "" for a whole-disc entry.
1669     [RETURNS] A pointer to the buffer on success, else NULL.
1670 */
1671 {
1672         unsigned int disc_index;
1673
1674         debug_msg_logger(LOG_INFO, __FUNCTION__);
1675
1676         if (major == 8) {
1677                 sprintf(buffer, "sd%c%s", 'a' + (minor >> 4), part);
1678                 return buffer;
1679         }
1680         if ((major > 64) && (major < 72)) {
1681                 disc_index = ((major - 64) << 4) +(minor >> 4);
1682                 if (disc_index < 26)
1683                         sprintf(buffer, "sd%c%s", 'a' + disc_index, part);
1684                 else
1685                         sprintf(buffer, "sd%c%c%s", 'a' +(disc_index / 26) - 1, 'a' + disc_index % 26, part);
1686                 return buffer;
1687         }
1688         return NULL;
1689 }   /*  End Function write_old_sd_name  */
1690
1691
1692 /*  expression.c */
1693
1694 /*EXPERIMENTAL_FUNCTION*/
1695
1696 int st_expr_expand(char *output, unsigned int length, const char *input,
1697                      const char *(*get_variable_func)(const char *variable,
1698                                                   void *info),
1699                      void *info)
1700 /*  [SUMMARY] Expand an expression using Borne Shell-like unquoted rules.
1701     <output> The output expanded expression is written here.
1702     <length> The size of the output buffer.
1703     <input> The input expression. This may equal <<output>>.
1704     <get_variable> A function which will be used to get variable values. If
1705     this returns NULL, the environment is searched instead. If this is NULL,
1706     only the environment is searched.
1707     <info> An arbitrary pointer passed to <<get_variable>>.
1708     [RETURNS] TRUE on success, else FALSE.
1709 */
1710 {
1711         char ch;
1712         unsigned int len;
1713         unsigned int out_pos = 0;
1714         const char *env;
1715         const char *ptr;
1716         struct passwd *pwent;
1717         char buffer[BUFFER_SIZE], tmp[STRING_LENGTH];
1718
1719         debug_msg_logger(LOG_INFO, __FUNCTION__);
1720
1721         if (length > BUFFER_SIZE)
1722                 length = BUFFER_SIZE;
1723         for (; TRUE; ++input) {
1724                 switch (ch = *input) {
1725                         case '$':
1726                                 /*  Variable expansion  */
1727                                 input = expand_variable(buffer, length, &out_pos, ++input, get_variable_func, info);
1728                                 if (input == NULL)
1729                                         return FALSE;
1730                                 break;
1731                         case '~':
1732                                 /*  Home directory expansion  */
1733                                 ch = input[1];
1734                                 if (isspace(ch) ||(ch == '/') ||(ch == '\0')) {
1735                                         /* User's own home directory: leave separator for next time */
1736                                         if ((env = getenv("HOME")) == NULL) {
1737                                                 msg_logger(LOG_INFO, bb_msg_variable_not_found, "HOME");
1738                                                 return FALSE;
1739                                         }
1740                                         len = strlen(env);
1741                                         if (len + out_pos >= length)
1742                                                 goto st_expr_expand_out;
1743                                         memcpy(buffer + out_pos, env, len + 1);
1744                                         out_pos += len;
1745                                         continue;
1746                                 }
1747                                 /*  Someone else's home directory  */
1748                                 for (ptr = ++input; !isspace(ch) && (ch != '/') && (ch != '\0'); ch = *++ptr)
1749                                         /* VOID */ ;
1750                                 len = ptr - input;
1751                                 if (len >= sizeof tmp)
1752                                         goto st_expr_expand_out;
1753                                 safe_memcpy(tmp, input, len);
1754                                 input = ptr - 1;
1755                                 if ((pwent = getpwnam(tmp)) == NULL) {
1756                                         msg_logger(LOG_INFO, "no pwent for: %s", tmp);
1757                                         return FALSE;
1758                                 }
1759                                 len = strlen(pwent->pw_dir);
1760                                 if (len + out_pos >= length)
1761                                         goto st_expr_expand_out;
1762                                 memcpy(buffer + out_pos, pwent->pw_dir, len + 1);
1763                                 out_pos += len;
1764                                 break;
1765                         case '\0':
1766                         /* Falltrough */
1767                         default:
1768                                 if (out_pos >= length)
1769                                         goto st_expr_expand_out;
1770                                 buffer[out_pos++] = ch;
1771                                 if (ch == '\0') {
1772                                         memcpy(output, buffer, out_pos);
1773                                         return TRUE;
1774                                 }
1775                                 break;
1776                         /* esac */
1777                 }
1778         }
1779         return FALSE;
1780 st_expr_expand_out:
1781         msg_logger(LOG_INFO, bb_msg_small_buffer);
1782         return FALSE;
1783 }   /*  End Function st_expr_expand  */
1784
1785
1786 /*  Private functions follow  */
1787
1788 static const char *expand_variable(char *buffer, unsigned int length,
1789                                     unsigned int *out_pos, const char *input,
1790                                     const char *(*func)(const char *variable,
1791                                                          void *info),
1792                                     void *info)
1793 /*  [SUMMARY] Expand a variable.
1794     <buffer> The buffer to write to.
1795     <length> The length of the output buffer.
1796     <out_pos> The current output position. This is updated.
1797     <input> A pointer to the input character pointer.
1798     <func> A function which will be used to get variable values. If this
1799     returns NULL, the environment is searched instead. If this is NULL, only
1800     the environment is searched.
1801     <info> An arbitrary pointer passed to <<func>>.
1802     <errfp> Diagnostic messages are written here.
1803     [RETURNS] A pointer to the end of this subexpression on success, else NULL.
1804 */
1805 {
1806         char ch;
1807         int len;
1808         unsigned int open_braces;
1809         const char *env, *ptr;
1810         char tmp[STRING_LENGTH];
1811
1812         debug_msg_logger(LOG_INFO, __FUNCTION__);
1813
1814         ch = input[0];
1815         if (ch == '$') {
1816                 /*  Special case for "$$": PID  */
1817                 sprintf(tmp, "%d",(int) getpid());
1818                 len = strlen(tmp);
1819                 if (len + *out_pos >= length)
1820                         goto expand_variable_out;
1821
1822                 memcpy(buffer + *out_pos, tmp, len + 1);
1823                 out_pos += len;
1824                 return input;
1825         }
1826         /*  Ordinary variable expansion, possibly in braces  */
1827         if (ch != '{') {
1828                 /*  Simple variable expansion  */
1829                 for (ptr = input; isalnum(ch) || (ch == '_') || (ch == ':'); ch = *++ptr)
1830                         /* VOID */ ;
1831                 len = ptr - input;
1832                 if ((size_t)len >= sizeof tmp)
1833                         goto expand_variable_out;
1834
1835                 safe_memcpy(tmp, input, len);
1836                 input = ptr - 1;
1837                 if ((env = get_variable_v2(tmp, func, info)) == NULL) {
1838                         msg_logger(LOG_INFO, bb_msg_variable_not_found, tmp);
1839                         return NULL;
1840                 }
1841                 len = strlen(env);
1842                 if (len + *out_pos >= length)
1843                         goto expand_variable_out;
1844
1845                 memcpy(buffer + *out_pos, env, len + 1);
1846                 *out_pos += len;
1847                 return input;
1848         }
1849         /*  Variable in braces: check for ':' tricks  */
1850         ch = *++input;
1851         for (ptr = input; isalnum(ch) || (ch == '_'); ch = *++ptr)
1852                 /* VOID */;
1853         if (ch == '}') {
1854                 /*  Must be simple variable expansion with "${var}"  */
1855                 len = ptr - input;
1856                 if ((size_t)len >= sizeof tmp)
1857                         goto expand_variable_out;
1858
1859                 safe_memcpy(tmp, input, len);
1860                 ptr = expand_variable(buffer, length, out_pos, tmp, func, info);
1861                 if (ptr == NULL)
1862                         return NULL;
1863                 return input + len;
1864         }
1865         if (ch != ':' || ptr[1] != '-') {
1866                 msg_logger(LOG_INFO, "illegal char in var name");
1867                 return NULL;
1868         }
1869         /*  It's that handy "${var:-word}" expression. Check if var is defined  */
1870         len = ptr - input;
1871         if ((size_t)len >= sizeof tmp)
1872                 goto expand_variable_out;
1873
1874         safe_memcpy(tmp, input, len);
1875         /*  Move input pointer to ':'  */
1876         input = ptr;
1877         /*  First skip to closing brace, taking note of nested expressions  */
1878         ptr += 2;
1879         ch = ptr[0];
1880         for (open_braces = 1; open_braces > 0; ch = *++ptr) {
1881                 switch (ch) {
1882                         case '{':
1883                                 ++open_braces;
1884                                 break;
1885                         case '}':
1886                                 --open_braces;
1887                                 break;
1888                         case '\0':
1889                                 msg_logger(LOG_INFO,"\"}\" not found in: %s", input);
1890                                 return NULL;
1891                         default:
1892                                 break;
1893                 }
1894         }
1895         --ptr;
1896         /*  At this point ptr should point to closing brace of "${var:-word}"  */
1897         if ((env = get_variable_v2(tmp, func, info)) != NULL) {
1898                 /*  Found environment variable, so skip the input to the closing brace
1899                         and return the variable  */
1900                 input = ptr;
1901                 len = strlen(env);
1902                 if (len + *out_pos >= length)
1903                         goto expand_variable_out;
1904
1905                 memcpy(buffer + *out_pos, env, len + 1);
1906                 *out_pos += len;
1907                 return input;
1908         }
1909         /*  Environment variable was not found, so process word. Advance input
1910         pointer to start of word in "${var:-word}"  */
1911         input += 2;
1912         len = ptr - input;
1913         if ((size_t)len >= sizeof tmp)
1914                 goto expand_variable_out;
1915
1916         safe_memcpy(tmp, input, len);
1917         input = ptr;
1918         if (!st_expr_expand(tmp, STRING_LENGTH, tmp, func, info))
1919                 return NULL;
1920         len = strlen(tmp);
1921         if (len + *out_pos >= length)
1922                 goto expand_variable_out;
1923
1924         memcpy(buffer + *out_pos, tmp, len + 1);
1925         *out_pos += len;
1926         return input;
1927 expand_variable_out:
1928         msg_logger(LOG_INFO, bb_msg_small_buffer);
1929         return NULL;
1930 }   /*  End Function expand_variable  */
1931
1932
1933 static const char *get_variable_v2(const char *variable,
1934                                   const char *(*func)(const char *variable, void *info),
1935                                  void *info)
1936 /*  [SUMMARY] Get a variable from the environment or .
1937     <variable> The variable name.
1938     <func> A function which will be used to get the variable. If this returns
1939     NULL, the environment is searched instead. If this is NULL, only the
1940     environment is searched.
1941     [RETURNS] The value of the variable on success, else NULL.
1942 */
1943 {
1944         const char *value;
1945
1946         debug_msg_logger(LOG_INFO, __FUNCTION__);
1947
1948         if (func != NULL) {
1949                 value = (*func)(variable, info);
1950                 if (value != NULL)
1951                         return value;
1952         }
1953         return getenv(variable);
1954 }   /*  End Function get_variable  */
1955
1956 /* END OF CODE */