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.
57 //#include <sys/wait.h>
58 //#include <sys/ioctl.h>
59 //#include <sys/socket.h>
63 #include <sys/sysmacros.h>
68 /* Various defines taken from linux/major.h */
81 /* Various defines taken from linux/devfs_fs.h */
82 #define DEVFSD_PROTOCOL_REVISION_KERNEL 5
83 #define DEVFSD_IOCTL_BASE 'd'
84 /* These are the various ioctls */
85 #define DEVFSDIOC_GET_PROTO_REV _IOR(DEVFSD_IOCTL_BASE, 0, int)
86 #define DEVFSDIOC_SET_EVENT_MASK _IOW(DEVFSD_IOCTL_BASE, 2, int)
87 #define DEVFSDIOC_RELEASE_EVENT_QUEUE _IOW(DEVFSD_IOCTL_BASE, 3, int)
88 #define DEVFSDIOC_SET_CONFIG_DEBUG_MASK _IOW(DEVFSD_IOCTL_BASE, 4, int)
89 #define DEVFSD_NOTIFY_REGISTERED 0
90 #define DEVFSD_NOTIFY_UNREGISTERED 1
91 #define DEVFSD_NOTIFY_ASYNC_OPEN 2
92 #define DEVFSD_NOTIFY_CLOSE 3
93 #define DEVFSD_NOTIFY_LOOKUP 4
94 #define DEVFSD_NOTIFY_CHANGE 5
95 #define DEVFSD_NOTIFY_CREATE 6
96 #define DEVFSD_NOTIFY_DELETE 7
97 #define DEVFS_PATHLEN 1024
98 /* Never change this otherwise the binary interface will change */
100 struct devfsd_notify_struct
101 { /* Use native C types to ensure same types in kernel and user space */
102 unsigned int type; /* DEVFSD_NOTIFY_* value */
103 unsigned int mode; /* Mode of the inode or device entry */
104 unsigned int major; /* Major number of device entry */
105 unsigned int minor; /* Minor number of device entry */
106 unsigned int uid; /* Uid of process, inode or device entry */
107 unsigned int gid; /* Gid of process, inode or device entry */
108 unsigned int overrun_count; /* Number of lost events */
109 unsigned int namelen; /* Number of characters not including '\0' */
110 /* The device name MUST come last */
111 char devname[DEVFS_PATHLEN]; /* This will be '\0' terminated */
114 #define BUFFER_SIZE 16384
115 #define DEVFSD_VERSION "1.3.25"
116 #define CONFIG_FILE "/etc/devfsd.conf"
117 #define MODPROBE "/sbin/modprobe"
118 #define MODPROBE_SWITCH_1 "-k"
119 #define MODPROBE_SWITCH_2 "-C"
120 #define CONFIG_MODULES_DEVFS "/etc/modules.devfs"
121 #define MAX_ARGS (6 + 1)
122 #define MAX_SUBEXPR 10
123 #define STRING_LENGTH 255
125 /* for get_uid_gid() */
129 /* fork_and_execute() */
133 /* for dir_operation() */
136 #define READ_CONFIG 2
138 /* Update only after changing code to reflect new protocol */
139 #define DEVFSD_PROTOCOL_REVISION_DAEMON 5
141 /* Compile-time check */
142 #if DEVFSD_PROTOCOL_REVISION_KERNEL != DEVFSD_PROTOCOL_REVISION_DAEMON
143 #error protocol version mismatch. Update your kernel headers
146 #define AC_PERMISSIONS 0
149 #define AC_MFUNCTION 3 /* not supported by busybox */
150 #define AC_CFUNCTION 4 /* not supported by busybox */
153 #define AC_MKOLDCOMPAT 7
154 #define AC_MKNEWCOMPAT 8
155 #define AC_RMOLDCOMPAT 9
156 #define AC_RMNEWCOMPAT 10
157 #define AC_RESTORE 11
159 struct permissions_type
168 char *argv[MAX_ARGS + 1]; /* argv[0] must always be the programme */
174 const char *destination;
183 struct config_entry_struct
185 struct action_type action;
189 struct permissions_type permissions;
190 struct execute_type execute;
191 struct copy_type copy;
194 struct config_entry_struct *next;
197 struct get_variable_info
199 const struct devfsd_notify_struct *info;
201 char devpath[STRING_LENGTH];
204 static void dir_operation(int , const char * , int, unsigned long*);
205 static void service(struct stat statbuf, char *path);
206 static int st_expr_expand(char *, unsigned, const char *, const char *(*)(const char *, void *), void *);
207 static const char *get_old_name(const char *, unsigned, char *, unsigned, unsigned);
208 static int mksymlink(const char *oldpath, const char *newpath);
209 static void read_config_file(char *path, int optional, unsigned long *event_mask);
210 static void process_config_line(const char *, unsigned long *);
211 static int do_servicing(int, unsigned long);
212 static void service_name(const struct devfsd_notify_struct *);
213 static void action_permissions(const struct devfsd_notify_struct *, const struct config_entry_struct *);
214 static void action_execute(const struct devfsd_notify_struct *, const struct config_entry_struct *,
215 const regmatch_t *, unsigned);
216 static void action_modload(const struct devfsd_notify_struct *info, const struct config_entry_struct *entry);
217 static void action_copy(const struct devfsd_notify_struct *, const struct config_entry_struct *,
218 const regmatch_t *, unsigned);
219 static void action_compat(const struct devfsd_notify_struct *, unsigned);
220 static void free_config(void);
221 static void restore(char *spath, struct stat source_stat, int rootlen);
222 static int copy_inode(const char *, const struct stat *, mode_t, const char *, const struct stat *);
223 static mode_t get_mode(const char *);
224 static void signal_handler(int);
225 static const char *get_variable(const char *, void *);
226 static int make_dir_tree(const char *);
227 static int expand_expression(char *, unsigned, const char *, const char *(*)(const char *, void *), void *,
228 const char *, const regmatch_t *, unsigned);
229 static void expand_regexp(char *, size_t, const char *, const char *, const regmatch_t *, unsigned);
230 static const char *expand_variable( char *, unsigned, unsigned *, const char *,
231 const char *(*)(const char *, void *), void *);
232 static const char *get_variable_v2(const char *, const char *(*)(const char *, void *), void *);
233 static char get_old_ide_name(unsigned , unsigned);
234 static char *write_old_sd_name(char *, unsigned, unsigned, const char *);
236 /* busybox functions */
237 static void msg_logger(int pri, const char * fmt, ...)__attribute__((format(printf, 2, 3)));
238 static void msg_logger_and_die(int pri, const char * fmt, ...)__attribute__((noreturn, format(printf, 2, 3)));
239 static void do_ioctl_and_die(int fd, int request, unsigned long event_mask_flag);
240 static void fork_and_execute(int die, char *arg0, char **arg);
241 static int get_uid_gid(int, const char *);
242 static void safe_memcpy(char * dest, const char * src, int len);
243 static unsigned int scan_dev_name_common(const char *d, unsigned int n, int addendum, const char *ptr);
244 static unsigned int scan_dev_name(const char *d, unsigned int n, const char *ptr);
246 /* Structs and vars */
247 static struct config_entry_struct *first_config = NULL;
248 static struct config_entry_struct *last_config = NULL;
249 static const char *mount_point = NULL;
250 static volatile int caught_signal = FALSE;
251 static volatile int caught_sighup = FALSE;
252 static struct initial_symlink_struct
256 } initial_symlinks[] =
258 {"/proc/self/fd", "fd"},
265 static struct event_type
267 unsigned int type; /* The DEVFSD_NOTIFY_* value */
268 const char *config_name; /* The name used in the config file */
271 {DEVFSD_NOTIFY_REGISTERED, "REGISTER"},
272 {DEVFSD_NOTIFY_UNREGISTERED, "UNREGISTER"},
273 {DEVFSD_NOTIFY_ASYNC_OPEN, "ASYNC_OPEN"},
274 {DEVFSD_NOTIFY_CLOSE, "CLOSE"},
275 {DEVFSD_NOTIFY_LOOKUP, "LOOKUP"},
276 {DEVFSD_NOTIFY_CHANGE, "CHANGE"},
277 {DEVFSD_NOTIFY_CREATE, "CREATE"},
278 {DEVFSD_NOTIFY_DELETE, "DELETE"},
282 /* Busybox messages */
284 static const char * const bb_msg_proto_rev = "protocol revision";
285 static const char * const bb_msg_bad_config = "bad %s config file: %s";
286 static const char * const bb_msg_small_buffer = "buffer too small";
287 static const char * const bb_msg_variable_not_found = "variable: %s not found";
289 /* Busybox functions */
290 static void msg_logger(int pri, const char * fmt, ...)
296 ret = access("/dev/log", F_OK);
298 openlog(applet_name, 0, LOG_DAEMON);
299 vsyslog(pri , fmt, ap);
300 /* Man: A trailing newline is added when needed. */
303 /* ENABLE_DEVFSD_VERBOSE is always enabled if msg_logger is used */
304 if ((ENABLE_DEVFSD_VERBOSE && ret) || ENABLE_DEBUG) {
305 bb_error_msg(fmt, ap);
310 static void msg_logger_and_die(int pri, const char* fmt, ...)
315 msg_logger(pri, fmt, ap);
321 #if defined(CONFIG_DEVFSD_VERBOSE) || defined(CONFIG_DEBUG)
322 #define devfsd_error_msg(fmt, args...) bb_error_msg(fmt, ## args)
323 #define devfsd_perror_msg_and_die(fmt, args...) bb_perror_msg_and_die(fmt, ## args)
324 #define devfsd_error_msg_and_die(fmt, args...) bb_error_msg_and_die(fmt, ## args)
326 #define msg_logger(p, fmt, args...)
327 #define msg_logger_and_die(p, fmt, args...) exit(1)
328 #define devfsd_perror_msg_and_die(fmt, args...) exit(1)
329 #define devfsd_error_msg_and_die(fmt, args...) exit(1)
330 #define devfsd_error_msg(fmt, args...)
333 static void do_ioctl_and_die(int fd, int request, unsigned long event_mask_flag)
335 if (ioctl(fd, request, event_mask_flag) == -1)
336 msg_logger_and_die(LOG_ERR, "ioctl");
339 static void fork_and_execute(int die, char *arg0, char **arg)
346 /* Parent: Error : die or return */
347 msg_logger(LOG_ERR,(char *)bb_msg_memory_exhausted);
352 /* Parent : ok : return or exit */
359 /* Child : if arg0 != NULL do execvp */
361 BB_EXECVP(arg0, arg);
362 msg_logger_and_die(LOG_ERR, "execvp");
366 static void safe_memcpy(char *dest, const char *src, int len)
368 memcpy(dest , src, len);
372 static unsigned int scan_dev_name_common(const char *d, unsigned int n, int addendum, const char *ptr)
374 if (d[n - 4] == 'd' && d[n - 3] == 'i' && d[n - 2] == 's' && d[n - 1] == 'c')
376 if (d[n - 2] == 'c' && d[n - 1] == 'd')
378 if (ptr[0] == 'p' && ptr[1] == 'a' && ptr[2] == 'r' && ptr[3] == 't')
380 if (ptr[n - 2] == 'm' && ptr[n - 1] == 't')
385 static unsigned int scan_dev_name(const char *d, unsigned int n, const char *ptr)
387 if (d[0] == 's' && d[1] == 'c' && d[2] == 's' && d[3] == 'i' && d[4] == '/') {
388 if (d[n - 7] == 'g' && d[n - 6] == 'e' && d[n - 5] == 'n'
389 && d[n - 4] == 'e' && d[n - 3] == 'r' && d[n - 2] == 'i' && d[n - 1] == 'c'
392 return scan_dev_name_common(d, n, 0, ptr);
394 if (d[0] == 'i' && d[1] == 'd' && d[2] == 'e' && d[3] == '/'
395 && d[4] == 'h' && d[5] == 'o' && d[6] == 's' && d[7] == 't'
397 return scan_dev_name_common(d, n, 4, ptr);
398 if (d[0] == 's' && d[1] == 'b' && d[2] == 'p' && d[3] == '/')
400 if (d[0] == 'v' && d[1] == 'c' && d[2] == 'c' && d[3] == '/')
402 if (d[0] == 'p' && d[1] == 't' && d[2] == 'y' && d[3] == '/')
407 /* Public functions follow */
409 int devfsd_main(int argc, char **argv);
410 int devfsd_main(int argc, char **argv)
412 int print_version = FALSE;
413 int do_daemon = TRUE;
414 int no_polling = FALSE;
416 int fd, proto_rev, count;
417 unsigned long event_mask = 0;
418 struct sigaction new_action;
419 struct initial_symlink_struct *curr;
424 for (count = 2; count < argc; ++count) {
425 if (argv[count][0] == '-') {
426 if (argv[count][1] == 'v' && !argv[count][2]) /* -v */
427 print_version = TRUE;
428 else if (ENABLE_DEVFSD_FG_NP && argv[count][1] == 'f'
429 && argv[count][2] == 'g' && !argv[count][3]) /* -fg */
431 else if (ENABLE_DEVFSD_FG_NP && argv[count][1] == 'n'
432 && argv[count][2] == 'p' && !argv[count][3]) /* -np */
439 /* strip last / from mount point, so we don't need to check for it later */
440 while (argv[1][1] != '\0' && argv[1][strlen(argv[1]) - 1] == '/')
441 argv[1][strlen(argv[1]) - 1] = '\0';
443 mount_point = argv[1];
447 fd = xopen(".devfsd", O_RDONLY);
449 if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0)
450 devfsd_perror_msg_and_die("FD_CLOEXEC");
452 if (ioctl(fd, DEVFSDIOC_GET_PROTO_REV, &proto_rev) == -1)
453 msg_logger_and_die(LOG_ERR, "ioctl");
455 /*setup initial entries */
456 for (curr = initial_symlinks; curr->dest != NULL; ++curr)
457 symlink(curr->dest, curr->name);
459 /* NB: The check for CONFIG_FILE is done in read_config_file() */
461 if (print_version ||(DEVFSD_PROTOCOL_REVISION_DAEMON != proto_rev)) {
462 printf("%s v%s\nDaemon %s:\t%d\nKernel-side %s:\t%d\n",
463 applet_name, DEVFSD_VERSION, bb_msg_proto_rev,
464 DEVFSD_PROTOCOL_REVISION_DAEMON,bb_msg_proto_rev, proto_rev);
465 if (DEVFSD_PROTOCOL_REVISION_DAEMON != proto_rev)
466 bb_error_msg_and_die("%s mismatch!", bb_msg_proto_rev);
467 exit(EXIT_SUCCESS); /* -v */
469 /* Tell kernel we are special(i.e. we get to see hidden entries) */
470 do_ioctl_and_die(fd, DEVFSDIOC_SET_EVENT_MASK, 0);
472 sigemptyset(&new_action.sa_mask);
473 new_action.sa_flags = 0;
475 /* Set up SIGHUP and SIGUSR1 handlers */
476 new_action.sa_handler = signal_handler;
477 if (sigaction(SIGHUP, &new_action, NULL) != 0 || sigaction(SIGUSR1, &new_action, NULL) != 0)
478 devfsd_error_msg_and_die("sigaction");
480 printf("%s v%s started for %s\n",applet_name, DEVFSD_VERSION, mount_point);
482 /* Set umask so that mknod(2), open(2) and mkdir(2) have complete control over permissions */
484 read_config_file((char*)CONFIG_FILE, FALSE, &event_mask);
485 /* Do the scan before forking, so that boot scripts see the finished product */
486 dir_operation(SERVICE, mount_point, 0, NULL);
488 if (ENABLE_DEVFSD_FG_NP && no_polling)
491 /* Release so that the child can grab it */
492 do_ioctl_and_die(fd, DEVFSDIOC_RELEASE_EVENT_QUEUE, 0);
493 fork_and_execute(DIE, NULL, NULL);
494 setsid(); /* Prevent hangups and become pgrp leader */
495 } else if (ENABLE_DEVFSD_FG_NP) {
496 setpgid(0, 0); /* Become process group leader */
500 do_scan = do_servicing(fd, event_mask);
503 read_config_file((char*)CONFIG_FILE, FALSE, &event_mask);
505 dir_operation(SERVICE, mount_point, 0, NULL);
507 } /* End Function main */
510 /* Private functions follow */
512 static void read_config_file(char *path, int optional, unsigned long *event_mask)
513 /* [SUMMARY] Read a configuration database.
514 <path> The path to read the database from. If this is a directory, all
515 entries in that directory will be read(except hidden entries).
516 <optional> If TRUE, the routine will silently ignore a missing config file.
517 <event_mask> The event mask is written here. This is not initialised.
523 char buf[STRING_LENGTH];
526 if (stat(path, &statbuf) == 0) {
527 /* Don't read 0 length files: ignored */
528 /*if (statbuf.st_size == 0)
530 if (S_ISDIR(statbuf.st_mode)) {
531 /* strip last / from dirname so we don't need to check for it later */
532 while (path && path[1] != '\0' && path[strlen(path) - 1] == '/')
533 path[strlen(path) - 1] = '\0';
535 dir_operation(READ_CONFIG, path, 0, event_mask);
538 if ((fp = fopen(path, "r")) != NULL) {
539 while (fgets(buf, STRING_LENGTH, fp) != NULL) {
540 /* Skip whitespace */
541 for (line = buf; isspace(*line); ++line)
543 if (line[0] == '\0' || line[0] == '#')
545 process_config_line(line, event_mask);
549 goto read_config_file_err;
552 read_config_file_err:
553 if (optional == 0 && errno == ENOENT)
554 msg_logger_and_die(LOG_ERR, "read config file: %s: %m", path);
556 } /* End Function read_config_file */
558 static void process_config_line(const char *line, unsigned long *event_mask)
559 /* [SUMMARY] Process a line from a configuration file.
560 <line> The configuration line.
561 <event_mask> The event mask is written here. This is not initialised.
566 struct config_entry_struct *new;
567 char p[MAX_ARGS][STRING_LENGTH];
568 char when[STRING_LENGTH], what[STRING_LENGTH];
569 char name[STRING_LENGTH];
570 const char *msg = "";
574 /* !!!! Only Uppercase Keywords in devsfd.conf */
575 static const char *const options[] = {
576 "CLEAR_CONFIG", "INCLUDE", "OPTIONAL_INCLUDE",
577 "RESTORE", "PERMISSIONS", "MODLOAD", "EXECUTE",
578 "COPY", "IGNORE", "MKOLDCOMPAT", "MKNEWCOMPAT",
579 "RMOLDCOMPAT", "RMNEWCOMPAT", 0
582 for (count = 0; count < MAX_ARGS; ++count)
584 num_args = sscanf(line, "%s %s %s %s %s %s %s %s %s %s",
586 p[0], p[1], p[2], p[3], p[4], p[5], p[6]);
588 i = index_in_str_array(options, when);
598 goto process_config_line_err;
600 /* "INCLUDE" & "OPTIONAL_INCLUDE" */
601 if (i == 1 || i == 2) {
602 st_expr_expand(name, STRING_LENGTH, name, get_variable, NULL);
603 msg_logger(LOG_INFO, "%sinclude: %s", (toupper(when[0]) == 'I') ? "": "optional_", name);
604 read_config_file(name, (toupper(when[0]) == 'I') ? FALSE : TRUE, event_mask);
609 dir_operation(RESTORE, name, strlen(name),NULL);
613 goto process_config_line_err;
615 new = xzalloc(sizeof *new);
617 for (count = 0; event_types[count].config_name != NULL; ++count) {
618 if (strcasecmp(when, event_types[count].config_name) != 0)
620 new->action.when = event_types[count].type;
623 if (event_types[count].config_name == NULL) {
625 goto process_config_line_err;
628 i = index_in_str_array(options, what);
631 case 4: /* "PERMISSIONS" */
632 new->action.what = AC_PERMISSIONS;
633 /* Get user and group */
634 if ((ptr = strchr(p[0], '.')) == NULL) {
636 goto process_config_line_err; /*"missing '.' in UID.GID"*/
640 new->u.permissions.uid = get_uid_gid(UID, p[0]);
641 new->u.permissions.gid = get_uid_gid(GID, ptr);
643 new->u.permissions.mode = get_mode(p[1]);
645 case 5: /* MODLOAD */
646 /*This action will pass "/dev/$devname"(i.e. "/dev/" prefixed to
647 the device name) to the module loading facility. In addition,
648 the /etc/modules.devfs configuration file is used.*/
649 if (ENABLE_DEVFSD_MODLOAD)
650 new->action.what = AC_MODLOAD;
652 case 6: /* EXECUTE */
653 new->action.what = AC_EXECUTE;
656 for (count = 0; count < num_args; ++count)
657 new->u.execute.argv[count] = xstrdup(p[count]);
659 new->u.execute.argv[num_args] = NULL;
662 new->action.what = AC_COPY;
665 goto process_config_line_err; /* missing path and function in line */
667 new->u.copy.source = xstrdup(p[0]);
668 new->u.copy.destination = xstrdup(p[1]);
672 case 9: /* MKOLDCOMPAT */
674 case 10: /* MKNEWCOMPAT */
676 case 11:/* RMOLDCOMPAT */
678 case 12: /* RMNEWCOMPAT */
684 new->action.what = i - 2;
688 goto process_config_line_err;
692 xregcomp(&new->preg, name, REG_EXTENDED);
694 *event_mask |= 1 << new->action.when;
696 if (first_config == NULL)
699 last_config->next = new;
702 process_config_line_err:
703 msg_logger_and_die(LOG_ERR, bb_msg_bad_config, msg , line);
704 } /* End Function process_config_line */
706 static int do_servicing(int fd, unsigned long event_mask)
707 /* [SUMMARY] Service devfs changes until a signal is received.
708 <fd> The open control file.
709 <event_mask> The event mask.
710 [RETURNS] TRUE if SIGHUP was caught, else FALSE.
714 struct devfsd_notify_struct info;
715 unsigned long tmp_event_mask;
717 /* Tell devfs what events we care about */
718 tmp_event_mask = event_mask;
719 do_ioctl_and_die(fd, DEVFSDIOC_SET_EVENT_MASK, tmp_event_mask);
720 while (!caught_signal) {
722 bytes = read(fd,(char *) &info, sizeof info);
724 break; /* Must test for this first */
726 continue; /* Yes, the order is important */
732 int c_sighup = caught_sighup;
734 caught_signal = FALSE;
735 caught_sighup = FALSE;
738 msg_logger_and_die(LOG_ERR, "read error on control file");
739 } /* End Function do_servicing */
741 static void service_name(const struct devfsd_notify_struct *info)
742 /* [SUMMARY] Service a single devfs change.
743 <info> The devfs change.
748 regmatch_t mbuf[MAX_SUBEXPR];
749 struct config_entry_struct *entry;
751 if (ENABLE_DEBUG && info->overrun_count > 0)
752 msg_logger(LOG_ERR, "lost %u events", info->overrun_count);
754 /* Discard lookups on "/dev/log" and "/dev/initctl" */
755 if (info->type == DEVFSD_NOTIFY_LOOKUP
756 && ((info->devname[0] == 'l' && info->devname[1] == 'o'
757 && info->devname[2] == 'g' && !info->devname[3])
758 || (info->devname[0] == 'i' && info->devname[1] == 'n'
759 && info->devname[2] == 'i' && info->devname[3] == 't'
760 && info->devname[4] == 'c' && info->devname[5] == 't'
761 && info->devname[6] == 'l' && !info->devname[7]))
765 for (entry = first_config; entry != NULL; entry = entry->next) {
766 /* First check if action matches the type, then check if name matches */
767 if (info->type != entry->action.when
768 || regexec(&entry->preg, info->devname, MAX_SUBEXPR, mbuf, 0) != 0)
770 for (n = 0;(n < MAX_SUBEXPR) && (mbuf[n].rm_so != -1); ++n)
773 switch (entry->action.what) {
775 action_permissions(info, entry);
778 if (ENABLE_DEVFSD_MODLOAD)
779 action_modload(info, entry);
782 action_execute(info, entry, mbuf, n);
785 action_copy(info, entry, mbuf, n);
794 action_compat(info, entry->action.what);
797 msg_logger_and_die(LOG_ERR, "Unknown action");
800 } /* End Function service_name */
802 static void action_permissions(const struct devfsd_notify_struct *info,
803 const struct config_entry_struct *entry)
804 /* [SUMMARY] Update permissions for a device entry.
805 <info> The devfs change.
806 <entry> The config file entry.
812 if (stat(info->devname, &statbuf) != 0 ||
813 chmod(info->devname,(statbuf.st_mode & S_IFMT) |(entry->u.permissions.mode & ~S_IFMT)) != 0 ||
814 chown(info->devname, entry->u.permissions.uid, entry->u.permissions.gid) != 0
816 msg_logger(LOG_ERR, "Can't chmod or chown: %s: %m", info->devname);
817 } /* End Function action_permissions */
819 static void action_modload(const struct devfsd_notify_struct *info,
820 const struct config_entry_struct *entry ATTRIBUTE_UNUSED)
821 /* [SUMMARY] Load a module.
822 <info> The devfs change.
823 <entry> The config file entry.
829 argv[0] =(char*)MODPROBE;
830 argv[1] =(char*)MODPROBE_SWITCH_1; /* "-k" */
831 argv[2] =(char*)MODPROBE_SWITCH_2; /* "-C" */
832 argv[3] =(char*)CONFIG_MODULES_DEVFS;
833 argv[4] = concat_path_file("/dev", info->devname); /* device */
836 fork_and_execute(DIE, argv[0], argv);
838 } /* End Function action_modload */
840 static void action_execute(const struct devfsd_notify_struct *info,
841 const struct config_entry_struct *entry,
842 const regmatch_t *regexpr, unsigned int numexpr)
843 /* [SUMMARY] Execute a programme.
844 <info> The devfs change.
845 <entry> The config file entry.
846 <regexpr> The number of subexpression(start, end) offsets within the
848 <numexpr> The number of elements within <<regexpr>>.
853 struct get_variable_info gv_info;
854 char *argv[MAX_ARGS + 1];
855 char largv[MAX_ARGS + 1][STRING_LENGTH];
858 gv_info.devname = info->devname;
859 snprintf(gv_info.devpath, sizeof(gv_info.devpath), "%s/%s", mount_point, info->devname);
860 for (count = 0; entry->u.execute.argv[count] != NULL; ++count) {
861 expand_expression(largv[count], STRING_LENGTH,
862 entry->u.execute.argv[count],
863 get_variable, &gv_info,
864 gv_info.devname, regexpr, numexpr);
865 argv[count] = largv[count];
868 fork_and_execute(NO_DIE, argv[0], argv);
869 } /* End Function action_execute */
872 static void action_copy(const struct devfsd_notify_struct *info,
873 const struct config_entry_struct *entry,
874 const regmatch_t *regexpr, unsigned int numexpr)
875 /* [SUMMARY] Copy permissions.
876 <info> The devfs change.
877 <entry> The config file entry.
878 <regexpr> This list of subexpression(start, end) offsets within the
880 <numexpr> The number of elements in <<regexpr>>.
885 struct get_variable_info gv_info;
886 struct stat source_stat, dest_stat;
887 char source[STRING_LENGTH], destination[STRING_LENGTH];
890 dest_stat.st_mode = 0;
892 if ((info->type == DEVFSD_NOTIFY_CHANGE) && S_ISLNK(info->mode))
895 gv_info.devname = info->devname;
897 snprintf(gv_info.devpath, sizeof(gv_info.devpath), "%s/%s", mount_point, info->devname);
898 expand_expression(source, STRING_LENGTH, entry->u.copy.source,
899 get_variable, &gv_info, gv_info.devname,
902 expand_expression(destination, STRING_LENGTH, entry->u.copy.destination,
903 get_variable, &gv_info, gv_info.devname,
906 if (!make_dir_tree(destination) || lstat(source, &source_stat) != 0)
908 lstat(destination, &dest_stat);
909 new_mode = source_stat.st_mode & ~S_ISVTX;
910 if (info->type == DEVFSD_NOTIFY_CREATE)
912 else if ((info->type == DEVFSD_NOTIFY_CHANGE) &&(dest_stat.st_mode & S_ISVTX))
914 ret = copy_inode(destination, &dest_stat, new_mode, source, &source_stat);
915 if (ENABLE_DEBUG && ret && (errno != EEXIST))
916 msg_logger(LOG_ERR, "copy_inode: %s to %s: %m", source, destination);
917 } /* End Function action_copy */
919 static void action_compat(const struct devfsd_notify_struct *info, unsigned int action)
920 /* [SUMMARY] Process a compatibility request.
921 <info> The devfs change.
922 <action> The action to take.
927 const char *compat_name = NULL;
928 const char *dest_name = info->devname;
930 char compat_buf[STRING_LENGTH], dest_buf[STRING_LENGTH];
931 int mode, host, bus, target, lun;
934 /* 1 to 5 "scsi/" , 6 to 9 "ide/host" */
935 static const char *const fmt[] = {
937 "sg/c%db%dt%du%d", /* scsi/generic */
938 "sd/c%db%dt%du%d", /* scsi/disc */
939 "sr/c%db%dt%du%d", /* scsi/cd */
940 "sd/c%db%dt%du%dp%d", /* scsi/part */
941 "st/c%db%dt%du%dm%d%c", /* scsi/mt */
942 "ide/hd/c%db%dt%du%d", /* ide/host/disc */
943 "ide/cd/c%db%dt%du%d", /* ide/host/cd */
944 "ide/hd/c%db%dt%du%dp%d", /* ide/host/part */
945 "ide/mt/c%db%dt%du%d%s", /* ide/host/mt */
949 /* First construct compatibility name */
953 compat_name = get_old_name(info->devname, info->namelen, compat_buf, info->major, info->minor);
957 ptr = bb_basename(info->devname);
958 i = scan_dev_name(info->devname, info->namelen, ptr);
964 sscanf(info->devname + ((i < 6) ? 5 : 4), "host%d/bus%d/target%d/lun%d/", &host, &bus, &target, &lun);
965 snprintf(dest_buf, sizeof(dest_buf), "../%s", info->devname + (( i > 5) ? 4 : 0));
966 dest_name = dest_buf;
967 compat_name = compat_buf;
970 /* 1 == scsi/generic 2 == scsi/disc 3 == scsi/cd 6 == ide/host/disc 7 == ide/host/cd */
971 if (i == 1 || i == 2 || i == 3 || i == 6 || i ==7)
972 sprintf(compat_buf, fmt[i], host, bus, target, lun);
974 /* 4 == scsi/part 8 == ide/host/part */
975 if (i == 4 || i == 8)
976 sprintf(compat_buf, fmt[i], host, bus, target, lun, atoi(ptr + 4));
980 rewind_ = info->devname[info->namelen - 1];
984 if (ptr[2] == 'l' /*108*/ || ptr[2] == 'm'/*109*/)
985 mode = ptr[2] - 107; /* 1 or 2 */
988 sprintf(compat_buf, fmt[i], host, bus, target, lun, mode, rewind_);
991 /* 9 == ide/host/mt */
993 snprintf(compat_buf, sizeof(compat_buf), fmt[i], host, bus, target, lun, ptr + 2);
995 } /* switch (action) */
997 if (compat_name == NULL)
1000 /* Now decide what to do with it */
1002 case AC_MKOLDCOMPAT:
1003 case AC_MKNEWCOMPAT:
1004 mksymlink(dest_name, compat_name);
1006 case AC_RMOLDCOMPAT:
1007 case AC_RMNEWCOMPAT:
1008 ret = unlink(compat_name);
1009 if (ENABLE_DEBUG && ret)
1010 msg_logger(LOG_ERR, "unlink: %s: %m", compat_name);
1013 } /* switch (action) */
1014 } /* End Function action_compat */
1016 static void restore(char *spath, struct stat source_stat, int rootlen)
1019 struct stat dest_stat;
1021 dest_stat.st_mode = 0;
1022 dpath = concat_path_file(mount_point, spath + rootlen);
1023 lstat(dpath, &dest_stat);
1025 if (S_ISLNK(source_stat.st_mode) ||(source_stat.st_mode & S_ISVTX))
1026 copy_inode(dpath, &dest_stat,(source_stat.st_mode & ~S_ISVTX) , spath, &source_stat);
1028 if (S_ISDIR(source_stat.st_mode))
1029 dir_operation(RESTORE, spath, rootlen,NULL);
1033 static int copy_inode(const char *destpath, const struct stat *dest_stat,
1035 const char *sourcepath, const struct stat *source_stat)
1036 /* [SUMMARY] Copy an inode.
1037 <destpath> The destination path. An existing inode may be deleted.
1038 <dest_stat> The destination stat(2) information.
1039 <new_mode> The desired new mode for the destination.
1040 <sourcepath> The source path.
1041 <source_stat> The source stat(2) information.
1042 [RETURNS] TRUE on success, else FALSE.
1045 int source_len, dest_len;
1046 char source_link[STRING_LENGTH], dest_link[STRING_LENGTH];
1048 struct sockaddr_un un_addr;
1049 char symlink_val[STRING_LENGTH];
1051 if ((source_stat->st_mode & S_IFMT) ==(dest_stat->st_mode & S_IFMT)) {
1053 if (S_ISLNK(source_stat->st_mode)) {
1054 if ((source_len = readlink(sourcepath, source_link, STRING_LENGTH - 1)) < 0
1055 || (dest_len = readlink(destpath , dest_link , STRING_LENGTH - 1)) < 0
1058 source_link[source_len] = '\0';
1059 dest_link[dest_len] = '\0';
1060 if ((source_len != dest_len) || (strcmp(source_link, dest_link) != 0)) {
1062 symlink(source_link, destpath);
1065 } /* Else not a symlink */
1066 chmod(destpath, new_mode & ~S_IFMT);
1067 chown(destpath, source_stat->st_uid, source_stat->st_gid);
1070 /* Different types: unlink and create */
1072 switch (source_stat->st_mode & S_IFMT) {
1074 if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0)
1076 un_addr.sun_family = AF_UNIX;
1077 snprintf(un_addr.sun_path, sizeof(un_addr.sun_path), "%s", destpath);
1078 val = bind(fd,(struct sockaddr *) &un_addr,(int) sizeof un_addr);
1080 if (val != 0 || chmod(destpath, new_mode & ~S_IFMT) != 0)
1084 if ((val = readlink(sourcepath, symlink_val, STRING_LENGTH - 1)) < 0)
1086 symlink_val[val] = '\0';
1087 if (symlink(symlink_val, destpath) == 0)
1091 if ((fd = open(destpath, O_RDONLY | O_CREAT, new_mode & ~S_IFMT)) < 0)
1094 if (chmod(destpath, new_mode & ~S_IFMT) != 0)
1100 if (mknod(destpath, new_mode, source_stat->st_rdev) != 0)
1104 if (mkdir(destpath, new_mode & ~S_IFMT) != 0)
1107 if (chown(destpath, source_stat->st_uid, source_stat->st_gid) == 0)
1112 } /* End Function copy_inode */
1114 static void free_config(void)
1115 /* [SUMMARY] Free the configuration information.
1119 struct config_entry_struct *c_entry;
1122 for (c_entry = first_config; c_entry != NULL; c_entry = next) {
1125 next = c_entry->next;
1126 regfree(&c_entry->preg);
1127 if (c_entry->action.what == AC_EXECUTE) {
1128 for (count = 0; count < MAX_ARGS; ++count) {
1129 if (c_entry->u.execute.argv[count] == NULL)
1131 free(c_entry->u.execute.argv[count]);
1136 first_config = NULL;
1138 } /* End Function free_config */
1140 static int get_uid_gid(int flag, const char *string)
1141 /* [SUMMARY] Convert a string to a UID or GID value.
1142 <flag> "UID" or "GID".
1143 <string> The string.
1144 [RETURNS] The UID or GID value.
1147 struct passwd *pw_ent;
1148 struct group *grp_ent;
1149 static const char *msg;
1151 if (ENABLE_DEVFSD_VERBOSE)
1154 if (isdigit(string[0]) ||((string[0] == '-') && isdigit(string[1])))
1155 return atoi(string);
1157 if (flag == UID && (pw_ent = getpwnam(string)) != NULL)
1158 return pw_ent->pw_uid;
1160 if (flag == GID && (grp_ent = getgrnam(string)) != NULL)
1161 return grp_ent->gr_gid;
1162 else if (ENABLE_DEVFSD_VERBOSE)
1165 if (ENABLE_DEVFSD_VERBOSE)
1166 msg_logger(LOG_ERR,"unknown %s: %s, defaulting to %cid=0", msg, string, msg[0]);
1168 }/* End Function get_uid_gid */
1170 static mode_t get_mode(const char *string)
1171 /* [SUMMARY] Convert a string to a mode value.
1172 <string> The string.
1173 [RETURNS] The mode value.
1179 if (isdigit(string[0]))
1180 return strtoul(string, NULL, 8);
1181 if (strlen(string) != 9)
1182 msg_logger_and_die(LOG_ERR, "bad mode: %s", string);
1187 if (string[0] == 'r' || string[0] == 'w' || string[0] == 'x')
1193 } /* End Function get_mode */
1195 static void signal_handler(int sig)
1197 caught_signal = TRUE;
1199 caught_sighup = TRUE;
1201 msg_logger(LOG_INFO, "Caught signal %d", sig);
1202 } /* End Function signal_handler */
1204 static const char *get_variable(const char *variable, void *info)
1206 struct get_variable_info *gv_info = info;
1207 static char hostname[STRING_LENGTH], sbuf[STRING_LENGTH];
1208 const char *field_names[] = { "hostname", "mntpt", "devpath", "devname",
1209 "uid", "gid", "mode", hostname, mount_point,
1210 gv_info->devpath, gv_info->devname, 0 };
1213 if (gethostname(hostname, STRING_LENGTH - 1) != 0)
1214 msg_logger_and_die(LOG_ERR, "gethostname: %m");
1216 /* Here on error we should do exit(RV_SYS_ERROR), instead we do exit(EXIT_FAILURE) */
1217 hostname[STRING_LENGTH - 1] = '\0';
1219 /* index_in_str_array returns i>=0 */
1220 i = index_in_str_array(field_names, variable);
1222 if (i > 6 || i < 0 || (i > 1 && gv_info == NULL))
1224 if (i >= 0 && i <= 3) {
1225 return field_names[i + 7];
1229 sprintf(sbuf, "%u", gv_info->info->uid);
1231 sprintf(sbuf, "%u", gv_info->info->gid);
1233 sprintf(sbuf, "%o", gv_info->info->mode);
1235 } /* End Function get_variable */
1237 static void service(struct stat statbuf, char *path)
1239 struct devfsd_notify_struct info;
1241 memset(&info, 0, sizeof info);
1242 info.type = DEVFSD_NOTIFY_REGISTERED;
1243 info.mode = statbuf.st_mode;
1244 info.major = major(statbuf.st_rdev);
1245 info.minor = minor(statbuf.st_rdev);
1246 info.uid = statbuf.st_uid;
1247 info.gid = statbuf.st_gid;
1248 snprintf(info.devname, sizeof(info.devname), "%s", path + strlen(mount_point) + 1);
1249 info.namelen = strlen(info.devname);
1250 service_name(&info);
1251 if (S_ISDIR(statbuf.st_mode))
1252 dir_operation(SERVICE, path, 0, NULL);
1255 static void dir_operation(int type, const char * dir_name, int var, unsigned long *event_mask)
1256 /* [SUMMARY] Scan a directory tree and generate register events on leaf nodes.
1257 <flag> To choose which function to perform
1258 <dp> The directory pointer. This is closed upon completion.
1259 <dir_name> The name of the directory.
1260 <rootlen> string length parameter.
1264 struct stat statbuf;
1269 if ((dp = warn_opendir(dir_name)) == NULL)
1272 while ((de = readdir(dp)) != NULL) {
1274 if (de->d_name && DOT_OR_DOTDOT(de->d_name))
1276 path = concat_path_file(dir_name, de->d_name);
1277 if (lstat(path, &statbuf) == 0) {
1280 service(statbuf, path);
1283 restore(path, statbuf, var);
1286 read_config_file(path, var, event_mask);
1293 } /* End Function do_scan_and_service */
1295 static int mksymlink(const char *oldpath, const char *newpath)
1296 /* [SUMMARY] Create a symlink, creating intervening directories as required.
1297 <oldpath> The string contained in the symlink.
1298 <newpath> The name of the new symlink.
1299 [RETURNS] 0 on success, else -1.
1302 if (!make_dir_tree(newpath))
1305 if (symlink(oldpath, newpath) != 0) {
1306 if (errno != EEXIST)
1310 } /* End Function mksymlink */
1313 static int make_dir_tree(const char *path)
1314 /* [SUMMARY] Creating intervening directories for a path as required.
1315 <path> The full pathname(including the leaf node).
1316 [RETURNS] TRUE on success, else FALSE.
1319 if (bb_make_directory(dirname((char *)path), -1, FILEUTILS_RECUR) == -1)
1322 } /* End Function make_dir_tree */
1324 static int expand_expression(char *output, unsigned int outsize,
1326 const char *(*get_variable_func)(const char *variable, void *info),
1328 const char *devname,
1329 const regmatch_t *ex, unsigned int numexp)
1330 /* [SUMMARY] Expand environment variables and regular subexpressions in string.
1331 <output> The output expanded expression is written here.
1332 <length> The size of the output buffer.
1333 <input> The input expression. This may equal <<output>>.
1334 <get_variable> A function which will be used to get variable values. If
1335 this returns NULL, the environment is searched instead. If this is NULL,
1336 only the environment is searched.
1337 <info> An arbitrary pointer passed to <<get_variable>>.
1338 <devname> Device name; specifically, this is the string that contains all
1339 of the regular subexpressions.
1340 <ex> Array of start / end offsets into info->devname for each subexpression
1341 <numexp> Number of regular subexpressions found in <<devname>>.
1342 [RETURNS] TRUE on success, else FALSE.
1345 char temp[STRING_LENGTH];
1347 if (!st_expr_expand(temp, STRING_LENGTH, input, get_variable_func, info))
1349 expand_regexp(output, outsize, temp, devname, ex, numexp);
1351 } /* End Function expand_expression */
1353 static void expand_regexp(char *output, size_t outsize, const char *input,
1354 const char *devname,
1355 const regmatch_t *ex, unsigned int numex)
1356 /* [SUMMARY] Expand all occurrences of the regular subexpressions \0 to \9.
1357 <output> The output expanded expression is written here.
1358 <outsize> The size of the output buffer.
1359 <input> The input expression. This may NOT equal <<output>>, because
1360 supporting that would require yet another string-copy. However, it's not
1361 hard to write a simple wrapper function to add this functionality for those
1362 few cases that need it.
1363 <devname> Device name; specifically, this is the string that contains all
1364 of the regular subexpressions.
1365 <ex> An array of start and end offsets into <<devname>>, one for each
1367 <numex> Number of subexpressions in the offset-array <<ex>>.
1371 const char last_exp = '0' - 1 + numex;
1374 /* Guarantee NULL termination by writing an explicit '\0' character into
1375 the very last byte */
1377 output[--outsize] = '\0';
1378 /* Copy the input string into the output buffer, replacing '\\' with '\'
1379 and '\0' .. '\9' with subexpressions 0 .. 9, if they exist. Other \x
1380 codes are deleted */
1381 while ((c != '\0') && (outsize != 0)) {
1388 if ((c >= '0') && (c <= last_exp)) {
1389 const regmatch_t *subexp = ex + (c - '0');
1390 unsigned int sublen = subexp->rm_eo - subexp->rm_so;
1392 /* Range checking */
1393 if (sublen > outsize)
1395 strncpy(output, devname + subexp->rm_so, sublen);
1406 } /* End Function expand_regexp */
1409 /* from compat_name.c */
1411 struct translate_struct
1413 const char *match; /* The string to match to(up to length) */
1414 const char *format; /* Format of output, "%s" takes data past match string,
1415 NULL is effectively "%s"(just more efficient) */
1418 static struct translate_struct translate_table[] =
1421 {"printers/", "lp%s"},
1423 {"parports/", "parport%s"},
1426 {"loop/", "loop%s"},
1427 {"floppy/", "fd%s"},
1429 {"md/", "md%s"}, /* Meta-devices */
1433 {"pg/", "pg%s"}, /* Parallel port generic ATAPI interface*/
1435 {"staliomem/", "staliomem%s"}, /* Stallion serial driver control */
1436 {"tts/E", "ttyE%s"}, /* Stallion serial driver */
1437 {"cua/E", "cue%s"}, /* Stallion serial driver callout */
1438 {"tts/R", "ttyR%s"}, /* Rocketport serial driver */
1439 {"cua/R", "cur%s"}, /* Rocketport serial driver callout */
1440 {"ip2/", "ip2%s"}, /* Computone serial driver control */
1441 {"tts/F", "ttyF%s"}, /* Computone serial driver */
1442 {"cua/F", "cuf%s"}, /* Computone serial driver callout */
1443 {"tts/C", "ttyC%s"}, /* Cyclades serial driver */
1444 {"cua/C", "cub%s"}, /* Cyclades serial driver callout */
1445 {"tts/", "ttyS%s"}, /* Generic serial: must be after others */
1446 {"cua/", "cua%s"}, /* Generic serial: must be after others */
1447 {"input/js", "js%s"}, /* Joystick driver */
1451 const char *get_old_name(const char *devname, unsigned int namelen,
1452 char *buffer, unsigned int major, unsigned int minor)
1453 /* [SUMMARY] Translate a kernel-supplied name into an old name.
1454 <devname> The device name provided by the kernel.
1455 <namelen> The length of the name.
1456 <buffer> A buffer that may be used. This should be at least 128 bytes long.
1457 <major> The major number for the device.
1458 <minor> The minor number for the device.
1459 [RETURNS] A pointer to the old name if known, else NULL.
1462 const char *compat_name = NULL;
1464 struct translate_struct *trans;
1471 /* 1 to 5 "scsi/" , 6 to 9 "ide/host", 10 sbp/, 11 vcc/, 12 pty/ */
1472 static const char *const fmt[] = {
1474 "sg%u", /* scsi/generic */
1475 NULL, /* scsi/disc */
1476 "sr%u", /* scsi/cd */
1477 NULL, /* scsi/part */
1478 "nst%u%c", /* scsi/mt */
1479 "hd%c" , /* ide/host/disc */
1480 "hd%c" , /* ide/host/cd */
1481 "hd%c%s", /* ide/host/part */
1482 "%sht%d", /* ide/host/mt */
1483 "sbpcd%u", /* sbp/ */
1485 "%cty%c%c", /* pty/ */
1489 for (trans = translate_table; trans->match != NULL; ++trans) {
1490 len = strlen(trans->match);
1492 if (strncmp(devname, trans->match, len) == 0) {
1493 if (trans->format == NULL)
1494 return devname + len;
1495 sprintf(buffer, trans->format, devname + len);
1500 ptr = bb_basename(devname);
1501 i = scan_dev_name(devname, namelen, ptr);
1503 if (i > 0 && i < 13)
1504 compat_name = buffer;
1508 /* 1 == scsi/generic, 3 == scsi/cd, 10 == sbp/ */
1509 if (i == 1 || i == 3 || i == 10)
1510 sprintf(buffer, fmt[i], minor);
1512 /* 2 ==scsi/disc, 4 == scsi/part */
1513 if (i == 2 || i == 4)
1514 compat_name = write_old_sd_name(buffer, major, minor,((i == 2) ? "" : (ptr + 4)));
1521 sprintf(buffer, fmt[i], minor & 0x1f, mode);
1522 if (devname[namelen - 1] != 'n')
1525 /* 6 == ide/host/disc, 7 == ide/host/cd, 8 == ide/host/part */
1526 if (i == 6 || i == 7 || i == 8)
1527 /* last arg should be ignored for i == 6 or i== 7 */
1528 sprintf(buffer, fmt[i] , get_old_ide_name(major, minor), ptr + 4);
1530 /* 9 == ide/host/mt */
1532 sprintf(buffer, fmt[i], ptr + 2, minor & 0x7f);
1536 sprintf(buffer, fmt[i], devname + 4);
1537 if (buffer[3] == '0')
1542 pty1 = "pqrstuvwxyzabcde";
1543 pty2 = "0123456789abcdef";
1544 indexx = atoi(devname + 5);
1545 sprintf(buffer, fmt[i], (devname[4] == 'm') ? 'p' : 't', pty1[indexx >> 4], pty2[indexx & 0x0f]);
1548 } /* End Function get_old_name */
1550 static char get_old_ide_name(unsigned int major, unsigned int minor)
1551 /* [SUMMARY] Get the old IDE name for a device.
1552 <major> The major number for the device.
1553 <minor> The minor number for the device.
1554 [RETURNS] The drive letter.
1557 char letter = 'y'; /* 121 */
1558 char c = 'a'; /* 97 */
1561 /* I hope it works like the previous code as it saves a few bytes. Tito ;P */
1563 if (i == IDE0_MAJOR || i == IDE1_MAJOR || i == IDE2_MAJOR
1564 || i == IDE3_MAJOR || i == IDE4_MAJOR || i == IDE5_MAJOR
1565 || i == IDE6_MAJOR || i == IDE7_MAJOR || i == IDE8_MAJOR
1568 if ((unsigned int)i == major) {
1575 } while (i <= IDE9_MAJOR);
1580 } /* End Function get_old_ide_name */
1582 static char *write_old_sd_name(char *buffer,
1583 unsigned int major, unsigned int minor,
1585 /* [SUMMARY] Write the old SCSI disc name to a buffer.
1586 <buffer> The buffer to write to.
1587 <major> The major number for the device.
1588 <minor> The minor number for the device.
1589 <part> The partition string. Must be "" for a whole-disc entry.
1590 [RETURNS] A pointer to the buffer on success, else NULL.
1593 unsigned int disc_index;
1596 sprintf(buffer, "sd%c%s", 'a' + (minor >> 4), part);
1599 if ((major > 64) && (major < 72)) {
1600 disc_index = ((major - 64) << 4) +(minor >> 4);
1601 if (disc_index < 26)
1602 sprintf(buffer, "sd%c%s", 'a' + disc_index, part);
1604 sprintf(buffer, "sd%c%c%s", 'a' +(disc_index / 26) - 1, 'a' + disc_index % 26, part);
1608 } /* End Function write_old_sd_name */
1613 /*EXPERIMENTAL_FUNCTION*/
1615 int st_expr_expand(char *output, unsigned int length, const char *input,
1616 const char *(*get_variable_func)(const char *variable,
1619 /* [SUMMARY] Expand an expression using Borne Shell-like unquoted rules.
1620 <output> The output expanded expression is written here.
1621 <length> The size of the output buffer.
1622 <input> The input expression. This may equal <<output>>.
1623 <get_variable> A function which will be used to get variable values. If
1624 this returns NULL, the environment is searched instead. If this is NULL,
1625 only the environment is searched.
1626 <info> An arbitrary pointer passed to <<get_variable>>.
1627 [RETURNS] TRUE on success, else FALSE.
1632 unsigned int out_pos = 0;
1635 struct passwd *pwent;
1636 char buffer[BUFFER_SIZE], tmp[STRING_LENGTH];
1638 if (length > BUFFER_SIZE)
1639 length = BUFFER_SIZE;
1640 for (; TRUE; ++input) {
1641 switch (ch = *input) {
1643 /* Variable expansion */
1644 input = expand_variable(buffer, length, &out_pos, ++input, get_variable_func, info);
1649 /* Home directory expansion */
1651 if (isspace(ch) ||(ch == '/') ||(ch == '\0')) {
1652 /* User's own home directory: leave separator for next time */
1653 if ((env = getenv("HOME")) == NULL) {
1654 msg_logger(LOG_INFO, bb_msg_variable_not_found, "HOME");
1658 if (len + out_pos >= length)
1659 goto st_expr_expand_out;
1660 memcpy(buffer + out_pos, env, len + 1);
1664 /* Someone else's home directory */
1665 for (ptr = ++input; !isspace(ch) && (ch != '/') && (ch != '\0'); ch = *++ptr)
1668 if (len >= sizeof tmp)
1669 goto st_expr_expand_out;
1670 safe_memcpy(tmp, input, len);
1672 if ((pwent = getpwnam(tmp)) == NULL) {
1673 msg_logger(LOG_INFO, "no pwent for: %s", tmp);
1676 len = strlen(pwent->pw_dir);
1677 if (len + out_pos >= length)
1678 goto st_expr_expand_out;
1679 memcpy(buffer + out_pos, pwent->pw_dir, len + 1);
1685 if (out_pos >= length)
1686 goto st_expr_expand_out;
1687 buffer[out_pos++] = ch;
1689 memcpy(output, buffer, out_pos);
1698 msg_logger(LOG_INFO, bb_msg_small_buffer);
1700 } /* End Function st_expr_expand */
1703 /* Private functions follow */
1705 static const char *expand_variable(char *buffer, unsigned int length,
1706 unsigned int *out_pos, const char *input,
1707 const char *(*func)(const char *variable,
1710 /* [SUMMARY] Expand a variable.
1711 <buffer> The buffer to write to.
1712 <length> The length of the output buffer.
1713 <out_pos> The current output position. This is updated.
1714 <input> A pointer to the input character pointer.
1715 <func> A function which will be used to get variable values. If this
1716 returns NULL, the environment is searched instead. If this is NULL, only
1717 the environment is searched.
1718 <info> An arbitrary pointer passed to <<func>>.
1719 <errfp> Diagnostic messages are written here.
1720 [RETURNS] A pointer to the end of this subexpression on success, else NULL.
1725 unsigned int open_braces;
1726 const char *env, *ptr;
1727 char tmp[STRING_LENGTH];
1731 /* Special case for "$$": PID */
1732 sprintf(tmp, "%d",(int) getpid());
1734 if (len + *out_pos >= length)
1735 goto expand_variable_out;
1737 memcpy(buffer + *out_pos, tmp, len + 1);
1741 /* Ordinary variable expansion, possibly in braces */
1743 /* Simple variable expansion */
1744 for (ptr = input; isalnum(ch) || (ch == '_') || (ch == ':'); ch = *++ptr)
1747 if ((size_t)len >= sizeof tmp)
1748 goto expand_variable_out;
1750 safe_memcpy(tmp, input, len);
1752 if ((env = get_variable_v2(tmp, func, info)) == NULL) {
1753 msg_logger(LOG_INFO, bb_msg_variable_not_found, tmp);
1757 if (len + *out_pos >= length)
1758 goto expand_variable_out;
1760 memcpy(buffer + *out_pos, env, len + 1);
1764 /* Variable in braces: check for ':' tricks */
1766 for (ptr = input; isalnum(ch) || (ch == '_'); ch = *++ptr)
1769 /* Must be simple variable expansion with "${var}" */
1771 if ((size_t)len >= sizeof tmp)
1772 goto expand_variable_out;
1774 safe_memcpy(tmp, input, len);
1775 ptr = expand_variable(buffer, length, out_pos, tmp, func, info);
1780 if (ch != ':' || ptr[1] != '-') {
1781 msg_logger(LOG_INFO, "illegal char in var name");
1784 /* It's that handy "${var:-word}" expression. Check if var is defined */
1786 if ((size_t)len >= sizeof tmp)
1787 goto expand_variable_out;
1789 safe_memcpy(tmp, input, len);
1790 /* Move input pointer to ':' */
1792 /* First skip to closing brace, taking note of nested expressions */
1795 for (open_braces = 1; open_braces > 0; ch = *++ptr) {
1804 msg_logger(LOG_INFO,"\"}\" not found in: %s", input);
1811 /* At this point ptr should point to closing brace of "${var:-word}" */
1812 if ((env = get_variable_v2(tmp, func, info)) != NULL) {
1813 /* Found environment variable, so skip the input to the closing brace
1814 and return the variable */
1817 if (len + *out_pos >= length)
1818 goto expand_variable_out;
1820 memcpy(buffer + *out_pos, env, len + 1);
1824 /* Environment variable was not found, so process word. Advance input
1825 pointer to start of word in "${var:-word}" */
1828 if ((size_t)len >= sizeof tmp)
1829 goto expand_variable_out;
1831 safe_memcpy(tmp, input, len);
1833 if (!st_expr_expand(tmp, STRING_LENGTH, tmp, func, info))
1836 if (len + *out_pos >= length)
1837 goto expand_variable_out;
1839 memcpy(buffer + *out_pos, tmp, len + 1);
1842 expand_variable_out:
1843 msg_logger(LOG_INFO, bb_msg_small_buffer);
1845 } /* End Function expand_variable */
1848 static const char *get_variable_v2(const char *variable,
1849 const char *(*func)(const char *variable, void *info),
1851 /* [SUMMARY] Get a variable from the environment or .
1852 <variable> The variable name.
1853 <func> A function which will be used to get the variable. If this returns
1854 NULL, the environment is searched instead. If this is NULL, only the
1855 environment is searched.
1856 [RETURNS] The value of the variable on success, else NULL.
1862 value = (*func)(variable, info);
1866 return getenv(variable);
1867 } /* End Function get_variable */