1 /* vi: set sw=4 ts=4: */
3 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
7 devfsd implementation for busybox
9 Copyright (C) 2003 by Tito Ragusa <farmatito@tiscali.it>
11 Busybox version is based on some previous work and ideas
12 Copyright (C) [2003] by [Matteo Croce] <3297627799@wind.it>
16 Main file for devfsd (devfs daemon for Linux).
18 Copyright (C) 1998-2002 Richard Gooch
22 Header file for devfsd (devfs daemon for Linux).
24 Copyright (C) 1998-2000 Richard Gooch
28 Compatibility name file for devfsd (build compatibility names).
30 Copyright (C) 1998-2002 Richard Gooch
34 This code provides Borne Shell-like expression expansion.
36 Copyright (C) 1997-1999 Richard Gooch
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.
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.
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.
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.
61 #include <sys/sysmacros.h>
63 /* Various defines taken from linux/major.h */
76 /* Various defines taken from linux/devfs_fs.h */
77 #define DEVFSD_PROTOCOL_REVISION_KERNEL 5
78 #define DEVFSD_IOCTL_BASE 'd'
79 /* These are the various ioctls */
80 #define DEVFSDIOC_GET_PROTO_REV _IOR(DEVFSD_IOCTL_BASE, 0, int)
81 #define DEVFSDIOC_SET_EVENT_MASK _IOW(DEVFSD_IOCTL_BASE, 2, int)
82 #define DEVFSDIOC_RELEASE_EVENT_QUEUE _IOW(DEVFSD_IOCTL_BASE, 3, int)
83 #define DEVFSDIOC_SET_CONFIG_DEBUG_MASK _IOW(DEVFSD_IOCTL_BASE, 4, int)
84 #define DEVFSD_NOTIFY_REGISTERED 0
85 #define DEVFSD_NOTIFY_UNREGISTERED 1
86 #define DEVFSD_NOTIFY_ASYNC_OPEN 2
87 #define DEVFSD_NOTIFY_CLOSE 3
88 #define DEVFSD_NOTIFY_LOOKUP 4
89 #define DEVFSD_NOTIFY_CHANGE 5
90 #define DEVFSD_NOTIFY_CREATE 6
91 #define DEVFSD_NOTIFY_DELETE 7
92 #define DEVFS_PATHLEN 1024
93 /* Never change this otherwise the binary interface will change */
95 struct devfsd_notify_struct {
96 /* Use native C types to ensure same types in kernel and user space */
97 unsigned int type; /* DEVFSD_NOTIFY_* value */
98 unsigned int mode; /* Mode of the inode or device entry */
99 unsigned int major; /* Major number of device entry */
100 unsigned int minor; /* Minor number of device entry */
101 unsigned int uid; /* Uid of process, inode or device entry */
102 unsigned int gid; /* Gid of process, inode or device entry */
103 unsigned int overrun_count; /* Number of lost events */
104 unsigned int namelen; /* Number of characters not including '\0' */
105 /* The device name MUST come last */
106 char devname[DEVFS_PATHLEN]; /* This will be '\0' terminated */
109 #define BUFFER_SIZE 16384
110 #define DEVFSD_VERSION "1.3.25"
111 #define CONFIG_FILE "/etc/devfsd.conf"
112 #define MODPROBE "/sbin/modprobe"
113 #define MODPROBE_SWITCH_1 "-k"
114 #define MODPROBE_SWITCH_2 "-C"
115 #define CONFIG_MODULES_DEVFS "/etc/modules.devfs"
116 #define MAX_ARGS (6 + 1)
117 #define MAX_SUBEXPR 10
118 #define STRING_LENGTH 255
120 /* for get_uid_gid() */
124 /* fork_and_execute() */
128 /* for dir_operation() */
131 #define READ_CONFIG 2
133 /* Update only after changing code to reflect new protocol */
134 #define DEVFSD_PROTOCOL_REVISION_DAEMON 5
136 /* Compile-time check */
137 #if DEVFSD_PROTOCOL_REVISION_KERNEL != DEVFSD_PROTOCOL_REVISION_DAEMON
138 #error protocol version mismatch. Update your kernel headers
141 #define AC_PERMISSIONS 0
144 #define AC_MFUNCTION 3 /* not supported by busybox */
145 #define AC_CFUNCTION 4 /* not supported by busybox */
148 #define AC_MKOLDCOMPAT 7
149 #define AC_MKNEWCOMPAT 8
150 #define AC_RMOLDCOMPAT 9
151 #define AC_RMNEWCOMPAT 10
152 #define AC_RESTORE 11
154 struct permissions_type {
160 struct execute_type {
161 char *argv[MAX_ARGS + 1]; /* argv[0] must always be the programme */
166 const char *destination;
174 struct config_entry_struct {
175 struct action_type action;
179 struct permissions_type permissions;
180 struct execute_type execute;
181 struct copy_type copy;
184 struct config_entry_struct *next;
187 struct get_variable_info {
188 const struct devfsd_notify_struct *info;
190 char devpath[STRING_LENGTH];
193 static void dir_operation(int , const char * , int, unsigned long*);
194 static void service(struct stat statbuf, char *path);
195 static int st_expr_expand(char *, unsigned, const char *, const char *(*)(const char *, void *), void *);
196 static const char *get_old_name(const char *, unsigned, char *, unsigned, unsigned);
197 static int mksymlink(const char *oldpath, const char *newpath);
198 static void read_config_file(char *path, int optional, unsigned long *event_mask);
199 static void process_config_line(const char *, unsigned long *);
200 static int do_servicing(int, unsigned long);
201 static void service_name(const struct devfsd_notify_struct *);
202 static void action_permissions(const struct devfsd_notify_struct *, const struct config_entry_struct *);
203 static void action_execute(const struct devfsd_notify_struct *, const struct config_entry_struct *,
204 const regmatch_t *, unsigned);
205 static void action_modload(const struct devfsd_notify_struct *info, const struct config_entry_struct *entry);
206 static void action_copy(const struct devfsd_notify_struct *, const struct config_entry_struct *,
207 const regmatch_t *, unsigned);
208 static void action_compat(const struct devfsd_notify_struct *, unsigned);
209 static void free_config(void);
210 static void restore(char *spath, struct stat source_stat, int rootlen);
211 static int copy_inode(const char *, const struct stat *, mode_t, const char *, const struct stat *);
212 static mode_t get_mode(const char *);
213 static void signal_handler(int);
214 static const char *get_variable(const char *, void *);
215 static int make_dir_tree(const char *);
216 static int expand_expression(char *, unsigned, const char *, const char *(*)(const char *, void *), void *,
217 const char *, const regmatch_t *, unsigned);
218 static void expand_regexp(char *, size_t, const char *, const char *, const regmatch_t *, unsigned);
219 static const char *expand_variable( char *, unsigned, unsigned *, const char *,
220 const char *(*)(const char *, void *), void *);
221 static const char *get_variable_v2(const char *, const char *(*)(const char *, void *), void *);
222 static char get_old_ide_name(unsigned , unsigned);
223 static char *write_old_sd_name(char *, unsigned, unsigned, const char *);
225 /* busybox functions */
226 static int get_uid_gid(int flag, const char *string);
227 static void safe_memcpy(char * dest, const char * src, int len);
228 static unsigned int scan_dev_name_common(const char *d, unsigned int n, int addendum, const char *ptr);
229 static unsigned int scan_dev_name(const char *d, unsigned int n, const char *ptr);
231 /* Structs and vars */
232 static struct config_entry_struct *first_config = NULL;
233 static struct config_entry_struct *last_config = NULL;
234 static char *mount_point = NULL;
235 static volatile int caught_signal = FALSE;
236 static volatile int caught_sighup = FALSE;
237 static struct initial_symlink_struct {
240 } initial_symlinks[] = {
241 {"/proc/self/fd", "fd"},
248 static struct event_type {
249 unsigned int type; /* The DEVFSD_NOTIFY_* value */
250 const char *config_name; /* The name used in the config file */
252 {DEVFSD_NOTIFY_REGISTERED, "REGISTER"},
253 {DEVFSD_NOTIFY_UNREGISTERED, "UNREGISTER"},
254 {DEVFSD_NOTIFY_ASYNC_OPEN, "ASYNC_OPEN"},
255 {DEVFSD_NOTIFY_CLOSE, "CLOSE"},
256 {DEVFSD_NOTIFY_LOOKUP, "LOOKUP"},
257 {DEVFSD_NOTIFY_CHANGE, "CHANGE"},
258 {DEVFSD_NOTIFY_CREATE, "CREATE"},
259 {DEVFSD_NOTIFY_DELETE, "DELETE"},
263 /* Busybox messages */
265 static const char bb_msg_proto_rev[] ALIGN1 = "protocol revision";
266 static const char bb_msg_bad_config[] ALIGN1 = "bad %s config file: %s";
267 static const char bb_msg_small_buffer[] ALIGN1 = "buffer too small";
268 static const char bb_msg_variable_not_found[] ALIGN1 = "variable: %s not found";
271 #if ENABLE_DEVFSD_VERBOSE || ENABLE_DEBUG
272 #define info_logger(p, fmt, args...) bb_info_msg(fmt, ## args)
273 #define msg_logger(p, fmt, args...) bb_error_msg(fmt, ## args)
274 #define msg_logger_and_die(p, fmt, args...) bb_error_msg_and_die(fmt, ## args)
275 #define error_logger(p, fmt, args...) bb_perror_msg(fmt, ## args)
276 #define error_logger_and_die(p, fmt, args...) bb_perror_msg_and_die(fmt, ## args)
278 #define info_logger(p, fmt, args...)
279 #define msg_logger(p, fmt, args...)
280 #define msg_logger_and_die(p, fmt, args...) exit(EXIT_FAILURE)
281 #define error_logger(p, fmt, args...)
282 #define error_logger_and_die(p, fmt, args...) exit(EXIT_FAILURE)
285 static void safe_memcpy(char *dest, const char *src, int len)
287 memcpy(dest , src, len);
291 static unsigned int scan_dev_name_common(const char *d, unsigned int n, int addendum, const char *ptr)
293 if (d[n - 4] == 'd' && d[n - 3] == 'i' && d[n - 2] == 's' && d[n - 1] == 'c')
295 if (d[n - 2] == 'c' && d[n - 1] == 'd')
297 if (ptr[0] == 'p' && ptr[1] == 'a' && ptr[2] == 'r' && ptr[3] == 't')
299 if (ptr[n - 2] == 'm' && ptr[n - 1] == 't')
304 static unsigned int scan_dev_name(const char *d, unsigned int n, const char *ptr)
306 if (d[0] == 's' && d[1] == 'c' && d[2] == 's' && d[3] == 'i' && d[4] == '/') {
307 if (d[n - 7] == 'g' && d[n - 6] == 'e' && d[n - 5] == 'n'
308 && d[n - 4] == 'e' && d[n - 3] == 'r' && d[n - 2] == 'i' && d[n - 1] == 'c'
311 return scan_dev_name_common(d, n, 0, ptr);
313 if (d[0] == 'i' && d[1] == 'd' && d[2] == 'e' && d[3] == '/'
314 && d[4] == 'h' && d[5] == 'o' && d[6] == 's' && d[7] == 't'
316 return scan_dev_name_common(d, n, 4, ptr);
317 if (d[0] == 's' && d[1] == 'b' && d[2] == 'p' && d[3] == '/')
319 if (d[0] == 'v' && d[1] == 'c' && d[2] == 'c' && d[3] == '/')
321 if (d[0] == 'p' && d[1] == 't' && d[2] == 'y' && d[3] == '/')
326 /* Public functions follow */
328 int devfsd_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
329 int devfsd_main(int argc, char **argv)
331 int print_version = FALSE;
332 int do_daemon = TRUE;
333 int no_polling = FALSE;
335 int fd, proto_rev, count;
336 unsigned long event_mask = 0;
337 struct sigaction new_action;
338 struct initial_symlink_struct *curr;
343 for (count = 2; count < argc; ++count) {
344 if (argv[count][0] == '-') {
345 if (argv[count][1] == 'v' && !argv[count][2]) /* -v */
346 print_version = TRUE;
347 else if (ENABLE_DEVFSD_FG_NP && argv[count][1] == 'f'
348 && argv[count][2] == 'g' && !argv[count][3]) /* -fg */
350 else if (ENABLE_DEVFSD_FG_NP && argv[count][1] == 'n'
351 && argv[count][2] == 'p' && !argv[count][3]) /* -np */
358 mount_point = bb_simplify_path(argv[1]);
362 fd = xopen(".devfsd", O_RDONLY);
363 close_on_exec_on(fd);
364 xioctl(fd, DEVFSDIOC_GET_PROTO_REV, &proto_rev);
366 /*setup initial entries */
367 for (curr = initial_symlinks; curr->dest != NULL; ++curr)
368 symlink(curr->dest, curr->name);
370 /* NB: The check for CONFIG_FILE is done in read_config_file() */
372 if (print_version || (DEVFSD_PROTOCOL_REVISION_DAEMON != proto_rev)) {
373 printf("%s v%s\nDaemon %s:\t%d\nKernel-side %s:\t%d\n",
374 applet_name, DEVFSD_VERSION, bb_msg_proto_rev,
375 DEVFSD_PROTOCOL_REVISION_DAEMON, bb_msg_proto_rev, proto_rev);
376 if (DEVFSD_PROTOCOL_REVISION_DAEMON != proto_rev)
377 bb_error_msg_and_die("%s mismatch!", bb_msg_proto_rev);
378 exit(EXIT_SUCCESS); /* -v */
380 /* Tell kernel we are special(i.e. we get to see hidden entries) */
381 xioctl(fd, DEVFSDIOC_SET_EVENT_MASK, 0);
383 /* Set up SIGHUP and SIGUSR1 handlers */
384 sigemptyset(&new_action.sa_mask);
385 new_action.sa_flags = 0;
386 new_action.sa_handler = signal_handler;
387 sigaction_set(SIGHUP, &new_action);
388 sigaction_set(SIGUSR1, &new_action);
390 printf("%s v%s started for %s\n", applet_name, DEVFSD_VERSION, mount_point);
392 /* Set umask so that mknod(2), open(2) and mkdir(2) have complete control over permissions */
394 read_config_file((char*)CONFIG_FILE, FALSE, &event_mask);
395 /* Do the scan before forking, so that boot scripts see the finished product */
396 dir_operation(SERVICE, mount_point, 0, NULL);
398 if (ENABLE_DEVFSD_FG_NP && no_polling)
401 if (ENABLE_DEVFSD_VERBOSE || ENABLE_DEBUG)
402 logmode = LOGMODE_BOTH;
403 else if (do_daemon == TRUE)
404 logmode = LOGMODE_SYSLOG;
405 /* This is the default */
407 logmode = LOGMODE_STDIO; */
410 /* Release so that the child can grab it */
411 xioctl(fd, DEVFSDIOC_RELEASE_EVENT_QUEUE, 0);
412 bb_daemonize_or_rexec(0, argv);
413 } else if (ENABLE_DEVFSD_FG_NP) {
414 setpgid(0, 0); /* Become process group leader */
418 do_scan = do_servicing(fd, event_mask);
421 read_config_file((char*)CONFIG_FILE, FALSE, &event_mask);
423 dir_operation(SERVICE, mount_point, 0, NULL);
425 if (ENABLE_FEATURE_CLEAN_UP) free(mount_point);
426 } /* End Function main */
429 /* Private functions follow */
431 static void read_config_file(char *path, int optional, unsigned long *event_mask)
432 /* [SUMMARY] Read a configuration database.
433 <path> The path to read the database from. If this is a directory, all
434 entries in that directory will be read(except hidden entries).
435 <optional> If TRUE, the routine will silently ignore a missing config file.
436 <event_mask> The event mask is written here. This is not initialised.
442 char buf[STRING_LENGTH];
446 if (stat(path, &statbuf) == 0) {
447 /* Don't read 0 length files: ignored */
448 /*if (statbuf.st_size == 0)
450 if (S_ISDIR(statbuf.st_mode)) {
451 p = bb_simplify_path(path);
452 dir_operation(READ_CONFIG, p, 0, event_mask);
456 fp = fopen_for_read(path);
458 while (fgets(buf, STRING_LENGTH, fp) != NULL) {
459 /* Skip whitespace */
461 line = skip_whitespace(line);
462 if (line[0] == '\0' || line[0] == '#')
464 process_config_line(line, event_mask);
468 goto read_config_file_err;
471 read_config_file_err:
472 if (optional == 0 && errno == ENOENT)
473 error_logger_and_die(LOG_ERR, "read config file: %s", path);
475 } /* End Function read_config_file */
477 static void process_config_line(const char *line, unsigned long *event_mask)
478 /* [SUMMARY] Process a line from a configuration file.
479 <line> The configuration line.
480 <event_mask> The event mask is written here. This is not initialised.
485 struct config_entry_struct *new;
486 char p[MAX_ARGS][STRING_LENGTH];
487 char when[STRING_LENGTH], what[STRING_LENGTH];
488 char name[STRING_LENGTH];
489 const char *msg = "";
493 /* !!!! Only Uppercase Keywords in devsfd.conf */
494 static const char options[] ALIGN1 =
495 "CLEAR_CONFIG\0""INCLUDE\0""OPTIONAL_INCLUDE\0"
496 "RESTORE\0""PERMISSIONS\0""MODLOAD\0""EXECUTE\0"
497 "COPY\0""IGNORE\0""MKOLDCOMPAT\0""MKNEWCOMPAT\0"
498 "RMOLDCOMPAT\0""RMNEWCOMPAT\0";
500 for (count = 0; count < MAX_ARGS; ++count)
502 num_args = sscanf(line, "%s %s %s %s %s %s %s %s %s %s",
504 p[0], p[1], p[2], p[3], p[4], p[5], p[6]);
506 i = index_in_strings(options, when);
516 goto process_config_line_err;
518 /* "INCLUDE" & "OPTIONAL_INCLUDE" */
519 if (i == 1 || i == 2) {
520 st_expr_expand(name, STRING_LENGTH, name, get_variable, NULL);
521 info_logger(LOG_INFO, "%sinclude: %s", (toupper(when[0]) == 'I') ? "": "optional_", name);
522 read_config_file(name, (toupper(when[0]) == 'I') ? FALSE : TRUE, event_mask);
527 dir_operation(RESTORE, name, strlen(name),NULL);
531 goto process_config_line_err;
533 new = xzalloc(sizeof *new);
535 for (count = 0; event_types[count].config_name != NULL; ++count) {
536 if (strcasecmp(when, event_types[count].config_name) != 0)
538 new->action.when = event_types[count].type;
541 if (event_types[count].config_name == NULL) {
543 goto process_config_line_err;
546 i = index_in_strings(options, what);
549 case 4: /* "PERMISSIONS" */
550 new->action.what = AC_PERMISSIONS;
551 /* Get user and group */
552 ptr = strchr(p[0], '.');
555 goto process_config_line_err; /*"missing '.' in UID.GID"*/
559 new->u.permissions.uid = get_uid_gid(UID, p[0]);
560 new->u.permissions.gid = get_uid_gid(GID, ptr);
562 new->u.permissions.mode = get_mode(p[1]);
564 case 5: /* MODLOAD */
565 /*This action will pass "/dev/$devname"(i.e. "/dev/" prefixed to
566 the device name) to the module loading facility. In addition,
567 the /etc/modules.devfs configuration file is used.*/
568 if (ENABLE_DEVFSD_MODLOAD)
569 new->action.what = AC_MODLOAD;
571 case 6: /* EXECUTE */
572 new->action.what = AC_EXECUTE;
575 for (count = 0; count < num_args; ++count)
576 new->u.execute.argv[count] = xstrdup(p[count]);
578 new->u.execute.argv[num_args] = NULL;
581 new->action.what = AC_COPY;
584 goto process_config_line_err; /* missing path and function in line */
586 new->u.copy.source = xstrdup(p[0]);
587 new->u.copy.destination = xstrdup(p[1]);
591 case 9: /* MKOLDCOMPAT */
593 case 10: /* MKNEWCOMPAT */
595 case 11:/* RMOLDCOMPAT */
597 case 12: /* RMNEWCOMPAT */
603 new->action.what = i - 2;
607 goto process_config_line_err;
611 xregcomp(&new->preg, name, REG_EXTENDED);
613 *event_mask |= 1 << new->action.when;
615 if (first_config == NULL)
618 last_config->next = new;
622 process_config_line_err:
623 msg_logger_and_die(LOG_ERR, bb_msg_bad_config, msg , line);
624 } /* End Function process_config_line */
626 static int do_servicing(int fd, unsigned long event_mask)
627 /* [SUMMARY] Service devfs changes until a signal is received.
628 <fd> The open control file.
629 <event_mask> The event mask.
630 [RETURNS] TRUE if SIGHUP was caught, else FALSE.
634 struct devfsd_notify_struct info;
636 /* (void*) cast is only in order to match prototype */
637 xioctl(fd, DEVFSDIOC_SET_EVENT_MASK, (void*)event_mask);
638 while (!caught_signal) {
640 bytes = read(fd, (char *) &info, sizeof info);
642 break; /* Must test for this first */
644 continue; /* Yes, the order is important */
650 int c_sighup = caught_sighup;
652 caught_signal = FALSE;
653 caught_sighup = FALSE;
656 msg_logger_and_die(LOG_ERR, "read error on control file");
657 } /* End Function do_servicing */
659 static void service_name(const struct devfsd_notify_struct *info)
660 /* [SUMMARY] Service a single devfs change.
661 <info> The devfs change.
666 regmatch_t mbuf[MAX_SUBEXPR];
667 struct config_entry_struct *entry;
669 if (ENABLE_DEBUG && info->overrun_count > 0)
670 msg_logger(LOG_ERR, "lost %u events", info->overrun_count);
672 /* Discard lookups on "/dev/log" and "/dev/initctl" */
673 if (info->type == DEVFSD_NOTIFY_LOOKUP
674 && ((info->devname[0] == 'l' && info->devname[1] == 'o'
675 && info->devname[2] == 'g' && !info->devname[3])
676 || (info->devname[0] == 'i' && info->devname[1] == 'n'
677 && info->devname[2] == 'i' && info->devname[3] == 't'
678 && info->devname[4] == 'c' && info->devname[5] == 't'
679 && info->devname[6] == 'l' && !info->devname[7]))
683 for (entry = first_config; entry != NULL; entry = entry->next) {
684 /* First check if action matches the type, then check if name matches */
685 if (info->type != entry->action.when
686 || regexec(&entry->preg, info->devname, MAX_SUBEXPR, mbuf, 0) != 0)
688 for (n = 0;(n < MAX_SUBEXPR) && (mbuf[n].rm_so != -1); ++n)
691 switch (entry->action.what) {
693 action_permissions(info, entry);
696 if (ENABLE_DEVFSD_MODLOAD)
697 action_modload(info, entry);
700 action_execute(info, entry, mbuf, n);
703 action_copy(info, entry, mbuf, n);
712 action_compat(info, entry->action.what);
715 msg_logger_and_die(LOG_ERR, "Unknown action");
718 } /* End Function service_name */
720 static void action_permissions(const struct devfsd_notify_struct *info,
721 const struct config_entry_struct *entry)
722 /* [SUMMARY] Update permissions for a device entry.
723 <info> The devfs change.
724 <entry> The config file entry.
730 if (stat(info->devname, &statbuf) != 0
731 || chmod(info->devname, (statbuf.st_mode & S_IFMT) | (entry->u.permissions.mode & ~S_IFMT)) != 0
732 || chown(info->devname, entry->u.permissions.uid, entry->u.permissions.gid) != 0
734 error_logger(LOG_ERR, "Can't chmod or chown: %s", info->devname);
735 } /* End Function action_permissions */
737 static void action_modload(const struct devfsd_notify_struct *info,
738 const struct config_entry_struct *entry UNUSED_PARAM)
739 /* [SUMMARY] Load a module.
740 <info> The devfs change.
741 <entry> The config file entry.
747 argv[0] = (char*)MODPROBE;
748 argv[1] = (char*)MODPROBE_SWITCH_1; /* "-k" */
749 argv[2] = (char*)MODPROBE_SWITCH_2; /* "-C" */
750 argv[3] = (char*)CONFIG_MODULES_DEVFS;
751 argv[4] = concat_path_file("/dev", info->devname); /* device */
754 spawn_and_wait(argv);
756 } /* End Function action_modload */
758 static void action_execute(const struct devfsd_notify_struct *info,
759 const struct config_entry_struct *entry,
760 const regmatch_t *regexpr, unsigned int numexpr)
761 /* [SUMMARY] Execute a programme.
762 <info> The devfs change.
763 <entry> The config file entry.
764 <regexpr> The number of subexpression(start, end) offsets within the
766 <numexpr> The number of elements within <<regexpr>>.
771 struct get_variable_info gv_info;
772 char *argv[MAX_ARGS + 1];
773 char largv[MAX_ARGS + 1][STRING_LENGTH];
776 gv_info.devname = info->devname;
777 snprintf(gv_info.devpath, sizeof(gv_info.devpath), "%s/%s", mount_point, info->devname);
778 for (count = 0; entry->u.execute.argv[count] != NULL; ++count) {
779 expand_expression(largv[count], STRING_LENGTH,
780 entry->u.execute.argv[count],
781 get_variable, &gv_info,
782 gv_info.devname, regexpr, numexpr);
783 argv[count] = largv[count];
786 spawn_and_wait(argv);
787 } /* End Function action_execute */
790 static void action_copy(const struct devfsd_notify_struct *info,
791 const struct config_entry_struct *entry,
792 const regmatch_t *regexpr, unsigned int numexpr)
793 /* [SUMMARY] Copy permissions.
794 <info> The devfs change.
795 <entry> The config file entry.
796 <regexpr> This list of subexpression(start, end) offsets within the
798 <numexpr> The number of elements in <<regexpr>>.
803 struct get_variable_info gv_info;
804 struct stat source_stat, dest_stat;
805 char source[STRING_LENGTH], destination[STRING_LENGTH];
808 dest_stat.st_mode = 0;
810 if ((info->type == DEVFSD_NOTIFY_CHANGE) && S_ISLNK(info->mode))
813 gv_info.devname = info->devname;
815 snprintf(gv_info.devpath, sizeof(gv_info.devpath), "%s/%s", mount_point, info->devname);
816 expand_expression(source, STRING_LENGTH, entry->u.copy.source,
817 get_variable, &gv_info, gv_info.devname,
820 expand_expression(destination, STRING_LENGTH, entry->u.copy.destination,
821 get_variable, &gv_info, gv_info.devname,
824 if (!make_dir_tree(destination) || lstat(source, &source_stat) != 0)
826 lstat(destination, &dest_stat);
827 new_mode = source_stat.st_mode & ~S_ISVTX;
828 if (info->type == DEVFSD_NOTIFY_CREATE)
830 else if ((info->type == DEVFSD_NOTIFY_CHANGE) &&(dest_stat.st_mode & S_ISVTX))
832 ret = copy_inode(destination, &dest_stat, new_mode, source, &source_stat);
833 if (ENABLE_DEBUG && ret && (errno != EEXIST))
834 error_logger(LOG_ERR, "copy_inode: %s to %s", source, destination);
835 } /* End Function action_copy */
837 static void action_compat(const struct devfsd_notify_struct *info, unsigned int action)
838 /* [SUMMARY] Process a compatibility request.
839 <info> The devfs change.
840 <action> The action to take.
845 const char *compat_name = NULL;
846 const char *dest_name = info->devname;
848 char compat_buf[STRING_LENGTH], dest_buf[STRING_LENGTH];
849 int mode, host, bus, target, lun;
852 /* 1 to 5 "scsi/" , 6 to 9 "ide/host" */
853 static const char *const fmt[] = {
855 "sg/c%db%dt%du%d", /* scsi/generic */
856 "sd/c%db%dt%du%d", /* scsi/disc */
857 "sr/c%db%dt%du%d", /* scsi/cd */
858 "sd/c%db%dt%du%dp%d", /* scsi/part */
859 "st/c%db%dt%du%dm%d%c", /* scsi/mt */
860 "ide/hd/c%db%dt%du%d", /* ide/host/disc */
861 "ide/cd/c%db%dt%du%d", /* ide/host/cd */
862 "ide/hd/c%db%dt%du%dp%d", /* ide/host/part */
863 "ide/mt/c%db%dt%du%d%s", /* ide/host/mt */
867 /* First construct compatibility name */
871 compat_name = get_old_name(info->devname, info->namelen, compat_buf, info->major, info->minor);
875 ptr = bb_basename(info->devname);
876 i = scan_dev_name(info->devname, info->namelen, ptr);
882 sscanf(info->devname + ((i < 6) ? 5 : 4), "host%d/bus%d/target%d/lun%d/", &host, &bus, &target, &lun);
883 snprintf(dest_buf, sizeof(dest_buf), "../%s", info->devname + (( i > 5) ? 4 : 0));
884 dest_name = dest_buf;
885 compat_name = compat_buf;
888 /* 1 == scsi/generic 2 == scsi/disc 3 == scsi/cd 6 == ide/host/disc 7 == ide/host/cd */
889 if (i == 1 || i == 2 || i == 3 || i == 6 || i ==7)
890 sprintf(compat_buf, fmt[i], host, bus, target, lun);
892 /* 4 == scsi/part 8 == ide/host/part */
893 if (i == 4 || i == 8)
894 sprintf(compat_buf, fmt[i], host, bus, target, lun, atoi(ptr + 4));
898 rewind_ = info->devname[info->namelen - 1];
902 if (ptr[2] == 'l' /*108*/ || ptr[2] == 'm'/*109*/)
903 mode = ptr[2] - 107; /* 1 or 2 */
906 sprintf(compat_buf, fmt[i], host, bus, target, lun, mode, rewind_);
909 /* 9 == ide/host/mt */
911 snprintf(compat_buf, sizeof(compat_buf), fmt[i], host, bus, target, lun, ptr + 2);
913 } /* switch (action) */
915 if (compat_name == NULL)
918 /* Now decide what to do with it */
922 mksymlink(dest_name, compat_name);
926 ret = unlink(compat_name);
927 if (ENABLE_DEBUG && ret)
928 error_logger(LOG_ERR, "unlink: %s", compat_name);
931 } /* switch (action) */
932 } /* End Function action_compat */
934 static void restore(char *spath, struct stat source_stat, int rootlen)
937 struct stat dest_stat;
939 dest_stat.st_mode = 0;
940 dpath = concat_path_file(mount_point, spath + rootlen);
941 lstat(dpath, &dest_stat);
943 if (S_ISLNK(source_stat.st_mode) || (source_stat.st_mode & S_ISVTX))
944 copy_inode(dpath, &dest_stat, (source_stat.st_mode & ~S_ISVTX), spath, &source_stat);
946 if (S_ISDIR(source_stat.st_mode))
947 dir_operation(RESTORE, spath, rootlen, NULL);
951 static int copy_inode(const char *destpath, const struct stat *dest_stat,
953 const char *sourcepath, const struct stat *source_stat)
954 /* [SUMMARY] Copy an inode.
955 <destpath> The destination path. An existing inode may be deleted.
956 <dest_stat> The destination stat(2) information.
957 <new_mode> The desired new mode for the destination.
958 <sourcepath> The source path.
959 <source_stat> The source stat(2) information.
960 [RETURNS] TRUE on success, else FALSE.
963 int source_len, dest_len;
964 char source_link[STRING_LENGTH], dest_link[STRING_LENGTH];
966 struct sockaddr_un un_addr;
967 char symlink_val[STRING_LENGTH];
969 if ((source_stat->st_mode & S_IFMT) ==(dest_stat->st_mode & S_IFMT)) {
971 if (S_ISLNK(source_stat->st_mode)) {
972 source_len = readlink(sourcepath, source_link, STRING_LENGTH - 1);
974 || (dest_len = readlink(destpath, dest_link, STRING_LENGTH - 1)) < 0
977 source_link[source_len] = '\0';
978 dest_link[dest_len] = '\0';
979 if ((source_len != dest_len) || (strcmp(source_link, dest_link) != 0)) {
981 symlink(source_link, destpath);
984 } /* Else not a symlink */
985 chmod(destpath, new_mode & ~S_IFMT);
986 chown(destpath, source_stat->st_uid, source_stat->st_gid);
989 /* Different types: unlink and create */
991 switch (source_stat->st_mode & S_IFMT) {
993 fd = socket(AF_UNIX, SOCK_STREAM, 0);
996 un_addr.sun_family = AF_UNIX;
997 snprintf(un_addr.sun_path, sizeof(un_addr.sun_path), "%s", destpath);
998 val = bind(fd, (struct sockaddr *) &un_addr, (int) sizeof un_addr);
1000 if (val != 0 || chmod(destpath, new_mode & ~S_IFMT) != 0)
1004 val = readlink(sourcepath, symlink_val, STRING_LENGTH - 1);
1007 symlink_val[val] = '\0';
1008 if (symlink(symlink_val, destpath) == 0)
1012 fd = open(destpath, O_RDONLY | O_CREAT, new_mode & ~S_IFMT);
1016 if (chmod(destpath, new_mode & ~S_IFMT) != 0)
1022 if (mknod(destpath, new_mode, source_stat->st_rdev) != 0)
1026 if (mkdir(destpath, new_mode & ~S_IFMT) != 0)
1029 if (chown(destpath, source_stat->st_uid, source_stat->st_gid) == 0)
1034 } /* End Function copy_inode */
1036 static void free_config(void)
1037 /* [SUMMARY] Free the configuration information.
1041 struct config_entry_struct *c_entry;
1044 for (c_entry = first_config; c_entry != NULL; c_entry = next) {
1047 next = c_entry->next;
1048 regfree(&c_entry->preg);
1049 if (c_entry->action.what == AC_EXECUTE) {
1050 for (count = 0; count < MAX_ARGS; ++count) {
1051 if (c_entry->u.execute.argv[count] == NULL)
1053 free(c_entry->u.execute.argv[count]);
1058 first_config = NULL;
1060 } /* End Function free_config */
1062 static int get_uid_gid(int flag, const char *string)
1063 /* [SUMMARY] Convert a string to a UID or GID value.
1064 <flag> "UID" or "GID".
1065 <string> The string.
1066 [RETURNS] The UID or GID value.
1069 struct passwd *pw_ent;
1070 struct group *grp_ent;
1071 static const char *msg;
1073 if (ENABLE_DEVFSD_VERBOSE)
1076 if (isdigit(string[0]) ||((string[0] == '-') && isdigit(string[1])))
1077 return atoi(string);
1079 if (flag == UID && (pw_ent = getpwnam(string)) != NULL)
1080 return pw_ent->pw_uid;
1082 if (flag == GID && (grp_ent = getgrnam(string)) != NULL)
1083 return grp_ent->gr_gid;
1084 else if (ENABLE_DEVFSD_VERBOSE)
1087 if (ENABLE_DEVFSD_VERBOSE)
1088 msg_logger(LOG_ERR, "unknown %s: %s, defaulting to %cid=0", msg, string, msg[0]);
1090 }/* End Function get_uid_gid */
1092 static mode_t get_mode(const char *string)
1093 /* [SUMMARY] Convert a string to a mode value.
1094 <string> The string.
1095 [RETURNS] The mode value.
1101 if (isdigit(string[0]))
1102 return strtoul(string, NULL, 8);
1103 if (strlen(string) != 9)
1104 msg_logger_and_die(LOG_ERR, "bad mode: %s", string);
1109 if (string[0] == 'r' || string[0] == 'w' || string[0] == 'x')
1115 } /* End Function get_mode */
1117 static void signal_handler(int sig)
1119 caught_signal = TRUE;
1121 caught_sighup = TRUE;
1123 info_logger(LOG_INFO, "Caught signal %d", sig);
1124 } /* End Function signal_handler */
1126 static const char *get_variable(const char *variable, void *info)
1128 static char sbuf[sizeof(int)*3 + 2]; /* sign and NUL */
1129 static char *hostname;
1131 struct get_variable_info *gv_info = info;
1132 const char *field_names[] = {
1133 "hostname", "mntpt", "devpath", "devname",
1134 "uid", "gid", "mode", hostname, mount_point,
1135 gv_info->devpath, gv_info->devname, NULL
1140 hostname = safe_gethostname();
1141 /* index_in_str_array returns i>=0 */
1142 i = index_in_str_array(field_names, variable);
1144 if (i > 6 || i < 0 || (i > 1 && gv_info == NULL))
1146 if (i >= 0 && i <= 3)
1147 return field_names[i + 7];
1150 sprintf(sbuf, "%u", gv_info->info->uid);
1152 sprintf(sbuf, "%u", gv_info->info->gid);
1154 sprintf(sbuf, "%o", gv_info->info->mode);
1156 } /* End Function get_variable */
1158 static void service(struct stat statbuf, char *path)
1160 struct devfsd_notify_struct info;
1162 memset(&info, 0, sizeof info);
1163 info.type = DEVFSD_NOTIFY_REGISTERED;
1164 info.mode = statbuf.st_mode;
1165 info.major = major(statbuf.st_rdev);
1166 info.minor = minor(statbuf.st_rdev);
1167 info.uid = statbuf.st_uid;
1168 info.gid = statbuf.st_gid;
1169 snprintf(info.devname, sizeof(info.devname), "%s", path + strlen(mount_point) + 1);
1170 info.namelen = strlen(info.devname);
1171 service_name(&info);
1172 if (S_ISDIR(statbuf.st_mode))
1173 dir_operation(SERVICE, path, 0, NULL);
1176 static void dir_operation(int type, const char * dir_name, int var, unsigned long *event_mask)
1177 /* [SUMMARY] Scan a directory tree and generate register events on leaf nodes.
1178 <flag> To choose which function to perform
1179 <dp> The directory pointer. This is closed upon completion.
1180 <dir_name> The name of the directory.
1181 <rootlen> string length parameter.
1185 struct stat statbuf;
1190 dp = warn_opendir(dir_name);
1194 while ((de = readdir(dp)) != NULL) {
1196 if (de->d_name && DOT_OR_DOTDOT(de->d_name))
1198 path = concat_path_file(dir_name, de->d_name);
1199 if (lstat(path, &statbuf) == 0) {
1202 service(statbuf, path);
1205 restore(path, statbuf, var);
1208 read_config_file(path, var, event_mask);
1215 } /* End Function do_scan_and_service */
1217 static int mksymlink(const char *oldpath, const char *newpath)
1218 /* [SUMMARY] Create a symlink, creating intervening directories as required.
1219 <oldpath> The string contained in the symlink.
1220 <newpath> The name of the new symlink.
1221 [RETURNS] 0 on success, else -1.
1224 if (!make_dir_tree(newpath))
1227 if (symlink(oldpath, newpath) != 0) {
1228 if (errno != EEXIST)
1232 } /* End Function mksymlink */
1235 static int make_dir_tree(const char *path)
1236 /* [SUMMARY] Creating intervening directories for a path as required.
1237 <path> The full pathname(including the leaf node).
1238 [RETURNS] TRUE on success, else FALSE.
1241 if (bb_make_directory(dirname((char *)path), -1, FILEUTILS_RECUR) == -1)
1244 } /* End Function make_dir_tree */
1246 static int expand_expression(char *output, unsigned int outsize,
1248 const char *(*get_variable_func)(const char *variable, void *info),
1250 const char *devname,
1251 const regmatch_t *ex, unsigned int numexp)
1252 /* [SUMMARY] Expand environment variables and regular subexpressions in string.
1253 <output> The output expanded expression is written here.
1254 <length> The size of the output buffer.
1255 <input> The input expression. This may equal <<output>>.
1256 <get_variable> A function which will be used to get variable values. If
1257 this returns NULL, the environment is searched instead. If this is NULL,
1258 only the environment is searched.
1259 <info> An arbitrary pointer passed to <<get_variable>>.
1260 <devname> Device name; specifically, this is the string that contains all
1261 of the regular subexpressions.
1262 <ex> Array of start / end offsets into info->devname for each subexpression
1263 <numexp> Number of regular subexpressions found in <<devname>>.
1264 [RETURNS] TRUE on success, else FALSE.
1267 char temp[STRING_LENGTH];
1269 if (!st_expr_expand(temp, STRING_LENGTH, input, get_variable_func, info))
1271 expand_regexp(output, outsize, temp, devname, ex, numexp);
1273 } /* End Function expand_expression */
1275 static void expand_regexp(char *output, size_t outsize, const char *input,
1276 const char *devname,
1277 const regmatch_t *ex, unsigned int numex)
1278 /* [SUMMARY] Expand all occurrences of the regular subexpressions \0 to \9.
1279 <output> The output expanded expression is written here.
1280 <outsize> The size of the output buffer.
1281 <input> The input expression. This may NOT equal <<output>>, because
1282 supporting that would require yet another string-copy. However, it's not
1283 hard to write a simple wrapper function to add this functionality for those
1284 few cases that need it.
1285 <devname> Device name; specifically, this is the string that contains all
1286 of the regular subexpressions.
1287 <ex> An array of start and end offsets into <<devname>>, one for each
1289 <numex> Number of subexpressions in the offset-array <<ex>>.
1293 const char last_exp = '0' - 1 + numex;
1296 /* Guarantee NULL termination by writing an explicit '\0' character into
1297 the very last byte */
1299 output[--outsize] = '\0';
1300 /* Copy the input string into the output buffer, replacing '\\' with '\'
1301 and '\0' .. '\9' with subexpressions 0 .. 9, if they exist. Other \x
1302 codes are deleted */
1303 while ((c != '\0') && (outsize != 0)) {
1310 if ((c >= '0') && (c <= last_exp)) {
1311 const regmatch_t *subexp = ex + (c - '0');
1312 unsigned int sublen = subexp->rm_eo - subexp->rm_so;
1314 /* Range checking */
1315 if (sublen > outsize)
1317 strncpy(output, devname + subexp->rm_so, sublen);
1328 } /* End Function expand_regexp */
1331 /* from compat_name.c */
1333 struct translate_struct {
1334 const char *match; /* The string to match to(up to length) */
1335 const char *format; /* Format of output, "%s" takes data past match string,
1336 NULL is effectively "%s"(just more efficient) */
1339 static struct translate_struct translate_table[] =
1342 {"printers/", "lp%s"},
1344 {"parports/", "parport%s"},
1347 {"loop/", "loop%s"},
1348 {"floppy/", "fd%s"},
1350 {"md/", "md%s"}, /* Meta-devices */
1354 {"pg/", "pg%s"}, /* Parallel port generic ATAPI interface*/
1356 {"staliomem/", "staliomem%s"}, /* Stallion serial driver control */
1357 {"tts/E", "ttyE%s"}, /* Stallion serial driver */
1358 {"cua/E", "cue%s"}, /* Stallion serial driver callout */
1359 {"tts/R", "ttyR%s"}, /* Rocketport serial driver */
1360 {"cua/R", "cur%s"}, /* Rocketport serial driver callout */
1361 {"ip2/", "ip2%s"}, /* Computone serial driver control */
1362 {"tts/F", "ttyF%s"}, /* Computone serial driver */
1363 {"cua/F", "cuf%s"}, /* Computone serial driver callout */
1364 {"tts/C", "ttyC%s"}, /* Cyclades serial driver */
1365 {"cua/C", "cub%s"}, /* Cyclades serial driver callout */
1366 {"tts/", "ttyS%s"}, /* Generic serial: must be after others */
1367 {"cua/", "cua%s"}, /* Generic serial: must be after others */
1368 {"input/js", "js%s"}, /* Joystick driver */
1372 const char *get_old_name(const char *devname, unsigned int namelen,
1373 char *buffer, unsigned int major, unsigned int minor)
1374 /* [SUMMARY] Translate a kernel-supplied name into an old name.
1375 <devname> The device name provided by the kernel.
1376 <namelen> The length of the name.
1377 <buffer> A buffer that may be used. This should be at least 128 bytes long.
1378 <major> The major number for the device.
1379 <minor> The minor number for the device.
1380 [RETURNS] A pointer to the old name if known, else NULL.
1383 const char *compat_name = NULL;
1385 struct translate_struct *trans;
1392 /* 1 to 5 "scsi/" , 6 to 9 "ide/host", 10 sbp/, 11 vcc/, 12 pty/ */
1393 static const char *const fmt[] = {
1395 "sg%u", /* scsi/generic */
1396 NULL, /* scsi/disc */
1397 "sr%u", /* scsi/cd */
1398 NULL, /* scsi/part */
1399 "nst%u%c", /* scsi/mt */
1400 "hd%c" , /* ide/host/disc */
1401 "hd%c" , /* ide/host/cd */
1402 "hd%c%s", /* ide/host/part */
1403 "%sht%d", /* ide/host/mt */
1404 "sbpcd%u", /* sbp/ */
1406 "%cty%c%c", /* pty/ */
1410 for (trans = translate_table; trans->match != NULL; ++trans) {
1411 len = strlen(trans->match);
1413 if (strncmp(devname, trans->match, len) == 0) {
1414 if (trans->format == NULL)
1415 return devname + len;
1416 sprintf(buffer, trans->format, devname + len);
1421 ptr = bb_basename(devname);
1422 i = scan_dev_name(devname, namelen, ptr);
1424 if (i > 0 && i < 13)
1425 compat_name = buffer;
1429 /* 1 == scsi/generic, 3 == scsi/cd, 10 == sbp/ */
1430 if (i == 1 || i == 3 || i == 10)
1431 sprintf(buffer, fmt[i], minor);
1433 /* 2 ==scsi/disc, 4 == scsi/part */
1434 if (i == 2 || i == 4)
1435 compat_name = write_old_sd_name(buffer, major, minor, ((i == 2) ? "" : (ptr + 4)));
1442 sprintf(buffer, fmt[i], minor & 0x1f, mode);
1443 if (devname[namelen - 1] != 'n')
1446 /* 6 == ide/host/disc, 7 == ide/host/cd, 8 == ide/host/part */
1447 if (i == 6 || i == 7 || i == 8)
1448 /* last arg should be ignored for i == 6 or i== 7 */
1449 sprintf(buffer, fmt[i] , get_old_ide_name(major, minor), ptr + 4);
1451 /* 9 == ide/host/mt */
1453 sprintf(buffer, fmt[i], ptr + 2, minor & 0x7f);
1457 sprintf(buffer, fmt[i], devname + 4);
1458 if (buffer[3] == '0')
1463 pty1 = "pqrstuvwxyzabcde";
1464 pty2 = "0123456789abcdef";
1465 indexx = atoi(devname + 5);
1466 sprintf(buffer, fmt[i], (devname[4] == 'm') ? 'p' : 't', pty1[indexx >> 4], pty2[indexx & 0x0f]);
1469 } /* End Function get_old_name */
1471 static char get_old_ide_name(unsigned int major, unsigned int minor)
1472 /* [SUMMARY] Get the old IDE name for a device.
1473 <major> The major number for the device.
1474 <minor> The minor number for the device.
1475 [RETURNS] The drive letter.
1478 char letter = 'y'; /* 121 */
1479 char c = 'a'; /* 97 */
1482 /* I hope it works like the previous code as it saves a few bytes. Tito ;P */
1484 if (i == IDE0_MAJOR || i == IDE1_MAJOR || i == IDE2_MAJOR
1485 || i == IDE3_MAJOR || i == IDE4_MAJOR || i == IDE5_MAJOR
1486 || i == IDE6_MAJOR || i == IDE7_MAJOR || i == IDE8_MAJOR
1489 if ((unsigned int)i == major) {
1496 } while (i <= IDE9_MAJOR);
1501 } /* End Function get_old_ide_name */
1503 static char *write_old_sd_name(char *buffer,
1504 unsigned int major, unsigned int minor,
1506 /* [SUMMARY] Write the old SCSI disc name to a buffer.
1507 <buffer> The buffer to write to.
1508 <major> The major number for the device.
1509 <minor> The minor number for the device.
1510 <part> The partition string. Must be "" for a whole-disc entry.
1511 [RETURNS] A pointer to the buffer on success, else NULL.
1514 unsigned int disc_index;
1517 sprintf(buffer, "sd%c%s", 'a' + (minor >> 4), part);
1520 if ((major > 64) && (major < 72)) {
1521 disc_index = ((major - 64) << 4) +(minor >> 4);
1522 if (disc_index < 26)
1523 sprintf(buffer, "sd%c%s", 'a' + disc_index, part);
1525 sprintf(buffer, "sd%c%c%s", 'a' +(disc_index / 26) - 1, 'a' + disc_index % 26, part);
1529 } /* End Function write_old_sd_name */
1534 /*EXPERIMENTAL_FUNCTION*/
1536 int st_expr_expand(char *output, unsigned int length, const char *input,
1537 const char *(*get_variable_func)(const char *variable,
1540 /* [SUMMARY] Expand an expression using Borne Shell-like unquoted rules.
1541 <output> The output expanded expression is written here.
1542 <length> The size of the output buffer.
1543 <input> The input expression. This may equal <<output>>.
1544 <get_variable> A function which will be used to get variable values. If
1545 this returns NULL, the environment is searched instead. If this is NULL,
1546 only the environment is searched.
1547 <info> An arbitrary pointer passed to <<get_variable>>.
1548 [RETURNS] TRUE on success, else FALSE.
1553 unsigned int out_pos = 0;
1556 struct passwd *pwent;
1557 char buffer[BUFFER_SIZE], tmp[STRING_LENGTH];
1559 if (length > BUFFER_SIZE)
1560 length = BUFFER_SIZE;
1561 for (; TRUE; ++input) {
1562 switch (ch = *input) {
1564 /* Variable expansion */
1565 input = expand_variable(buffer, length, &out_pos, ++input, get_variable_func, info);
1570 /* Home directory expansion */
1572 if (isspace(ch) ||(ch == '/') ||(ch == '\0')) {
1573 /* User's own home directory: leave separator for next time */
1574 env = getenv("HOME");
1576 info_logger(LOG_INFO, bb_msg_variable_not_found, "HOME");
1580 if (len + out_pos >= length)
1581 goto st_expr_expand_out;
1582 memcpy(buffer + out_pos, env, len + 1);
1586 /* Someone else's home directory */
1587 for (ptr = ++input; !isspace(ch) && (ch != '/') && (ch != '\0'); ch = *++ptr)
1590 if (len >= sizeof tmp)
1591 goto st_expr_expand_out;
1592 safe_memcpy(tmp, input, len);
1594 pwent = getpwnam(tmp);
1595 if (pwent == NULL) {
1596 info_logger(LOG_INFO, "no pwent for: %s", tmp);
1599 len = strlen(pwent->pw_dir);
1600 if (len + out_pos >= length)
1601 goto st_expr_expand_out;
1602 memcpy(buffer + out_pos, pwent->pw_dir, len + 1);
1608 if (out_pos >= length)
1609 goto st_expr_expand_out;
1610 buffer[out_pos++] = ch;
1612 memcpy(output, buffer, out_pos);
1621 info_logger(LOG_INFO, bb_msg_small_buffer);
1623 } /* End Function st_expr_expand */
1626 /* Private functions follow */
1628 static const char *expand_variable(char *buffer, unsigned int length,
1629 unsigned int *out_pos, const char *input,
1630 const char *(*func)(const char *variable,
1633 /* [SUMMARY] Expand a variable.
1634 <buffer> The buffer to write to.
1635 <length> The length of the output buffer.
1636 <out_pos> The current output position. This is updated.
1637 <input> A pointer to the input character pointer.
1638 <func> A function which will be used to get variable values. If this
1639 returns NULL, the environment is searched instead. If this is NULL, only
1640 the environment is searched.
1641 <info> An arbitrary pointer passed to <<func>>.
1642 <errfp> Diagnostic messages are written here.
1643 [RETURNS] A pointer to the end of this subexpression on success, else NULL.
1648 unsigned int open_braces;
1649 const char *env, *ptr;
1650 char tmp[STRING_LENGTH];
1654 /* Special case for "$$": PID */
1655 sprintf(tmp, "%d", (int) getpid());
1657 if (len + *out_pos >= length)
1658 goto expand_variable_out;
1660 memcpy(buffer + *out_pos, tmp, len + 1);
1664 /* Ordinary variable expansion, possibly in braces */
1666 /* Simple variable expansion */
1667 for (ptr = input; isalnum(ch) || (ch == '_') || (ch == ':'); ch = *++ptr)
1670 if ((size_t)len >= sizeof tmp)
1671 goto expand_variable_out;
1673 safe_memcpy(tmp, input, len);
1675 env = get_variable_v2(tmp, func, info);
1677 info_logger(LOG_INFO, bb_msg_variable_not_found, tmp);
1681 if (len + *out_pos >= length)
1682 goto expand_variable_out;
1684 memcpy(buffer + *out_pos, env, len + 1);
1688 /* Variable in braces: check for ':' tricks */
1690 for (ptr = input; isalnum(ch) || (ch == '_'); ch = *++ptr)
1693 /* Must be simple variable expansion with "${var}" */
1695 if ((size_t)len >= sizeof tmp)
1696 goto expand_variable_out;
1698 safe_memcpy(tmp, input, len);
1699 ptr = expand_variable(buffer, length, out_pos, tmp, func, info);
1704 if (ch != ':' || ptr[1] != '-') {
1705 info_logger(LOG_INFO, "illegal char in var name");
1708 /* It's that handy "${var:-word}" expression. Check if var is defined */
1710 if ((size_t)len >= sizeof tmp)
1711 goto expand_variable_out;
1713 safe_memcpy(tmp, input, len);
1714 /* Move input pointer to ':' */
1716 /* First skip to closing brace, taking note of nested expressions */
1719 for (open_braces = 1; open_braces > 0; ch = *++ptr) {
1728 info_logger(LOG_INFO, "\"}\" not found in: %s", input);
1735 /* At this point ptr should point to closing brace of "${var:-word}" */
1736 env = get_variable_v2(tmp, func, info);
1738 /* Found environment variable, so skip the input to the closing brace
1739 and return the variable */
1742 if (len + *out_pos >= length)
1743 goto expand_variable_out;
1745 memcpy(buffer + *out_pos, env, len + 1);
1749 /* Environment variable was not found, so process word. Advance input
1750 pointer to start of word in "${var:-word}" */
1753 if ((size_t)len >= sizeof tmp)
1754 goto expand_variable_out;
1756 safe_memcpy(tmp, input, len);
1758 if (!st_expr_expand(tmp, STRING_LENGTH, tmp, func, info))
1761 if (len + *out_pos >= length)
1762 goto expand_variable_out;
1764 memcpy(buffer + *out_pos, tmp, len + 1);
1767 expand_variable_out:
1768 info_logger(LOG_INFO, bb_msg_small_buffer);
1770 } /* End Function expand_variable */
1773 static const char *get_variable_v2(const char *variable,
1774 const char *(*func)(const char *variable, void *info),
1776 /* [SUMMARY] Get a variable from the environment or .
1777 <variable> The variable name.
1778 <func> A function which will be used to get the variable. If this returns
1779 NULL, the environment is searched instead. If this is NULL, only the
1780 environment is searched.
1781 [RETURNS] The value of the variable on success, else NULL.
1787 value = (*func)(variable, info);
1791 return getenv(variable);
1792 } /* End Function get_variable */