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