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