old gcc
[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 he 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
1437         if (bb_make_directory( (char *)path,  S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH , FILEUTILS_RECUR )==-1)
1438         {
1439 #ifdef CONFIG_DEVFSD_VERBOSE
1440                 msg_logger( NO_DIE, LOG_ERR, "make_dir_tree(): %s: %m\n", path);
1441 #endif
1442                 return (FALSE);
1443         }
1444         return(TRUE);
1445 } /*  End Function make_dir_tree  */
1446
1447 static int expand_expression(char *output, unsigned int outsize,
1448                               const char *input,
1449                               const char *(*get_variable_func)(const char *variable, void *info),
1450                               void *info,
1451                               const char *devname,
1452                               const regmatch_t *ex, unsigned int numexp)
1453 /*  [SUMMARY] Expand enviroment variables and regular subexpressions in string.
1454     <output> The output expanded expression is written here.
1455     <length> The size of the output buffer.
1456     <input> The input expression. This may equal <<output>>.
1457     <get_variable> A function which will be used to get variable values. If
1458     this returns NULL, the environment is searched instead. If this is NULL,
1459     only the environment is searched.
1460     <info> An arbitrary pointer passed to <<get_variable>>.
1461     <devname> Device name; specifically, this is the string that contains all
1462     of the regular subexpressions.
1463     <ex> Array of start / end offsets into info->devname for each subexpression
1464     <numexp> Number of regular subexpressions found in <<devname>>.
1465     [RETURNS] TRUE on success, else FALSE.
1466 */
1467 {
1468         char temp[STRING_LENGTH];
1469
1470 #ifdef CONFIG_DEVFSD_DEBUG
1471         msg_logger( NO_DIE, LOG_INFO, "expand_expression()\n");
1472 #endif
1473
1474         if ( !st_expr_expand (temp, STRING_LENGTH, input, get_variable_func, info) )
1475                 return (FALSE);
1476         expand_regexp (output, outsize, temp, devname, ex, numexp);
1477         return (TRUE);
1478 }   /*  End Function expand_expression  */
1479
1480 static void expand_regexp (char *output, size_t outsize, const char *input,
1481                            const char *devname,
1482                            const regmatch_t *ex, unsigned int numex )
1483 /*  [SUMMARY] Expand all occurrences of the regular subexpressions \0 to \9.
1484     <output> The output expanded expression is written here.
1485     <outsize> The size of the output buffer.
1486     <input> The input expression. This may NOT equal <<output>>, because
1487     supporting that would require yet another string-copy. However, it's not
1488     hard to write a simple wrapper function to add this functionality for those
1489     few cases that need it.
1490     <devname> Device name; specifically, this is the string that contains all
1491     of the regular subexpressions.
1492     <ex> An array of start and end offsets into <<devname>>, one for each
1493     subexpression
1494     <numex> Number of subexpressions in the offset-array <<ex>>.
1495     [RETURNS] Nothing.
1496 */
1497 {
1498         const char last_exp = '0' - 1 + numex;
1499         int c = -1;
1500
1501 #ifdef CONFIG_DEVFSD_DEBUG
1502         msg_logger( NO_DIE, LOG_INFO, "expand_regexp()\n");
1503 #endif
1504
1505         /*  Guarantee NULL termination by writing an explicit '\0' character into
1506         the very last byte  */
1507         if (outsize)
1508                 output[--outsize] = '\0';
1509         /*  Copy the input string into the output buffer, replacing '\\' with '\'
1510         and '\0' .. '\9' with subexpressions 0 .. 9, if they exist. Other \x
1511         codes are deleted  */
1512         while ( (c != '\0') && (outsize != 0) )
1513         {
1514                 c = *input;
1515                 ++input;
1516                 if (c == '\\')
1517                 {
1518                         c = *input;
1519                         ++input;
1520                         if (c != '\\')
1521                         {
1522                                 if ((c >= '0') && (c <= last_exp))
1523                                 {
1524                                         const regmatch_t *subexp = ex + (c - '0');
1525                                         unsigned int sublen = subexp->rm_eo - subexp->rm_so;
1526
1527                                         /*  Range checking  */
1528                                         if (sublen > outsize)
1529                                                 sublen = outsize;
1530                                         strncpy (output, devname + subexp->rm_so, sublen);
1531                                         output += sublen;
1532                                         outsize -= sublen;
1533                                 }
1534                                 continue;
1535                         }
1536                 }
1537                 *output = c;
1538                 ++output;
1539                 --outsize;
1540         } /* while */
1541 }   /*  End Function expand_regexp  */
1542
1543
1544 /* from compat_name.c */
1545
1546 struct translate_struct
1547 {
1548         char *match;    /*  The string to match to (up to length)                */
1549         char *format;   /*  Format of output, "%s" takes data past match string,
1550                         NULL is effectively "%s" (just more efficient)       */
1551 };
1552
1553 static struct translate_struct translate_table[] =
1554 {
1555         {"sound/",     NULL},
1556         {"printers/",  "lp%s"},
1557         {"v4l/",       NULL},
1558         {"parports/",  "parport%s"},
1559         {"fb/",        "fb%s"},
1560         {"netlink/",   NULL},
1561         {"loop/",      "loop%s"},
1562         {"floppy/",    "fd%s"},
1563         {"rd/",        "ram%s"},
1564         {"md/",        "md%s"},         /*  Meta-devices                         */
1565         {"vc/",        "tty%s"},
1566         {"misc/",      NULL},
1567         {"isdn/",      NULL},
1568         {"pg/",        "pg%s"},         /*  Parallel port generic ATAPI interface*/
1569         {"i2c/",       "i2c-%s"},
1570         {"staliomem/", "staliomem%s"},  /*  Stallion serial driver control       */
1571         {"tts/E",      "ttyE%s"},       /*  Stallion serial driver               */
1572         {"cua/E",      "cue%s"},        /*  Stallion serial driver callout       */
1573         {"tts/R",      "ttyR%s"},       /*  Rocketport serial driver             */
1574         {"cua/R",      "cur%s"},        /*  Rocketport serial driver callout     */
1575         {"ip2/",       "ip2%s"},        /*  Computone serial driver control      */
1576         {"tts/F",      "ttyF%s"},       /*  Computone serial driver              */
1577         {"cua/F",      "cuf%s"},        /*  Computone serial driver callout      */
1578         {"tts/C",      "ttyC%s"},       /*  Cyclades serial driver               */
1579         {"cua/C",      "cub%s"},        /*  Cyclades serial driver callout       */
1580         {"tts/",       "ttyS%s"},       /*  Generic serial: must be after others */
1581         {"cua/",       "cua%s"},        /*  Generic serial: must be after others */
1582         {"input/js",   "js%s"},         /*  Joystick driver                      */
1583         {NULL,         NULL}
1584 };
1585
1586 const char *get_old_name (const char *devname, unsigned int namelen,
1587                           char *buffer, unsigned int major, unsigned int minor)
1588 /*  [SUMMARY] Translate a kernel-supplied name into an old name.
1589     <devname> The device name provided by the kernel.
1590     <namelen> The length of the name.
1591     <buffer> A buffer that may be used. This should be at least 128 bytes long.
1592     <major> The major number for the device.
1593     <minor> The minor number for the device.
1594     [RETURNS] A pointer to the old name if known, else NULL.
1595 */
1596 {
1597         const char *compat_name = NULL;
1598         char *ptr;
1599         struct translate_struct *trans;
1600
1601 #ifdef CONFIG_DEVFSD_DEBUG
1602         msg_logger( NO_DIE, LOG_INFO, "get_old_name()\n");
1603 #endif
1604
1605         for (trans = translate_table; trans->match != NULL; ++trans)
1606         {
1607                 size_t len = strlen (trans->match);
1608
1609                 if (strncmp (devname, trans->match, len) == 0)
1610                 {
1611                         if (trans->format == NULL)
1612                                 return (devname + len);
1613                         sprintf (buffer, trans->format, devname + len);
1614                         return (buffer);
1615                 }
1616         }
1617         if (strncmp (devname, "sbp/", 4) == 0)
1618         {
1619                 sprintf (buffer, "sbpcd%u", minor);
1620                 compat_name = buffer;
1621         }
1622         else if (strncmp (devname, "scsi/", 5) == 0)
1623         {   /*  All SCSI devices  */
1624                 if (strcmp (devname + namelen - 7, "generic") == 0)
1625                 {
1626                         sprintf (buffer, "sg%u", minor);
1627                         compat_name = buffer;
1628                 }
1629                 else if (strncmp (ptr = (strrchr (devname, '/') + 1), "mt", 2) == 0)
1630                 {
1631                         char mode = ptr[2];
1632
1633                         if (mode == 'n')
1634                                 mode = '\0';
1635                         sprintf (buffer, "nst%u%c", minor & 0x1f, mode);
1636                         compat_name = buffer;
1637                         if (devname[namelen - 1] != 'n')
1638                                 ++compat_name;
1639                 }
1640                 else if (strcmp (devname + namelen - 2, "cd") == 0)
1641                 {
1642                         sprintf (buffer, "sr%u", minor);
1643                         compat_name = buffer;
1644                 }
1645                 else if (strcmp (devname + namelen - 4, "disc") == 0)
1646                         compat_name = write_old_sd_name (buffer, major, minor, "");
1647                 else if (strncmp (ptr = (strrchr (devname, '/') + 1), "part", 4) == 0)
1648                         compat_name = write_old_sd_name (buffer, major, minor, ptr + 4);
1649                 return (compat_name);
1650         }
1651         else if (strncmp (devname, "ide/host", 8) == 0)
1652         {   /*  All IDE devices  */
1653                 if (strncmp (ptr = (strrchr (devname, '/') + 1), "mt", 2) == 0)
1654                 {
1655                         sprintf (buffer, "%sht%d", ptr + 2, minor & 0x7f);
1656                         compat_name = buffer;
1657                 }
1658                 else if (strcmp (devname + namelen - 4, "disc") == 0)
1659                 {
1660                         sprintf ( buffer, "hd%c", get_old_ide_name (major, minor) );
1661                         compat_name = buffer;
1662                 }
1663                 else if (strncmp (ptr = (strrchr (devname, '/') + 1), "part", 4) == 0)
1664                 {
1665                         sprintf (buffer, "hd%c%s", get_old_ide_name (major, minor), ptr + 4);
1666                         compat_name = buffer;
1667                 }
1668                 else if (strcmp (devname + namelen - 2, "cd") == 0)
1669                 {
1670                         sprintf ( buffer, "hd%c", get_old_ide_name (major, minor) );
1671                         compat_name = buffer;
1672                 }
1673                 return (compat_name);
1674         }
1675         else if (strncmp (devname, "vcc/", 4) == 0)
1676         {
1677                 sprintf (buffer, "vcs%s", devname + 4);
1678                 if (buffer[3] == '0')
1679                         buffer[3] = '\0';
1680                 compat_name = buffer;
1681         }
1682         else if (strncmp (devname, "pty/", 4) == 0)
1683         {
1684                 int indexx = atoi (devname + 5);
1685                 const char *pty1 = "pqrstuvwxyzabcde";
1686                 const char *pty2 = "0123456789abcdef";
1687
1688                 sprintf (buffer, "%cty%c%c", (devname[4] == 'm') ? 'p' : 't', pty1[indexx >> 4], pty2[indexx & 0x0f]);
1689                 compat_name = buffer;
1690         }
1691         return (compat_name);
1692 }   /*  End Function get_old_name  */
1693
1694 static char get_old_ide_name (unsigned int major, unsigned int minor)
1695 /*  [SUMMARY] Get the old IDE name for a device.
1696     <major> The major number for the device.
1697     <minor> The minor number for the device.
1698     [RETURNS] The drive letter.
1699 */
1700 {
1701         char letter='y';        /* 121 */
1702         char c='a';             /*  97 */
1703         int i=IDE0_MAJOR;
1704
1705
1706 #ifdef CONFIG_DEVFSD_DEBUG
1707         msg_logger( NO_DIE, LOG_INFO, "get_old_ide_name()\n");
1708 #endif
1709
1710         /* I hope it works like the previous code as it saves a few bytes. Tito ;P */
1711         do {
1712                 if(     i==IDE0_MAJOR || i==IDE1_MAJOR || i==IDE2_MAJOR ||
1713                         i==IDE3_MAJOR || i==IDE4_MAJOR || i==IDE5_MAJOR ||
1714                         i==IDE6_MAJOR || i==IDE7_MAJOR || i==IDE8_MAJOR ||
1715                         i==IDE9_MAJOR )
1716                 {
1717                         if(i==major)
1718                         {
1719                                 letter=c;
1720                                 break;
1721                         }
1722                         c+=2;
1723                 }
1724                 i++;
1725         } while(i<=IDE9_MAJOR);
1726
1727         if (minor > 63)
1728                 ++letter;
1729         return (letter);
1730 }   /*  End Function get_old_ide_name  */
1731
1732 static char *write_old_sd_name (char *buffer,
1733                                 unsigned int major, unsigned int minor,
1734                                 char *part)
1735 /*  [SUMMARY] Write the old SCSI disc name to a buffer.
1736     <buffer> The buffer to write to.
1737     <major> The major number for the device.
1738     <minor> The minor number for the device.
1739     <part> The partition string. Must be "" for a whole-disc entry.
1740     [RETURNS] A pointer to the buffer on success, else NULL.
1741 */
1742 {
1743         unsigned int disc_index;
1744
1745 #ifdef CONFIG_DEVFSD_DEBUG
1746         msg_logger( NO_DIE, LOG_INFO, "write_old_sd_name()\n");
1747 #endif
1748
1749         if (major == 8)
1750         {
1751                 sprintf (buffer, "sd%c%s", 'a' + (minor >> 4), part);
1752                 return (buffer);
1753         }
1754         if ( (major > 64) && (major < 72) )
1755         {
1756                 disc_index = ( (major - 64) << 4 ) + (minor >> 4);
1757                 if (disc_index < 26)
1758                         sprintf (buffer, "sd%c%s", 'a' + disc_index, part);
1759                 else
1760                         sprintf (buffer, "sd%c%c%s", 'a' + (disc_index / 26) - 1, 'a' + disc_index % 26,part);
1761                 return (buffer);
1762         }
1763         return (NULL);
1764 }   /*  End Function write_old_sd_name  */
1765
1766
1767 /*  expression.c */
1768
1769 /*EXPERIMENTAL_FUNCTION*/
1770
1771 int st_expr_expand (char *output, unsigned int length, const char *input,
1772                      const char *(*get_variable_func) (const char *variable,
1773                                                   void *info),
1774                      void *info)
1775 /*  [SUMMARY] Expand an expression using Borne Shell-like unquoted rules.
1776     <output> The output expanded expression is written here.
1777     <length> The size of the output buffer.
1778     <input> The input expression. This may equal <<output>>.
1779     <get_variable> A function which will be used to get variable values. If
1780     this returns NULL, the environment is searched instead. If this is NULL,
1781     only the environment is searched.
1782     <info> An arbitrary pointer passed to <<get_variable>>.
1783     [RETURNS] TRUE on success, else FALSE.
1784 */
1785 {
1786         char ch;
1787         unsigned int len;
1788         unsigned int out_pos = 0;
1789         const char *env;
1790         const char *ptr;
1791         struct passwd *pwent;
1792         char buffer[BUFFER_SIZE], tmp[STRING_LENGTH];
1793
1794 #ifdef CONFIG_DEVFSD_DEBUG
1795         msg_logger( NO_DIE, LOG_INFO, "st_expr_expand()\n");
1796 #endif
1797
1798         if (length > BUFFER_SIZE)
1799                 length = BUFFER_SIZE;
1800         for (; TRUE; ++input)
1801         {
1802                 switch (ch = *input)
1803                 {
1804                         case '$':
1805                                 /*  Variable expansion  */
1806                                 input = expand_variable (buffer, length, &out_pos, ++input, get_variable_func, info);
1807                                 if (input == NULL)
1808                                         return (FALSE);
1809                                 break;
1810                         case '~':
1811                                 /*  Home directory expansion  */
1812                                 ch = input[1];
1813                                 if ( isspace (ch) || (ch == '/') || (ch == '\0') )
1814                                 {
1815                                         /* User's own home directory: leave separator for next time */
1816                                         if ( ( env = getenv ("HOME") ) == NULL )
1817                                         {
1818 #ifdef CONFIG_DEVFSD_VERBOSE
1819                                                 msg_logger( NO_DIE, LOG_INFO, bb_msg_variable_not_found, "HOME");
1820 #endif
1821                                                 return (FALSE);
1822                                         }
1823                                         len = strlen (env);
1824                                         if (len + out_pos >= length)
1825                                                 goto st_expr_expand_out;
1826                                         memcpy (buffer + out_pos, env, len + 1);
1827                                         out_pos += len;
1828                                         continue;
1829                                 }
1830                                 /*  Someone else's home directory  */
1831                                 for (ptr = ++input; !isspace (ch) && (ch != '/') && (ch != '\0'); ch = *++ptr)
1832                                         /* VOID */ ;
1833                                 len = ptr - input;
1834                                 if (len >= sizeof tmp)
1835                                         goto st_expr_expand_out;
1836                                 safe_memcpy (tmp, input, len);
1837                                 input = ptr - 1;
1838                                 if ( ( pwent = getpwnam (tmp) ) == NULL )
1839                                 {
1840 #ifdef CONFIG_DEVFSD_VERBOSE
1841                                         msg_logger( NO_DIE, LOG_INFO, "getpwnam(): %s\n", tmp);
1842 #endif
1843                                         return (FALSE);
1844                                 }
1845                                 len = strlen (pwent->pw_dir);
1846                                 if (len + out_pos >= length)
1847                                         goto st_expr_expand_out;
1848                                 memcpy (buffer + out_pos, pwent->pw_dir, len + 1);
1849                                 out_pos += len;
1850                                 break;
1851                         case '\0':
1852                         /* Falltrough */
1853                         default:
1854                                 if (out_pos >= length)
1855                                         goto st_expr_expand_out;
1856                                 buffer[out_pos++] = ch;
1857                                 if (ch == '\0')
1858                                 {
1859                                         memcpy (output, buffer, out_pos);
1860                                         return (TRUE);
1861                                 }
1862                                 break;
1863                         /* esac */
1864                 }
1865         }
1866         return (FALSE);
1867 st_expr_expand_out:
1868 #ifdef CONFIG_DEVFSD_VERBOSE
1869         msg_logger( NO_DIE, LOG_INFO, bb_msg_small_buffer);
1870 #endif
1871         return (FALSE);
1872 }   /*  End Function st_expr_expand  */
1873
1874
1875 /*  Private functions follow  */
1876
1877 static const char *expand_variable (char *buffer, unsigned int length,
1878                                     unsigned int *out_pos, const char *input,
1879                                     const char *(*func) (const char *variable,
1880                                                          void *info),
1881                                     void *info)
1882 /*  [SUMMARY] Expand a variable.
1883     <buffer> The buffer to write to.
1884     <length> The length of the output buffer.
1885     <out_pos> The current output position. This is updated.
1886     <input> A pointer to the input character pointer.
1887     <func> A function which will be used to get variable values. If this
1888     returns NULL, the environment is searched instead. If this is NULL, only
1889     the environment is searched.
1890     <info> An arbitrary pointer passed to <<func>>.
1891     <errfp> Diagnostic messages are written here.
1892     [RETURNS] A pointer to the end of this subexpression on success, else NULL.
1893 */
1894 {
1895         char ch;
1896         int len;
1897         unsigned int open_braces;
1898         const char *env, *ptr;
1899         char tmp[STRING_LENGTH];
1900
1901 #ifdef CONFIG_DEVFSD_DEBUG
1902         msg_logger( NO_DIE, LOG_INFO, "expand_variable()\n");
1903 #endif
1904
1905         ch = input[0];
1906         if (ch == '$')
1907         {
1908                 /*  Special case for "$$": PID  */
1909                 sprintf ( tmp, "%d", (int) getpid () );
1910                 len = strlen (tmp);
1911                 if (len + *out_pos >= length)
1912                         goto expand_variable_out;
1913
1914                 memcpy (buffer + *out_pos, tmp, len + 1);
1915                 out_pos += len;
1916                 return (input);
1917         }
1918         /*  Ordinary variable expansion, possibly in braces  */
1919         if (ch != '{')
1920         {
1921                 /*  Simple variable expansion  */
1922                 for (ptr = input; isalnum (ch) || (ch == '_') || (ch == ':');ch = *++ptr)
1923                         /* VOID */ ;
1924                 len = ptr - input;
1925                 if (len >= sizeof tmp)
1926                         goto expand_variable_out;
1927
1928                 safe_memcpy (tmp, input, len);
1929                 input = ptr - 1;
1930                 if ( ( env = get_variable_v2 (tmp, func, info) ) == NULL )
1931                 {
1932 #ifdef CONFIG_DEVFSD_VERBOSE
1933                         msg_logger( NO_DIE, LOG_INFO, bb_msg_variable_not_found, tmp);
1934 #endif
1935                         return (NULL);
1936                 }
1937                 len = strlen (env);
1938                 if (len + *out_pos >= length)
1939                         goto expand_variable_out;
1940
1941                 memcpy (buffer + *out_pos, env, len + 1);
1942                 *out_pos += len;
1943                 return (input);
1944         }
1945         /*  Variable in braces: check for ':' tricks  */
1946         ch = *++input;
1947         for (ptr = input; isalnum (ch) || (ch == '_'); ch = *++ptr)
1948                 /* VOID */;
1949         if (ch == '}')
1950         {
1951                 /*  Must be simple variable expansion with "${var}"  */
1952                 len = ptr - input;
1953                 if (len >= sizeof tmp)
1954                         goto expand_variable_out;
1955
1956                 safe_memcpy (tmp, input, len);
1957                 ptr = expand_variable (buffer, length, out_pos, tmp, func, info );
1958                 if (ptr == NULL)
1959                         return (NULL);
1960                 return (input + len);
1961         }
1962         if (ch != ':' || ptr[1] != '-' )
1963         {
1964 #ifdef CONFIG_DEVFSD_VERBOSE
1965                 msg_logger( NO_DIE, LOG_INFO,"illegal char in var name\n");
1966 #endif
1967                 return (NULL);
1968         }
1969         /*  It's that handy "${var:-word}" expression. Check if var is defined  */
1970         len = ptr - input;
1971         if (len >= sizeof tmp)
1972                 goto expand_variable_out;
1973
1974         safe_memcpy (tmp, input, len);
1975         /*  Move input pointer to ':'  */
1976         input = ptr;
1977         /*  First skip to closing brace, taking note of nested expressions  */
1978         ptr += 2;
1979         ch = ptr[0];
1980         for (open_braces = 1; open_braces > 0; ch = *++ptr)
1981         {
1982                 switch (ch)
1983                 {
1984                         case '{':
1985                                 ++open_braces;
1986                                 break;
1987                         case '}':
1988                                 --open_braces;
1989                                 break;
1990                         case '\0':
1991 #ifdef CONFIG_DEVFSD_VERBOSE
1992                                 msg_logger( NO_DIE, LOG_INFO,"\"}\" not found in: %s\n", input);
1993 #endif
1994                                 return (NULL);
1995                         default:
1996                                 break;
1997                 }
1998         }
1999         --ptr;
2000         /*  At this point ptr should point to closing brace of "${var:-word}"  */
2001         if ( ( env = get_variable_v2 (tmp, func, info) ) != NULL )
2002         {
2003                 /*  Found environment variable, so skip the input to the closing brace
2004                         and return the variable  */
2005                 input = ptr;
2006                 len = strlen (env);
2007                 if (len + *out_pos >= length)
2008                         goto expand_variable_out;
2009
2010                 memcpy (buffer + *out_pos, env, len + 1);
2011                 *out_pos += len;
2012                 return (input);
2013         }
2014         /*  Environment variable was not found, so process word. Advance input
2015         pointer to start of word in "${var:-word}"  */
2016         input += 2;
2017         len = ptr - input;
2018         if (len >= sizeof tmp)
2019                 goto expand_variable_out;
2020
2021         safe_memcpy (tmp, input, len);
2022         input = ptr;
2023         if ( !st_expr_expand (tmp, STRING_LENGTH, tmp, func, info ) )
2024                 return (NULL);
2025         len = strlen (tmp);
2026         if (len + *out_pos >= length)
2027                 goto expand_variable_out;
2028
2029         memcpy (buffer + *out_pos, tmp, len + 1);
2030         *out_pos += len;
2031         return (input);
2032 expand_variable_out:
2033 #ifdef CONFIG_DEVFSD_VERBOSE
2034         msg_logger( NO_DIE, LOG_INFO, bb_msg_small_buffer);
2035 #endif
2036         return (NULL);
2037 }   /*  End Function expand_variable  */
2038
2039
2040 static const char *get_variable_v2 (const char *variable,
2041                                   const char *(*func) (const char *variable, void *info),
2042                                  void *info)
2043 /*  [SUMMARY] Get a variable from the environment or .
2044     <variable> The variable name.
2045     <func> A function which will be used to get the variable. If this returns
2046     NULL, the environment is searched instead. If this is NULL, only the
2047     environment is searched.
2048     [RETURNS] The value of the variable on success, else NULL.
2049 */
2050 {
2051         const char *value;
2052
2053 #ifdef CONFIG_DEVFSD_DEBUG
2054                 msg_logger( NO_DIE, LOG_INFO, "get_variable_v2()\n");
2055 #endif
2056
2057         if (func != NULL)
2058         {
2059                 value = (*func) (variable, info);
2060                 if (value != NULL)
2061                         return (value);
2062         }
2063         return getenv (variable);
2064 }   /*  End Function get_variable  */
2065
2066 /* END OF CODE */