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