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