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