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