1 /* vi: set sw=4 ts=4: */
3 * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
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
163 char *argv[MAX_ARGS + 1]; /* argv[0] must always be the programme */
169 const char *destination;
178 struct config_entry_struct
180 struct action_type action;
184 struct permissions_type permissions;
185 struct execute_type execute;
186 struct copy_type copy;
189 struct config_entry_struct *next;
192 struct get_variable_info
194 const struct devfsd_notify_struct *info;
196 char devpath[STRING_LENGTH];
199 static void dir_operation(int , const char * , int, unsigned long*);
200 static void service(struct stat statbuf, char *path);
201 static int st_expr_expand(char *, unsigned, const char *, const char *(*)(const char *, void *), void *);
202 static const char *get_old_name(const char *, unsigned, char *, unsigned, unsigned);
203 static int mksymlink(const char *oldpath, const char *newpath);
204 static void read_config_file(char *path, int optional, unsigned long *event_mask);
205 static void process_config_line(const char *, unsigned long *);
206 static int do_servicing(int, unsigned long);
207 static void service_name(const struct devfsd_notify_struct *);
208 static void action_permissions(const struct devfsd_notify_struct *, const struct config_entry_struct *);
209 static void action_execute(const struct devfsd_notify_struct *, const struct config_entry_struct *,
210 const regmatch_t *, unsigned);
211 static void action_modload(const struct devfsd_notify_struct *info, const struct config_entry_struct *entry);
212 static void action_copy(const struct devfsd_notify_struct *, const struct config_entry_struct *,
213 const regmatch_t *, unsigned);
214 static void action_compat(const struct devfsd_notify_struct *, unsigned);
215 static void free_config(void);
216 static void restore(char *spath, struct stat source_stat, int rootlen);
217 static int copy_inode(const char *, const struct stat *, mode_t, const char *, const struct stat *);
218 static mode_t get_mode(const char *);
219 static void signal_handler(int);
220 static const char *get_variable(const char *, void *);
221 static int make_dir_tree(const char *);
222 static int expand_expression(char *, unsigned, const char *, const char *(*)(const char *, void *), void *,
223 const char *, const regmatch_t *, unsigned);
224 static void expand_regexp(char *, size_t, const char *, const char *, const regmatch_t *, unsigned);
225 static const char *expand_variable( char *, unsigned, unsigned *, const char *,
226 const char *(*)(const char *, void *), void *);
227 static const char *get_variable_v2(const char *, const char *(*)(const char *, void *), void *);
228 static char get_old_ide_name(unsigned , unsigned);
229 static char *write_old_sd_name(char *, unsigned, unsigned, const char *);
231 /* busybox functions */
232 static int get_uid_gid(int flag, const char *string);
233 static void safe_memcpy(char * dest, const char * src, int len);
234 static unsigned int scan_dev_name_common(const char *d, unsigned int n, int addendum, const char *ptr);
235 static unsigned int scan_dev_name(const char *d, unsigned int n, const char *ptr);
237 /* Structs and vars */
238 static struct config_entry_struct *first_config = NULL;
239 static struct config_entry_struct *last_config = NULL;
240 static char *mount_point = NULL;
241 static volatile int caught_signal = FALSE;
242 static volatile int caught_sighup = FALSE;
243 static struct initial_symlink_struct {
246 } initial_symlinks[] = {
247 {"/proc/self/fd", "fd"},
254 static struct event_type {
255 unsigned int type; /* The DEVFSD_NOTIFY_* value */
256 const char *config_name; /* The name used in the config file */
258 {DEVFSD_NOTIFY_REGISTERED, "REGISTER"},
259 {DEVFSD_NOTIFY_UNREGISTERED, "UNREGISTER"},
260 {DEVFSD_NOTIFY_ASYNC_OPEN, "ASYNC_OPEN"},
261 {DEVFSD_NOTIFY_CLOSE, "CLOSE"},
262 {DEVFSD_NOTIFY_LOOKUP, "LOOKUP"},
263 {DEVFSD_NOTIFY_CHANGE, "CHANGE"},
264 {DEVFSD_NOTIFY_CREATE, "CREATE"},
265 {DEVFSD_NOTIFY_DELETE, "DELETE"},
269 /* Busybox messages */
271 static const char bb_msg_proto_rev[] ALIGN1 = "protocol revision";
272 static const char bb_msg_bad_config[] ALIGN1 = "bad %s config file: %s";
273 static const char bb_msg_small_buffer[] ALIGN1 = "buffer too small";
274 static const char bb_msg_variable_not_found[] ALIGN1 = "variable: %s not found";
277 #if ENABLE_DEVFSD_VERBOSE || ENABLE_DEBUG
278 #define info_logger(p, fmt, args...) bb_info_msg(fmt, ## args)
279 #define msg_logger(p, fmt, args...) bb_error_msg(fmt, ## args)
280 #define msg_logger_and_die(p, fmt, args...) bb_error_msg_and_die(fmt, ## args)
281 #define error_logger(p, fmt, args...) bb_perror_msg(fmt, ## args)
282 #define error_logger_and_die(p, fmt, args...) bb_perror_msg_and_die(fmt, ## args)
284 #define info_logger(p, fmt, args...)
285 #define msg_logger(p, fmt, args...)
286 #define msg_logger_and_die(p, fmt, args...) exit(1)
287 #define error_logger(p, fmt, args...)
288 #define error_logger_and_die(p, fmt, args...) exit(1)
291 static void safe_memcpy(char *dest, const char *src, int len)
293 memcpy(dest , src, len);
297 static unsigned int scan_dev_name_common(const char *d, unsigned int n, int addendum, const char *ptr)
299 if (d[n - 4] == 'd' && d[n - 3] == 'i' && d[n - 2] == 's' && d[n - 1] == 'c')
301 if (d[n - 2] == 'c' && d[n - 1] == 'd')
303 if (ptr[0] == 'p' && ptr[1] == 'a' && ptr[2] == 'r' && ptr[3] == 't')
305 if (ptr[n - 2] == 'm' && ptr[n - 1] == 't')
310 static unsigned int scan_dev_name(const char *d, unsigned int n, const char *ptr)
312 if (d[0] == 's' && d[1] == 'c' && d[2] == 's' && d[3] == 'i' && d[4] == '/') {
313 if (d[n - 7] == 'g' && d[n - 6] == 'e' && d[n - 5] == 'n'
314 && d[n - 4] == 'e' && d[n - 3] == 'r' && d[n - 2] == 'i' && d[n - 1] == 'c'
317 return scan_dev_name_common(d, n, 0, ptr);
319 if (d[0] == 'i' && d[1] == 'd' && d[2] == 'e' && d[3] == '/'
320 && d[4] == 'h' && d[5] == 'o' && d[6] == 's' && d[7] == 't'
322 return scan_dev_name_common(d, n, 4, ptr);
323 if (d[0] == 's' && d[1] == 'b' && d[2] == 'p' && d[3] == '/')
325 if (d[0] == 'v' && d[1] == 'c' && d[2] == 'c' && d[3] == '/')
327 if (d[0] == 'p' && d[1] == 't' && d[2] == 'y' && d[3] == '/')
332 /* Public functions follow */
334 int devfsd_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
335 int devfsd_main(int argc, char **argv)
337 int print_version = FALSE;
338 int do_daemon = TRUE;
339 int no_polling = FALSE;
341 int fd, proto_rev, count;
342 unsigned long event_mask = 0;
343 struct sigaction new_action;
344 struct initial_symlink_struct *curr;
349 for (count = 2; count < argc; ++count) {
350 if (argv[count][0] == '-') {
351 if (argv[count][1] == 'v' && !argv[count][2]) /* -v */
352 print_version = TRUE;
353 else if (ENABLE_DEVFSD_FG_NP && argv[count][1] == 'f'
354 && argv[count][2] == 'g' && !argv[count][3]) /* -fg */
356 else if (ENABLE_DEVFSD_FG_NP && argv[count][1] == 'n'
357 && argv[count][2] == 'p' && !argv[count][3]) /* -np */
364 mount_point = bb_simplify_path(argv[1]);
368 fd = xopen(".devfsd", O_RDONLY);
369 close_on_exec_on(fd);
370 xioctl(fd, DEVFSDIOC_GET_PROTO_REV, &proto_rev);
372 /*setup initial entries */
373 for (curr = initial_symlinks; curr->dest != NULL; ++curr)
374 symlink(curr->dest, curr->name);
376 /* NB: The check for CONFIG_FILE is done in read_config_file() */
378 if (print_version || (DEVFSD_PROTOCOL_REVISION_DAEMON != proto_rev)) {
379 printf("%s v%s\nDaemon %s:\t%d\nKernel-side %s:\t%d\n",
380 applet_name, DEVFSD_VERSION, bb_msg_proto_rev,
381 DEVFSD_PROTOCOL_REVISION_DAEMON, bb_msg_proto_rev, proto_rev);
382 if (DEVFSD_PROTOCOL_REVISION_DAEMON != proto_rev)
383 bb_error_msg_and_die("%s mismatch!", bb_msg_proto_rev);
384 exit(EXIT_SUCCESS); /* -v */
386 /* Tell kernel we are special(i.e. we get to see hidden entries) */
387 xioctl(fd, DEVFSDIOC_SET_EVENT_MASK, 0);
389 sigemptyset(&new_action.sa_mask);
390 new_action.sa_flags = 0;
392 /* Set up SIGHUP and SIGUSR1 handlers */
393 new_action.sa_handler = signal_handler;
394 if (sigaction(SIGHUP, &new_action, NULL) != 0 || sigaction(SIGUSR1, &new_action, NULL) != 0)
395 bb_error_msg_and_die("sigaction");
397 printf("%s v%s started for %s\n",applet_name, DEVFSD_VERSION, mount_point);
399 /* Set umask so that mknod(2), open(2) and mkdir(2) have complete control over permissions */
401 read_config_file((char*)CONFIG_FILE, FALSE, &event_mask);
402 /* Do the scan before forking, so that boot scripts see the finished product */
403 dir_operation(SERVICE, mount_point, 0, NULL);
405 if (ENABLE_DEVFSD_FG_NP && no_polling)
408 if (ENABLE_DEVFSD_VERBOSE || ENABLE_DEBUG)
409 logmode = LOGMODE_BOTH;
410 else if (do_daemon == TRUE)
411 logmode = LOGMODE_SYSLOG;
412 /* This is the default */
414 logmode = LOGMODE_STDIO; */
417 /* Release so that the child can grab it */
418 xioctl(fd, DEVFSDIOC_RELEASE_EVENT_QUEUE, 0);
419 bb_daemonize_or_rexec(0, argv);
420 } else if (ENABLE_DEVFSD_FG_NP) {
421 setpgid(0, 0); /* Become process group leader */
425 do_scan = do_servicing(fd, event_mask);
428 read_config_file((char*)CONFIG_FILE, FALSE, &event_mask);
430 dir_operation(SERVICE, mount_point, 0, NULL);
432 if (ENABLE_FEATURE_CLEAN_UP) free(mount_point);
433 } /* End Function main */
436 /* Private functions follow */
438 static void read_config_file(char *path, int optional, unsigned long *event_mask)
439 /* [SUMMARY] Read a configuration database.
440 <path> The path to read the database from. If this is a directory, all
441 entries in that directory will be read(except hidden entries).
442 <optional> If TRUE, the routine will silently ignore a missing config file.
443 <event_mask> The event mask is written here. This is not initialised.
449 char buf[STRING_LENGTH];
453 if (stat(path, &statbuf) == 0) {
454 /* Don't read 0 length files: ignored */
455 /*if (statbuf.st_size == 0)
457 if (S_ISDIR(statbuf.st_mode)) {
458 p = bb_simplify_path(path);
459 dir_operation(READ_CONFIG, p, 0, event_mask);
463 fp = fopen(path, "r");
465 while (fgets(buf, STRING_LENGTH, fp) != NULL) {
466 /* Skip whitespace */
468 line = skip_whitespace(line);
469 if (line[0] == '\0' || line[0] == '#')
471 process_config_line(line, event_mask);
475 goto read_config_file_err;
478 read_config_file_err:
479 if (optional == 0 && errno == ENOENT)
480 error_logger_and_die(LOG_ERR, "read config file: %s", path);
482 } /* End Function read_config_file */
484 static void process_config_line(const char *line, unsigned long *event_mask)
485 /* [SUMMARY] Process a line from a configuration file.
486 <line> The configuration line.
487 <event_mask> The event mask is written here. This is not initialised.
492 struct config_entry_struct *new;
493 char p[MAX_ARGS][STRING_LENGTH];
494 char when[STRING_LENGTH], what[STRING_LENGTH];
495 char name[STRING_LENGTH];
496 const char *msg = "";
500 /* !!!! Only Uppercase Keywords in devsfd.conf */
501 static const char options[] ALIGN1 =
502 "CLEAR_CONFIG\0""INCLUDE\0""OPTIONAL_INCLUDE\0"
503 "RESTORE\0""PERMISSIONS\0""MODLOAD\0""EXECUTE\0"
504 "COPY\0""IGNORE\0""MKOLDCOMPAT\0""MKNEWCOMPAT\0"
505 "RMOLDCOMPAT\0""RMNEWCOMPAT\0";
507 for (count = 0; count < MAX_ARGS; ++count)
509 num_args = sscanf(line, "%s %s %s %s %s %s %s %s %s %s",
511 p[0], p[1], p[2], p[3], p[4], p[5], p[6]);
513 i = index_in_strings(options, when);
523 goto process_config_line_err;
525 /* "INCLUDE" & "OPTIONAL_INCLUDE" */
526 if (i == 1 || i == 2) {
527 st_expr_expand(name, STRING_LENGTH, name, get_variable, NULL);
528 info_logger(LOG_INFO, "%sinclude: %s", (toupper(when[0]) == 'I') ? "": "optional_", name);
529 read_config_file(name, (toupper(when[0]) == 'I') ? FALSE : TRUE, event_mask);
534 dir_operation(RESTORE, name, strlen(name),NULL);
538 goto process_config_line_err;
540 new = xzalloc(sizeof *new);
542 for (count = 0; event_types[count].config_name != NULL; ++count) {
543 if (strcasecmp(when, event_types[count].config_name) != 0)
545 new->action.when = event_types[count].type;
548 if (event_types[count].config_name == NULL) {
550 goto process_config_line_err;
553 i = index_in_strings(options, what);
556 case 4: /* "PERMISSIONS" */
557 new->action.what = AC_PERMISSIONS;
558 /* Get user and group */
559 ptr = strchr(p[0], '.');
562 goto process_config_line_err; /*"missing '.' in UID.GID"*/
566 new->u.permissions.uid = get_uid_gid(UID, p[0]);
567 new->u.permissions.gid = get_uid_gid(GID, ptr);
569 new->u.permissions.mode = get_mode(p[1]);
571 case 5: /* MODLOAD */
572 /*This action will pass "/dev/$devname"(i.e. "/dev/" prefixed to
573 the device name) to the module loading facility. In addition,
574 the /etc/modules.devfs configuration file is used.*/
575 if (ENABLE_DEVFSD_MODLOAD)
576 new->action.what = AC_MODLOAD;
578 case 6: /* EXECUTE */
579 new->action.what = AC_EXECUTE;
582 for (count = 0; count < num_args; ++count)
583 new->u.execute.argv[count] = xstrdup(p[count]);
585 new->u.execute.argv[num_args] = NULL;
588 new->action.what = AC_COPY;
591 goto process_config_line_err; /* missing path and function in line */
593 new->u.copy.source = xstrdup(p[0]);
594 new->u.copy.destination = xstrdup(p[1]);
598 case 9: /* MKOLDCOMPAT */
600 case 10: /* MKNEWCOMPAT */
602 case 11:/* RMOLDCOMPAT */
604 case 12: /* RMNEWCOMPAT */
610 new->action.what = i - 2;
614 goto process_config_line_err;
618 xregcomp(&new->preg, name, REG_EXTENDED);
620 *event_mask |= 1 << new->action.when;
622 if (first_config == NULL)
625 last_config->next = new;
629 process_config_line_err:
630 msg_logger_and_die(LOG_ERR, bb_msg_bad_config, msg , line);
631 } /* End Function process_config_line */
633 static int do_servicing(int fd, unsigned long event_mask)
634 /* [SUMMARY] Service devfs changes until a signal is received.
635 <fd> The open control file.
636 <event_mask> The event mask.
637 [RETURNS] TRUE if SIGHUP was caught, else FALSE.
641 struct devfsd_notify_struct info;
643 /* (void*) cast is only in order to match prototype */
644 xioctl(fd, DEVFSDIOC_SET_EVENT_MASK, (void*)event_mask);
645 while (!caught_signal) {
647 bytes = read(fd,(char *) &info, sizeof info);
649 break; /* Must test for this first */
651 continue; /* Yes, the order is important */
657 int c_sighup = caught_sighup;
659 caught_signal = FALSE;
660 caught_sighup = FALSE;
663 msg_logger_and_die(LOG_ERR, "read error on control file");
664 } /* End Function do_servicing */
666 static void service_name(const struct devfsd_notify_struct *info)
667 /* [SUMMARY] Service a single devfs change.
668 <info> The devfs change.
673 regmatch_t mbuf[MAX_SUBEXPR];
674 struct config_entry_struct *entry;
676 if (ENABLE_DEBUG && info->overrun_count > 0)
677 msg_logger(LOG_ERR, "lost %u events", info->overrun_count);
679 /* Discard lookups on "/dev/log" and "/dev/initctl" */
680 if (info->type == DEVFSD_NOTIFY_LOOKUP
681 && ((info->devname[0] == 'l' && info->devname[1] == 'o'
682 && info->devname[2] == 'g' && !info->devname[3])
683 || (info->devname[0] == 'i' && info->devname[1] == 'n'
684 && info->devname[2] == 'i' && info->devname[3] == 't'
685 && info->devname[4] == 'c' && info->devname[5] == 't'
686 && info->devname[6] == 'l' && !info->devname[7]))
690 for (entry = first_config; entry != NULL; entry = entry->next) {
691 /* First check if action matches the type, then check if name matches */
692 if (info->type != entry->action.when
693 || regexec(&entry->preg, info->devname, MAX_SUBEXPR, mbuf, 0) != 0)
695 for (n = 0;(n < MAX_SUBEXPR) && (mbuf[n].rm_so != -1); ++n)
698 switch (entry->action.what) {
700 action_permissions(info, entry);
703 if (ENABLE_DEVFSD_MODLOAD)
704 action_modload(info, entry);
707 action_execute(info, entry, mbuf, n);
710 action_copy(info, entry, mbuf, n);
719 action_compat(info, entry->action.what);
722 msg_logger_and_die(LOG_ERR, "Unknown action");
725 } /* End Function service_name */
727 static void action_permissions(const struct devfsd_notify_struct *info,
728 const struct config_entry_struct *entry)
729 /* [SUMMARY] Update permissions for a device entry.
730 <info> The devfs change.
731 <entry> The config file entry.
737 if (stat(info->devname, &statbuf) != 0
738 || chmod(info->devname, (statbuf.st_mode & S_IFMT) | (entry->u.permissions.mode & ~S_IFMT)) != 0
739 || chown(info->devname, entry->u.permissions.uid, entry->u.permissions.gid) != 0
741 error_logger(LOG_ERR, "Can't chmod or chown: %s", info->devname);
742 } /* End Function action_permissions */
744 static void action_modload(const struct devfsd_notify_struct *info,
745 const struct config_entry_struct *entry ATTRIBUTE_UNUSED)
746 /* [SUMMARY] Load a module.
747 <info> The devfs change.
748 <entry> The config file entry.
754 argv[0] = (char*)MODPROBE;
755 argv[1] = (char*)MODPROBE_SWITCH_1; /* "-k" */
756 argv[2] = (char*)MODPROBE_SWITCH_2; /* "-C" */
757 argv[3] = (char*)CONFIG_MODULES_DEVFS;
758 argv[4] = concat_path_file("/dev", info->devname); /* device */
761 wait4pid(xspawn(argv));
763 } /* End Function action_modload */
765 static void action_execute(const struct devfsd_notify_struct *info,
766 const struct config_entry_struct *entry,
767 const regmatch_t *regexpr, unsigned int numexpr)
768 /* [SUMMARY] Execute a programme.
769 <info> The devfs change.
770 <entry> The config file entry.
771 <regexpr> The number of subexpression(start, end) offsets within the
773 <numexpr> The number of elements within <<regexpr>>.
778 struct get_variable_info gv_info;
779 char *argv[MAX_ARGS + 1];
780 char largv[MAX_ARGS + 1][STRING_LENGTH];
783 gv_info.devname = info->devname;
784 snprintf(gv_info.devpath, sizeof(gv_info.devpath), "%s/%s", mount_point, info->devname);
785 for (count = 0; entry->u.execute.argv[count] != NULL; ++count) {
786 expand_expression(largv[count], STRING_LENGTH,
787 entry->u.execute.argv[count],
788 get_variable, &gv_info,
789 gv_info.devname, regexpr, numexpr);
790 argv[count] = largv[count];
793 wait4pid(spawn(argv));
794 } /* End Function action_execute */
797 static void action_copy(const struct devfsd_notify_struct *info,
798 const struct config_entry_struct *entry,
799 const regmatch_t *regexpr, unsigned int numexpr)
800 /* [SUMMARY] Copy permissions.
801 <info> The devfs change.
802 <entry> The config file entry.
803 <regexpr> This list of subexpression(start, end) offsets within the
805 <numexpr> The number of elements in <<regexpr>>.
810 struct get_variable_info gv_info;
811 struct stat source_stat, dest_stat;
812 char source[STRING_LENGTH], destination[STRING_LENGTH];
815 dest_stat.st_mode = 0;
817 if ((info->type == DEVFSD_NOTIFY_CHANGE) && S_ISLNK(info->mode))
820 gv_info.devname = info->devname;
822 snprintf(gv_info.devpath, sizeof(gv_info.devpath), "%s/%s", mount_point, info->devname);
823 expand_expression(source, STRING_LENGTH, entry->u.copy.source,
824 get_variable, &gv_info, gv_info.devname,
827 expand_expression(destination, STRING_LENGTH, entry->u.copy.destination,
828 get_variable, &gv_info, gv_info.devname,
831 if (!make_dir_tree(destination) || lstat(source, &source_stat) != 0)
833 lstat(destination, &dest_stat);
834 new_mode = source_stat.st_mode & ~S_ISVTX;
835 if (info->type == DEVFSD_NOTIFY_CREATE)
837 else if ((info->type == DEVFSD_NOTIFY_CHANGE) &&(dest_stat.st_mode & S_ISVTX))
839 ret = copy_inode(destination, &dest_stat, new_mode, source, &source_stat);
840 if (ENABLE_DEBUG && ret && (errno != EEXIST))
841 error_logger(LOG_ERR, "copy_inode: %s to %s", source, destination);
842 } /* End Function action_copy */
844 static void action_compat(const struct devfsd_notify_struct *info, unsigned int action)
845 /* [SUMMARY] Process a compatibility request.
846 <info> The devfs change.
847 <action> The action to take.
852 const char *compat_name = NULL;
853 const char *dest_name = info->devname;
855 char compat_buf[STRING_LENGTH], dest_buf[STRING_LENGTH];
856 int mode, host, bus, target, lun;
859 /* 1 to 5 "scsi/" , 6 to 9 "ide/host" */
860 static const char *const fmt[] = {
862 "sg/c%db%dt%du%d", /* scsi/generic */
863 "sd/c%db%dt%du%d", /* scsi/disc */
864 "sr/c%db%dt%du%d", /* scsi/cd */
865 "sd/c%db%dt%du%dp%d", /* scsi/part */
866 "st/c%db%dt%du%dm%d%c", /* scsi/mt */
867 "ide/hd/c%db%dt%du%d", /* ide/host/disc */
868 "ide/cd/c%db%dt%du%d", /* ide/host/cd */
869 "ide/hd/c%db%dt%du%dp%d", /* ide/host/part */
870 "ide/mt/c%db%dt%du%d%s", /* ide/host/mt */
874 /* First construct compatibility name */
878 compat_name = get_old_name(info->devname, info->namelen, compat_buf, info->major, info->minor);
882 ptr = bb_basename(info->devname);
883 i = scan_dev_name(info->devname, info->namelen, ptr);
889 sscanf(info->devname + ((i < 6) ? 5 : 4), "host%d/bus%d/target%d/lun%d/", &host, &bus, &target, &lun);
890 snprintf(dest_buf, sizeof(dest_buf), "../%s", info->devname + (( i > 5) ? 4 : 0));
891 dest_name = dest_buf;
892 compat_name = compat_buf;
895 /* 1 == scsi/generic 2 == scsi/disc 3 == scsi/cd 6 == ide/host/disc 7 == ide/host/cd */
896 if (i == 1 || i == 2 || i == 3 || i == 6 || i ==7)
897 sprintf(compat_buf, fmt[i], host, bus, target, lun);
899 /* 4 == scsi/part 8 == ide/host/part */
900 if (i == 4 || i == 8)
901 sprintf(compat_buf, fmt[i], host, bus, target, lun, atoi(ptr + 4));
905 rewind_ = info->devname[info->namelen - 1];
909 if (ptr[2] == 'l' /*108*/ || ptr[2] == 'm'/*109*/)
910 mode = ptr[2] - 107; /* 1 or 2 */
913 sprintf(compat_buf, fmt[i], host, bus, target, lun, mode, rewind_);
916 /* 9 == ide/host/mt */
918 snprintf(compat_buf, sizeof(compat_buf), fmt[i], host, bus, target, lun, ptr + 2);
920 } /* switch (action) */
922 if (compat_name == NULL)
925 /* Now decide what to do with it */
929 mksymlink(dest_name, compat_name);
933 ret = unlink(compat_name);
934 if (ENABLE_DEBUG && ret)
935 error_logger(LOG_ERR, "unlink: %s", compat_name);
938 } /* switch (action) */
939 } /* End Function action_compat */
941 static void restore(char *spath, struct stat source_stat, int rootlen)
944 struct stat dest_stat;
946 dest_stat.st_mode = 0;
947 dpath = concat_path_file(mount_point, spath + rootlen);
948 lstat(dpath, &dest_stat);
950 if (S_ISLNK(source_stat.st_mode) || (source_stat.st_mode & S_ISVTX))
951 copy_inode(dpath, &dest_stat,(source_stat.st_mode & ~S_ISVTX) , spath, &source_stat);
953 if (S_ISDIR(source_stat.st_mode))
954 dir_operation(RESTORE, spath, rootlen,NULL);
958 static int copy_inode(const char *destpath, const struct stat *dest_stat,
960 const char *sourcepath, const struct stat *source_stat)
961 /* [SUMMARY] Copy an inode.
962 <destpath> The destination path. An existing inode may be deleted.
963 <dest_stat> The destination stat(2) information.
964 <new_mode> The desired new mode for the destination.
965 <sourcepath> The source path.
966 <source_stat> The source stat(2) information.
967 [RETURNS] TRUE on success, else FALSE.
970 int source_len, dest_len;
971 char source_link[STRING_LENGTH], dest_link[STRING_LENGTH];
973 struct sockaddr_un un_addr;
974 char symlink_val[STRING_LENGTH];
976 if ((source_stat->st_mode & S_IFMT) ==(dest_stat->st_mode & S_IFMT)) {
978 if (S_ISLNK(source_stat->st_mode)) {
979 source_len = readlink(sourcepath, source_link, STRING_LENGTH - 1);
981 || (dest_len = readlink(destpath, dest_link, STRING_LENGTH - 1)) < 0
984 source_link[source_len] = '\0';
985 dest_link[dest_len] = '\0';
986 if ((source_len != dest_len) || (strcmp(source_link, dest_link) != 0)) {
988 symlink(source_link, destpath);
991 } /* Else not a symlink */
992 chmod(destpath, new_mode & ~S_IFMT);
993 chown(destpath, source_stat->st_uid, source_stat->st_gid);
996 /* Different types: unlink and create */
998 switch (source_stat->st_mode & S_IFMT) {
1000 fd = socket(AF_UNIX, SOCK_STREAM, 0);
1003 un_addr.sun_family = AF_UNIX;
1004 snprintf(un_addr.sun_path, sizeof(un_addr.sun_path), "%s", destpath);
1005 val = bind(fd,(struct sockaddr *) &un_addr,(int) sizeof un_addr);
1007 if (val != 0 || chmod(destpath, new_mode & ~S_IFMT) != 0)
1011 val = readlink(sourcepath, symlink_val, STRING_LENGTH - 1);
1014 symlink_val[val] = '\0';
1015 if (symlink(symlink_val, destpath) == 0)
1019 fd = open(destpath, O_RDONLY | O_CREAT, new_mode & ~S_IFMT);
1023 if (chmod(destpath, new_mode & ~S_IFMT) != 0)
1029 if (mknod(destpath, new_mode, source_stat->st_rdev) != 0)
1033 if (mkdir(destpath, new_mode & ~S_IFMT) != 0)
1036 if (chown(destpath, source_stat->st_uid, source_stat->st_gid) == 0)
1041 } /* End Function copy_inode */
1043 static void free_config(void)
1044 /* [SUMMARY] Free the configuration information.
1048 struct config_entry_struct *c_entry;
1051 for (c_entry = first_config; c_entry != NULL; c_entry = next) {
1054 next = c_entry->next;
1055 regfree(&c_entry->preg);
1056 if (c_entry->action.what == AC_EXECUTE) {
1057 for (count = 0; count < MAX_ARGS; ++count) {
1058 if (c_entry->u.execute.argv[count] == NULL)
1060 free(c_entry->u.execute.argv[count]);
1065 first_config = NULL;
1067 } /* End Function free_config */
1069 static int get_uid_gid(int flag, const char *string)
1070 /* [SUMMARY] Convert a string to a UID or GID value.
1071 <flag> "UID" or "GID".
1072 <string> The string.
1073 [RETURNS] The UID or GID value.
1076 struct passwd *pw_ent;
1077 struct group *grp_ent;
1078 static const char *msg;
1080 if (ENABLE_DEVFSD_VERBOSE)
1083 if (isdigit(string[0]) ||((string[0] == '-') && isdigit(string[1])))
1084 return atoi(string);
1086 if (flag == UID && (pw_ent = getpwnam(string)) != NULL)
1087 return pw_ent->pw_uid;
1089 if (flag == GID && (grp_ent = getgrnam(string)) != NULL)
1090 return grp_ent->gr_gid;
1091 else if (ENABLE_DEVFSD_VERBOSE)
1094 if (ENABLE_DEVFSD_VERBOSE)
1095 msg_logger(LOG_ERR,"unknown %s: %s, defaulting to %cid=0", msg, string, msg[0]);
1097 }/* End Function get_uid_gid */
1099 static mode_t get_mode(const char *string)
1100 /* [SUMMARY] Convert a string to a mode value.
1101 <string> The string.
1102 [RETURNS] The mode value.
1108 if (isdigit(string[0]))
1109 return strtoul(string, NULL, 8);
1110 if (strlen(string) != 9)
1111 msg_logger_and_die(LOG_ERR, "bad mode: %s", string);
1116 if (string[0] == 'r' || string[0] == 'w' || string[0] == 'x')
1122 } /* End Function get_mode */
1124 static void signal_handler(int sig)
1126 caught_signal = TRUE;
1128 caught_sighup = TRUE;
1130 info_logger(LOG_INFO, "Caught signal %d", sig);
1131 } /* End Function signal_handler */
1133 static const char *get_variable(const char *variable, void *info)
1135 static char sbuf[sizeof(int)*3 + 2]; /* sign and NUL */
1137 char hostname[STRING_LENGTH];
1138 struct get_variable_info *gv_info = info;
1139 const char *field_names[] = {
1140 "hostname", "mntpt", "devpath", "devname",
1141 "uid", "gid", "mode", hostname, mount_point,
1142 gv_info->devpath, gv_info->devname, NULL
1146 if (gethostname(hostname, STRING_LENGTH - 1) != 0)
1147 /* Here on error we should do exit(RV_SYS_ERROR), instead we do exit(EXIT_FAILURE) */
1148 error_logger_and_die(LOG_ERR, "gethostname");
1150 hostname[STRING_LENGTH - 1] = '\0';
1152 /* index_in_str_array returns i>=0 */
1153 i = index_in_str_array(field_names, variable);
1155 if (i > 6 || i < 0 || (i > 1 && gv_info == NULL))
1157 if (i >= 0 && i <= 3)
1158 return field_names[i + 7];
1161 sprintf(sbuf, "%u", gv_info->info->uid);
1163 sprintf(sbuf, "%u", gv_info->info->gid);
1165 sprintf(sbuf, "%o", gv_info->info->mode);
1167 } /* End Function get_variable */
1169 static void service(struct stat statbuf, char *path)
1171 struct devfsd_notify_struct info;
1173 memset(&info, 0, sizeof info);
1174 info.type = DEVFSD_NOTIFY_REGISTERED;
1175 info.mode = statbuf.st_mode;
1176 info.major = major(statbuf.st_rdev);
1177 info.minor = minor(statbuf.st_rdev);
1178 info.uid = statbuf.st_uid;
1179 info.gid = statbuf.st_gid;
1180 snprintf(info.devname, sizeof(info.devname), "%s", path + strlen(mount_point) + 1);
1181 info.namelen = strlen(info.devname);
1182 service_name(&info);
1183 if (S_ISDIR(statbuf.st_mode))
1184 dir_operation(SERVICE, path, 0, NULL);
1187 static void dir_operation(int type, const char * dir_name, int var, unsigned long *event_mask)
1188 /* [SUMMARY] Scan a directory tree and generate register events on leaf nodes.
1189 <flag> To choose which function to perform
1190 <dp> The directory pointer. This is closed upon completion.
1191 <dir_name> The name of the directory.
1192 <rootlen> string length parameter.
1196 struct stat statbuf;
1201 dp = warn_opendir(dir_name);
1205 while ((de = readdir(dp)) != NULL) {
1207 if (de->d_name && DOT_OR_DOTDOT(de->d_name))
1209 path = concat_path_file(dir_name, de->d_name);
1210 if (lstat(path, &statbuf) == 0) {
1213 service(statbuf, path);
1216 restore(path, statbuf, var);
1219 read_config_file(path, var, event_mask);
1226 } /* End Function do_scan_and_service */
1228 static int mksymlink(const char *oldpath, const char *newpath)
1229 /* [SUMMARY] Create a symlink, creating intervening directories as required.
1230 <oldpath> The string contained in the symlink.
1231 <newpath> The name of the new symlink.
1232 [RETURNS] 0 on success, else -1.
1235 if (!make_dir_tree(newpath))
1238 if (symlink(oldpath, newpath) != 0) {
1239 if (errno != EEXIST)
1243 } /* End Function mksymlink */
1246 static int make_dir_tree(const char *path)
1247 /* [SUMMARY] Creating intervening directories for a path as required.
1248 <path> The full pathname(including the leaf node).
1249 [RETURNS] TRUE on success, else FALSE.
1252 if (bb_make_directory(dirname((char *)path), -1, FILEUTILS_RECUR) == -1)
1255 } /* End Function make_dir_tree */
1257 static int expand_expression(char *output, unsigned int outsize,
1259 const char *(*get_variable_func)(const char *variable, void *info),
1261 const char *devname,
1262 const regmatch_t *ex, unsigned int numexp)
1263 /* [SUMMARY] Expand environment variables and regular subexpressions in string.
1264 <output> The output expanded expression is written here.
1265 <length> The size of the output buffer.
1266 <input> The input expression. This may equal <<output>>.
1267 <get_variable> A function which will be used to get variable values. If
1268 this returns NULL, the environment is searched instead. If this is NULL,
1269 only the environment is searched.
1270 <info> An arbitrary pointer passed to <<get_variable>>.
1271 <devname> Device name; specifically, this is the string that contains all
1272 of the regular subexpressions.
1273 <ex> Array of start / end offsets into info->devname for each subexpression
1274 <numexp> Number of regular subexpressions found in <<devname>>.
1275 [RETURNS] TRUE on success, else FALSE.
1278 char temp[STRING_LENGTH];
1280 if (!st_expr_expand(temp, STRING_LENGTH, input, get_variable_func, info))
1282 expand_regexp(output, outsize, temp, devname, ex, numexp);
1284 } /* End Function expand_expression */
1286 static void expand_regexp(char *output, size_t outsize, const char *input,
1287 const char *devname,
1288 const regmatch_t *ex, unsigned int numex)
1289 /* [SUMMARY] Expand all occurrences of the regular subexpressions \0 to \9.
1290 <output> The output expanded expression is written here.
1291 <outsize> The size of the output buffer.
1292 <input> The input expression. This may NOT equal <<output>>, because
1293 supporting that would require yet another string-copy. However, it's not
1294 hard to write a simple wrapper function to add this functionality for those
1295 few cases that need it.
1296 <devname> Device name; specifically, this is the string that contains all
1297 of the regular subexpressions.
1298 <ex> An array of start and end offsets into <<devname>>, one for each
1300 <numex> Number of subexpressions in the offset-array <<ex>>.
1304 const char last_exp = '0' - 1 + numex;
1307 /* Guarantee NULL termination by writing an explicit '\0' character into
1308 the very last byte */
1310 output[--outsize] = '\0';
1311 /* Copy the input string into the output buffer, replacing '\\' with '\'
1312 and '\0' .. '\9' with subexpressions 0 .. 9, if they exist. Other \x
1313 codes are deleted */
1314 while ((c != '\0') && (outsize != 0)) {
1321 if ((c >= '0') && (c <= last_exp)) {
1322 const regmatch_t *subexp = ex + (c - '0');
1323 unsigned int sublen = subexp->rm_eo - subexp->rm_so;
1325 /* Range checking */
1326 if (sublen > outsize)
1328 strncpy(output, devname + subexp->rm_so, sublen);
1339 } /* End Function expand_regexp */
1342 /* from compat_name.c */
1344 struct translate_struct
1346 const char *match; /* The string to match to(up to length) */
1347 const char *format; /* Format of output, "%s" takes data past match string,
1348 NULL is effectively "%s"(just more efficient) */
1351 static struct translate_struct translate_table[] =
1354 {"printers/", "lp%s"},
1356 {"parports/", "parport%s"},
1359 {"loop/", "loop%s"},
1360 {"floppy/", "fd%s"},
1362 {"md/", "md%s"}, /* Meta-devices */
1366 {"pg/", "pg%s"}, /* Parallel port generic ATAPI interface*/
1368 {"staliomem/", "staliomem%s"}, /* Stallion serial driver control */
1369 {"tts/E", "ttyE%s"}, /* Stallion serial driver */
1370 {"cua/E", "cue%s"}, /* Stallion serial driver callout */
1371 {"tts/R", "ttyR%s"}, /* Rocketport serial driver */
1372 {"cua/R", "cur%s"}, /* Rocketport serial driver callout */
1373 {"ip2/", "ip2%s"}, /* Computone serial driver control */
1374 {"tts/F", "ttyF%s"}, /* Computone serial driver */
1375 {"cua/F", "cuf%s"}, /* Computone serial driver callout */
1376 {"tts/C", "ttyC%s"}, /* Cyclades serial driver */
1377 {"cua/C", "cub%s"}, /* Cyclades serial driver callout */
1378 {"tts/", "ttyS%s"}, /* Generic serial: must be after others */
1379 {"cua/", "cua%s"}, /* Generic serial: must be after others */
1380 {"input/js", "js%s"}, /* Joystick driver */
1384 const char *get_old_name(const char *devname, unsigned int namelen,
1385 char *buffer, unsigned int major, unsigned int minor)
1386 /* [SUMMARY] Translate a kernel-supplied name into an old name.
1387 <devname> The device name provided by the kernel.
1388 <namelen> The length of the name.
1389 <buffer> A buffer that may be used. This should be at least 128 bytes long.
1390 <major> The major number for the device.
1391 <minor> The minor number for the device.
1392 [RETURNS] A pointer to the old name if known, else NULL.
1395 const char *compat_name = NULL;
1397 struct translate_struct *trans;
1404 /* 1 to 5 "scsi/" , 6 to 9 "ide/host", 10 sbp/, 11 vcc/, 12 pty/ */
1405 static const char *const fmt[] = {
1407 "sg%u", /* scsi/generic */
1408 NULL, /* scsi/disc */
1409 "sr%u", /* scsi/cd */
1410 NULL, /* scsi/part */
1411 "nst%u%c", /* scsi/mt */
1412 "hd%c" , /* ide/host/disc */
1413 "hd%c" , /* ide/host/cd */
1414 "hd%c%s", /* ide/host/part */
1415 "%sht%d", /* ide/host/mt */
1416 "sbpcd%u", /* sbp/ */
1418 "%cty%c%c", /* pty/ */
1422 for (trans = translate_table; trans->match != NULL; ++trans) {
1423 len = strlen(trans->match);
1425 if (strncmp(devname, trans->match, len) == 0) {
1426 if (trans->format == NULL)
1427 return devname + len;
1428 sprintf(buffer, trans->format, devname + len);
1433 ptr = bb_basename(devname);
1434 i = scan_dev_name(devname, namelen, ptr);
1436 if (i > 0 && i < 13)
1437 compat_name = buffer;
1441 /* 1 == scsi/generic, 3 == scsi/cd, 10 == sbp/ */
1442 if (i == 1 || i == 3 || i == 10)
1443 sprintf(buffer, fmt[i], minor);
1445 /* 2 ==scsi/disc, 4 == scsi/part */
1446 if (i == 2 || i == 4)
1447 compat_name = write_old_sd_name(buffer, major, minor,((i == 2) ? "" : (ptr + 4)));
1454 sprintf(buffer, fmt[i], minor & 0x1f, mode);
1455 if (devname[namelen - 1] != 'n')
1458 /* 6 == ide/host/disc, 7 == ide/host/cd, 8 == ide/host/part */
1459 if (i == 6 || i == 7 || i == 8)
1460 /* last arg should be ignored for i == 6 or i== 7 */
1461 sprintf(buffer, fmt[i] , get_old_ide_name(major, minor), ptr + 4);
1463 /* 9 == ide/host/mt */
1465 sprintf(buffer, fmt[i], ptr + 2, minor & 0x7f);
1469 sprintf(buffer, fmt[i], devname + 4);
1470 if (buffer[3] == '0')
1475 pty1 = "pqrstuvwxyzabcde";
1476 pty2 = "0123456789abcdef";
1477 indexx = atoi(devname + 5);
1478 sprintf(buffer, fmt[i], (devname[4] == 'm') ? 'p' : 't', pty1[indexx >> 4], pty2[indexx & 0x0f]);
1481 } /* End Function get_old_name */
1483 static char get_old_ide_name(unsigned int major, unsigned int minor)
1484 /* [SUMMARY] Get the old IDE name for a device.
1485 <major> The major number for the device.
1486 <minor> The minor number for the device.
1487 [RETURNS] The drive letter.
1490 char letter = 'y'; /* 121 */
1491 char c = 'a'; /* 97 */
1494 /* I hope it works like the previous code as it saves a few bytes. Tito ;P */
1496 if (i == IDE0_MAJOR || i == IDE1_MAJOR || i == IDE2_MAJOR
1497 || i == IDE3_MAJOR || i == IDE4_MAJOR || i == IDE5_MAJOR
1498 || i == IDE6_MAJOR || i == IDE7_MAJOR || i == IDE8_MAJOR
1501 if ((unsigned int)i == major) {
1508 } while (i <= IDE9_MAJOR);
1513 } /* End Function get_old_ide_name */
1515 static char *write_old_sd_name(char *buffer,
1516 unsigned int major, unsigned int minor,
1518 /* [SUMMARY] Write the old SCSI disc name to a buffer.
1519 <buffer> The buffer to write to.
1520 <major> The major number for the device.
1521 <minor> The minor number for the device.
1522 <part> The partition string. Must be "" for a whole-disc entry.
1523 [RETURNS] A pointer to the buffer on success, else NULL.
1526 unsigned int disc_index;
1529 sprintf(buffer, "sd%c%s", 'a' + (minor >> 4), part);
1532 if ((major > 64) && (major < 72)) {
1533 disc_index = ((major - 64) << 4) +(minor >> 4);
1534 if (disc_index < 26)
1535 sprintf(buffer, "sd%c%s", 'a' + disc_index, part);
1537 sprintf(buffer, "sd%c%c%s", 'a' +(disc_index / 26) - 1, 'a' + disc_index % 26, part);
1541 } /* End Function write_old_sd_name */
1546 /*EXPERIMENTAL_FUNCTION*/
1548 int st_expr_expand(char *output, unsigned int length, const char *input,
1549 const char *(*get_variable_func)(const char *variable,
1552 /* [SUMMARY] Expand an expression using Borne Shell-like unquoted rules.
1553 <output> The output expanded expression is written here.
1554 <length> The size of the output buffer.
1555 <input> The input expression. This may equal <<output>>.
1556 <get_variable> A function which will be used to get variable values. If
1557 this returns NULL, the environment is searched instead. If this is NULL,
1558 only the environment is searched.
1559 <info> An arbitrary pointer passed to <<get_variable>>.
1560 [RETURNS] TRUE on success, else FALSE.
1565 unsigned int out_pos = 0;
1568 struct passwd *pwent;
1569 char buffer[BUFFER_SIZE], tmp[STRING_LENGTH];
1571 if (length > BUFFER_SIZE)
1572 length = BUFFER_SIZE;
1573 for (; TRUE; ++input) {
1574 switch (ch = *input) {
1576 /* Variable expansion */
1577 input = expand_variable(buffer, length, &out_pos, ++input, get_variable_func, info);
1582 /* Home directory expansion */
1584 if (isspace(ch) ||(ch == '/') ||(ch == '\0')) {
1585 /* User's own home directory: leave separator for next time */
1586 env = getenv("HOME");
1588 info_logger(LOG_INFO, bb_msg_variable_not_found, "HOME");
1592 if (len + out_pos >= length)
1593 goto st_expr_expand_out;
1594 memcpy(buffer + out_pos, env, len + 1);
1598 /* Someone else's home directory */
1599 for (ptr = ++input; !isspace(ch) && (ch != '/') && (ch != '\0'); ch = *++ptr)
1602 if (len >= sizeof tmp)
1603 goto st_expr_expand_out;
1604 safe_memcpy(tmp, input, len);
1606 pwent = getpwnam(tmp);
1607 if (pwent == NULL) {
1608 info_logger(LOG_INFO, "no pwent for: %s", tmp);
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);
1620 if (out_pos >= length)
1621 goto st_expr_expand_out;
1622 buffer[out_pos++] = ch;
1624 memcpy(output, buffer, out_pos);
1633 info_logger(LOG_INFO, bb_msg_small_buffer);
1635 } /* End Function st_expr_expand */
1638 /* Private functions follow */
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,
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.
1660 unsigned int open_braces;
1661 const char *env, *ptr;
1662 char tmp[STRING_LENGTH];
1666 /* Special case for "$$": PID */
1667 sprintf(tmp, "%d",(int) getpid());
1669 if (len + *out_pos >= length)
1670 goto expand_variable_out;
1672 memcpy(buffer + *out_pos, tmp, len + 1);
1676 /* Ordinary variable expansion, possibly in braces */
1678 /* Simple variable expansion */
1679 for (ptr = input; isalnum(ch) || (ch == '_') || (ch == ':'); ch = *++ptr)
1682 if ((size_t)len >= sizeof tmp)
1683 goto expand_variable_out;
1685 safe_memcpy(tmp, input, len);
1687 env = get_variable_v2(tmp, func, info);
1689 info_logger(LOG_INFO, bb_msg_variable_not_found, tmp);
1693 if (len + *out_pos >= length)
1694 goto expand_variable_out;
1696 memcpy(buffer + *out_pos, env, len + 1);
1700 /* Variable in braces: check for ':' tricks */
1702 for (ptr = input; isalnum(ch) || (ch == '_'); ch = *++ptr)
1705 /* Must be simple variable expansion with "${var}" */
1707 if ((size_t)len >= sizeof tmp)
1708 goto expand_variable_out;
1710 safe_memcpy(tmp, input, len);
1711 ptr = expand_variable(buffer, length, out_pos, tmp, func, info);
1716 if (ch != ':' || ptr[1] != '-') {
1717 info_logger(LOG_INFO, "illegal char in var name");
1720 /* It's that handy "${var:-word}" expression. Check if var is defined */
1722 if ((size_t)len >= sizeof tmp)
1723 goto expand_variable_out;
1725 safe_memcpy(tmp, input, len);
1726 /* Move input pointer to ':' */
1728 /* First skip to closing brace, taking note of nested expressions */
1731 for (open_braces = 1; open_braces > 0; ch = *++ptr) {
1740 info_logger(LOG_INFO,"\"}\" not found in: %s", input);
1747 /* At this point ptr should point to closing brace of "${var:-word}" */
1748 env = get_variable_v2(tmp, func, info);
1750 /* Found environment variable, so skip the input to the closing brace
1751 and return the variable */
1754 if (len + *out_pos >= length)
1755 goto expand_variable_out;
1757 memcpy(buffer + *out_pos, env, len + 1);
1761 /* Environment variable was not found, so process word. Advance input
1762 pointer to start of word in "${var:-word}" */
1765 if ((size_t)len >= sizeof tmp)
1766 goto expand_variable_out;
1768 safe_memcpy(tmp, input, len);
1770 if (!st_expr_expand(tmp, STRING_LENGTH, tmp, func, info))
1773 if (len + *out_pos >= length)
1774 goto expand_variable_out;
1776 memcpy(buffer + *out_pos, tmp, len + 1);
1779 expand_variable_out:
1780 info_logger(LOG_INFO, bb_msg_small_buffer);
1782 } /* End Function expand_variable */
1785 static const char *get_variable_v2(const char *variable,
1786 const char *(*func)(const char *variable, void *info),
1788 /* [SUMMARY] Get a variable from the environment or .
1789 <variable> The variable name.
1790 <func> A function which will be used to get the variable. If this returns
1791 NULL, the environment is searched instead. If this is NULL, only the
1792 environment is searched.
1793 [RETURNS] The value of the variable on success, else NULL.
1799 value = (*func)(variable, info);
1803 return getenv(variable);
1804 } /* End Function get_variable */