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