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