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