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