1 /* vi: set sw=4 ts=4: */
3 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
7 devfsd implementation for busybox
9 Copyright (C) 2003 by Tito Ragusa <farmatito@tiscali.it>
11 Busybox version is based on some previous work and ideas
12 Copyright (C) [2003] by [Matteo Croce] <3297627799@wind.it>
16 Main file for devfsd (devfs daemon for Linux).
18 Copyright (C) 1998-2002 Richard Gooch
22 Header file for devfsd (devfs daemon for Linux).
24 Copyright (C) 1998-2000 Richard Gooch
28 Compatibility name file for devfsd (build compatibility names).
30 Copyright (C) 1998-2002 Richard Gooch
34 This code provides Borne Shell-like expression expansion.
36 Copyright (C) 1997-1999 Richard Gooch
38 This program is free software; you can redistribute it and/or modify
39 it under the terms of the GNU General Public License as published by
40 the Free Software Foundation; either version 2 of the License, or
41 (at your option) any later version.
43 This program is distributed in the hope that it will be useful,
44 but WITHOUT ANY WARRANTY; without even the implied warranty of
45 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
46 GNU General Public License for more details.
48 You should have received a copy of the GNU General Public License
49 along with this program; if not, write to the Free Software
50 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
52 Richard Gooch may be reached by email at rgooch@atnf.csiro.au
53 The postal address is:
54 Richard Gooch, c/o ATNF, P. O. Box 76, Epping, N.S.W., 2121, Australia.
56 //config:config DEVFSD
57 //config: bool "devfsd (obsolete)"
59 //config: select PLATFORM_LINUX
60 //config: select FEATURE_SYSLOG
62 //config: This is deprecated and should NOT be used anymore.
63 //config: Use linux >= 2.6 (optionally with hotplug) and mdev instead!
64 //config: See docs/mdev.txt for detailed instructions on how to use mdev
67 //config: Provides compatibility with old device names on a devfs systems.
68 //config: You should set it to true if you have devfs enabled.
69 //config: The following keywords in devsfd.conf are supported:
70 //config: "CLEAR_CONFIG", "INCLUDE", "OPTIONAL_INCLUDE", "RESTORE",
71 //config: "PERMISSIONS", "EXECUTE", "COPY", "IGNORE",
72 //config: "MKOLDCOMPAT", "MKNEWCOMPAT","RMOLDCOMPAT", "RMNEWCOMPAT".
74 //config: But only if they are written UPPERCASE!!!!!!!!
76 //config:config DEVFSD_MODLOAD
77 //config: bool "Adds support for MODLOAD keyword in devsfd.conf"
79 //config: depends on DEVFSD
81 //config: This actually doesn't work with busybox modutils but needs
82 //config: the external modutils.
84 //config:config DEVFSD_FG_NP
85 //config: bool "Enable the -fg and -np options"
87 //config: depends on DEVFSD
89 //config: -fg Run the daemon in the foreground.
90 //config: -np Exit after parsing the configuration file.
91 //config: Do not poll for events.
93 //config:config DEVFSD_VERBOSE
94 //config: bool "Increases logging (and size)"
96 //config: depends on DEVFSD
98 //config: Increases logging to stderr or syslog.
100 //config:config FEATURE_DEVFS
101 //config: bool "Use devfs names for all devices (obsolete)"
103 //config: select PLATFORM_LINUX
105 //config: This is obsolete and should NOT be used anymore.
106 //config: Use linux >= 2.6 (optionally with hotplug) and mdev instead!
108 //config: For legacy systems -- if there is no way around devfsd -- this
109 //config: tells busybox to look for names like /dev/loop/0 instead of
110 //config: /dev/loop0. If your /dev directory has normal names instead of
111 //config: devfs names, you don't want this.
113 //applet:IF_DEVFSD(APPLET(devfsd, BB_DIR_SBIN, BB_SUID_DROP))
115 //kbuild:lib-$(CONFIG_DEVFSD) += devfsd.o
117 //usage:#define devfsd_trivial_usage
118 //usage: "mntpnt [-v]" IF_DEVFSD_FG_NP("[-fg][-np]")
119 //usage:#define devfsd_full_usage "\n\n"
120 //usage: "Manage devfs permissions and old device name symlinks\n"
121 //usage: "\n mntpnt The mount point where devfs is mounted"
122 //usage: "\n -v Print the protocol version numbers for devfsd"
123 //usage: "\n and the kernel-side protocol version and exit"
124 //usage: IF_DEVFSD_FG_NP(
125 //usage: "\n -fg Run in foreground"
126 //usage: "\n -np Exit after parsing the configuration file"
127 //usage: "\n and processing synthetic REGISTER events,"
128 //usage: "\n don't poll for events"
136 #include <sys/sysmacros.h>
138 /* Various defines taken from linux/major.h */
140 #define IDE1_MAJOR 22
141 #define IDE2_MAJOR 33
142 #define IDE3_MAJOR 34
143 #define IDE4_MAJOR 56
144 #define IDE5_MAJOR 57
145 #define IDE6_MAJOR 88
146 #define IDE7_MAJOR 89
147 #define IDE8_MAJOR 90
148 #define IDE9_MAJOR 91
151 /* Various defines taken from linux/devfs_fs.h */
152 #define DEVFSD_PROTOCOL_REVISION_KERNEL 5
153 #define DEVFSD_IOCTL_BASE 'd'
154 /* These are the various ioctls */
155 #define DEVFSDIOC_GET_PROTO_REV _IOR(DEVFSD_IOCTL_BASE, 0, int)
156 #define DEVFSDIOC_SET_EVENT_MASK _IOW(DEVFSD_IOCTL_BASE, 2, int)
157 #define DEVFSDIOC_RELEASE_EVENT_QUEUE _IOW(DEVFSD_IOCTL_BASE, 3, int)
158 #define DEVFSDIOC_SET_CONFIG_DEBUG_MASK _IOW(DEVFSD_IOCTL_BASE, 4, int)
159 #define DEVFSD_NOTIFY_REGISTERED 0
160 #define DEVFSD_NOTIFY_UNREGISTERED 1
161 #define DEVFSD_NOTIFY_ASYNC_OPEN 2
162 #define DEVFSD_NOTIFY_CLOSE 3
163 #define DEVFSD_NOTIFY_LOOKUP 4
164 #define DEVFSD_NOTIFY_CHANGE 5
165 #define DEVFSD_NOTIFY_CREATE 6
166 #define DEVFSD_NOTIFY_DELETE 7
167 #define DEVFS_PATHLEN 1024
168 /* Never change this otherwise the binary interface will change */
170 struct devfsd_notify_struct {
171 /* Use native C types to ensure same types in kernel and user space */
172 unsigned int type; /* DEVFSD_NOTIFY_* value */
173 unsigned int mode; /* Mode of the inode or device entry */
174 unsigned int major; /* Major number of device entry */
175 unsigned int minor; /* Minor number of device entry */
176 unsigned int uid; /* Uid of process, inode or device entry */
177 unsigned int gid; /* Gid of process, inode or device entry */
178 unsigned int overrun_count; /* Number of lost events */
179 unsigned int namelen; /* Number of characters not including '\0' */
180 /* The device name MUST come last */
181 char devname[DEVFS_PATHLEN]; /* This will be '\0' terminated */
184 #define BUFFER_SIZE 16384
185 #define DEVFSD_VERSION "1.3.25"
186 #define CONFIG_FILE "/etc/devfsd.conf"
187 #define MODPROBE "/sbin/modprobe"
188 #define MODPROBE_SWITCH_1 "-k"
189 #define MODPROBE_SWITCH_2 "-C"
190 #define CONFIG_MODULES_DEVFS "/etc/modules.devfs"
191 #define MAX_ARGS (6 + 1)
192 #define MAX_SUBEXPR 10
193 #define STRING_LENGTH 255
195 /* for get_uid_gid() */
199 /* fork_and_execute() */
203 /* for dir_operation() */
206 #define READ_CONFIG 2
208 /* Update only after changing code to reflect new protocol */
209 #define DEVFSD_PROTOCOL_REVISION_DAEMON 5
211 /* Compile-time check */
212 #if DEVFSD_PROTOCOL_REVISION_KERNEL != DEVFSD_PROTOCOL_REVISION_DAEMON
213 #error protocol version mismatch. Update your kernel headers
216 #define AC_PERMISSIONS 0
219 #define AC_MFUNCTION 3 /* not supported by busybox */
220 #define AC_CFUNCTION 4 /* not supported by busybox */
223 #define AC_MKOLDCOMPAT 7
224 #define AC_MKNEWCOMPAT 8
225 #define AC_RMOLDCOMPAT 9
226 #define AC_RMNEWCOMPAT 10
227 #define AC_RESTORE 11
229 struct permissions_type {
235 struct execute_type {
236 char *argv[MAX_ARGS + 1]; /* argv[0] must always be the programme */
241 const char *destination;
249 struct config_entry_struct {
250 struct action_type action;
254 struct permissions_type permissions;
255 struct execute_type execute;
256 struct copy_type copy;
259 struct config_entry_struct *next;
262 struct get_variable_info {
263 const struct devfsd_notify_struct *info;
265 char devpath[STRING_LENGTH];
268 static void dir_operation(int , const char * , int, unsigned long*);
269 static void service(struct stat statbuf, char *path);
270 static int st_expr_expand(char *, unsigned, const char *, const char *(*)(const char *, void *), void *);
271 static const char *get_old_name(const char *, unsigned, char *, unsigned, unsigned);
272 static int mksymlink(const char *oldpath, const char *newpath);
273 static void read_config_file(char *path, int optional, unsigned long *event_mask);
274 static void process_config_line(const char *, unsigned long *);
275 static int do_servicing(int, unsigned long);
276 static void service_name(const struct devfsd_notify_struct *);
277 static void action_permissions(const struct devfsd_notify_struct *, const struct config_entry_struct *);
278 static void action_execute(const struct devfsd_notify_struct *, const struct config_entry_struct *,
279 const regmatch_t *, unsigned);
280 static void action_modload(const struct devfsd_notify_struct *info, const struct config_entry_struct *entry);
281 static void action_copy(const struct devfsd_notify_struct *, const struct config_entry_struct *,
282 const regmatch_t *, unsigned);
283 static void action_compat(const struct devfsd_notify_struct *, unsigned);
284 static void free_config(void);
285 static void restore(char *spath, struct stat source_stat, int rootlen);
286 static int copy_inode(const char *, const struct stat *, mode_t, const char *, const struct stat *);
287 static mode_t get_mode(const char *);
288 static void signal_handler(int);
289 static const char *get_variable(const char *, void *);
290 static int make_dir_tree(const char *);
291 static int expand_expression(char *, unsigned, const char *, const char *(*)(const char *, void *), void *,
292 const char *, const regmatch_t *, unsigned);
293 static void expand_regexp(char *, size_t, const char *, const char *, const regmatch_t *, unsigned);
294 static const char *expand_variable( char *, unsigned, unsigned *, const char *,
295 const char *(*)(const char *, void *), void *);
296 static const char *get_variable_v2(const char *, const char *(*)(const char *, void *), void *);
297 static char get_old_ide_name(unsigned, unsigned);
298 static char *write_old_sd_name(char *, unsigned, unsigned, const char *);
300 /* busybox functions */
301 static int get_uid_gid(int flag, const char *string);
302 static void safe_memcpy(char * dest, const char * src, int len);
303 static unsigned int scan_dev_name_common(const char *d, unsigned int n, int addendum, const char *ptr);
304 static unsigned int scan_dev_name(const char *d, unsigned int n, const char *ptr);
306 /* Structs and vars */
307 static struct config_entry_struct *first_config = NULL;
308 static struct config_entry_struct *last_config = NULL;
309 static char *mount_point = NULL;
310 static volatile int caught_signal = FALSE;
311 static volatile int caught_sighup = FALSE;
312 static struct initial_symlink_struct {
315 } initial_symlinks[] = {
316 {"/proc/self/fd", "fd"},
323 static struct event_type {
324 unsigned int type; /* The DEVFSD_NOTIFY_* value */
325 const char *config_name; /* The name used in the config file */
327 {DEVFSD_NOTIFY_REGISTERED, "REGISTER"},
328 {DEVFSD_NOTIFY_UNREGISTERED, "UNREGISTER"},
329 {DEVFSD_NOTIFY_ASYNC_OPEN, "ASYNC_OPEN"},
330 {DEVFSD_NOTIFY_CLOSE, "CLOSE"},
331 {DEVFSD_NOTIFY_LOOKUP, "LOOKUP"},
332 {DEVFSD_NOTIFY_CHANGE, "CHANGE"},
333 {DEVFSD_NOTIFY_CREATE, "CREATE"},
334 {DEVFSD_NOTIFY_DELETE, "DELETE"},
338 /* Busybox messages */
340 static const char bb_msg_proto_rev[] ALIGN1 = "protocol revision";
341 static const char bb_msg_bad_config[] ALIGN1 = "bad %s config file: %s";
342 static const char bb_msg_small_buffer[] ALIGN1 = "buffer too small";
343 static const char bb_msg_variable_not_found[] ALIGN1 = "variable: %s not found";
346 #if ENABLE_DEVFSD_VERBOSE || ENABLE_DEBUG
347 #define info_logger(p, fmt, args...) bb_error_msg(fmt, ## args)
348 #define msg_logger(p, fmt, args...) bb_error_msg(fmt, ## args)
349 #define msg_logger_and_die(p, fmt, args...) bb_error_msg_and_die(fmt, ## args)
350 #define error_logger(p, fmt, args...) bb_perror_msg(fmt, ## args)
351 #define error_logger_and_die(p, fmt, args...) bb_perror_msg_and_die(fmt, ## args)
353 #define info_logger(p, fmt, args...)
354 #define msg_logger(p, fmt, args...)
355 #define msg_logger_and_die(p, fmt, args...) exit(EXIT_FAILURE)
356 #define error_logger(p, fmt, args...)
357 #define error_logger_and_die(p, fmt, args...) exit(EXIT_FAILURE)
360 static void safe_memcpy(char *dest, const char *src, int len)
362 memcpy(dest , src, len);
366 static unsigned int scan_dev_name_common(const char *d, unsigned int n, int addendum, const char *ptr)
368 if (d[n - 4] == 'd' && d[n - 3] == 'i' && d[n - 2] == 's' && d[n - 1] == 'c')
370 if (d[n - 2] == 'c' && d[n - 1] == 'd')
372 if (ptr[0] == 'p' && ptr[1] == 'a' && ptr[2] == 'r' && ptr[3] == 't')
374 if (ptr[n - 2] == 'm' && ptr[n - 1] == 't')
379 static unsigned int scan_dev_name(const char *d, unsigned int n, const char *ptr)
381 if (d[0] == 's' && d[1] == 'c' && d[2] == 's' && d[3] == 'i' && d[4] == '/') {
382 if (d[n - 7] == 'g' && d[n - 6] == 'e' && d[n - 5] == 'n'
383 && d[n - 4] == 'e' && d[n - 3] == 'r' && d[n - 2] == 'i' && d[n - 1] == 'c'
386 return scan_dev_name_common(d, n, 0, ptr);
388 if (d[0] == 'i' && d[1] == 'd' && d[2] == 'e' && d[3] == '/'
389 && d[4] == 'h' && d[5] == 'o' && d[6] == 's' && d[7] == 't'
391 return scan_dev_name_common(d, n, 4, ptr);
392 if (d[0] == 's' && d[1] == 'b' && d[2] == 'p' && d[3] == '/')
394 if (d[0] == 'v' && d[1] == 'c' && d[2] == 'c' && d[3] == '/')
396 if (d[0] == 'p' && d[1] == 't' && d[2] == 'y' && d[3] == '/')
401 /* Public functions follow */
403 int devfsd_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
404 int devfsd_main(int argc, char **argv)
406 int print_version = FALSE;
407 int do_daemon = TRUE;
408 int no_polling = FALSE;
410 int fd, proto_rev, count;
411 unsigned long event_mask = 0;
412 struct sigaction new_action;
413 struct initial_symlink_struct *curr;
418 for (count = 2; count < argc; ++count) {
419 if (argv[count][0] == '-') {
420 if (argv[count][1] == 'v' && !argv[count][2]) /* -v */
421 print_version = TRUE;
422 else if (ENABLE_DEVFSD_FG_NP && argv[count][1] == 'f'
423 && argv[count][2] == 'g' && !argv[count][3]) /* -fg */
425 else if (ENABLE_DEVFSD_FG_NP && argv[count][1] == 'n'
426 && argv[count][2] == 'p' && !argv[count][3]) /* -np */
433 mount_point = bb_simplify_path(argv[1]);
437 fd = xopen(".devfsd", O_RDONLY);
438 close_on_exec_on(fd);
439 xioctl(fd, DEVFSDIOC_GET_PROTO_REV, &proto_rev);
441 /*setup initial entries */
442 for (curr = initial_symlinks; curr->dest != NULL; ++curr)
443 symlink(curr->dest, curr->name);
445 /* NB: The check for CONFIG_FILE is done in read_config_file() */
447 if (print_version || (DEVFSD_PROTOCOL_REVISION_DAEMON != proto_rev)) {
448 printf("%s v%s\nDaemon %s:\t%d\nKernel-side %s:\t%d\n",
449 applet_name, DEVFSD_VERSION, bb_msg_proto_rev,
450 DEVFSD_PROTOCOL_REVISION_DAEMON, bb_msg_proto_rev, proto_rev);
451 if (DEVFSD_PROTOCOL_REVISION_DAEMON != proto_rev)
452 bb_error_msg_and_die("%s mismatch!", bb_msg_proto_rev);
453 exit(EXIT_SUCCESS); /* -v */
455 /* Tell kernel we are special(i.e. we get to see hidden entries) */
456 xioctl(fd, DEVFSDIOC_SET_EVENT_MASK, 0);
458 /* Set up SIGHUP and SIGUSR1 handlers */
459 sigemptyset(&new_action.sa_mask);
460 new_action.sa_flags = 0;
461 new_action.sa_handler = signal_handler;
462 sigaction_set(SIGHUP, &new_action);
463 sigaction_set(SIGUSR1, &new_action);
465 printf("%s v%s started for %s\n", applet_name, DEVFSD_VERSION, mount_point);
467 /* Set umask so that mknod(2), open(2) and mkdir(2) have complete control over permissions */
469 read_config_file((char*)CONFIG_FILE, FALSE, &event_mask);
470 /* Do the scan before forking, so that boot scripts see the finished product */
471 dir_operation(SERVICE, mount_point, 0, NULL);
473 if (ENABLE_DEVFSD_FG_NP && no_polling)
476 if (ENABLE_DEVFSD_VERBOSE || ENABLE_DEBUG)
477 logmode = LOGMODE_BOTH;
478 else if (do_daemon == TRUE)
479 logmode = LOGMODE_SYSLOG;
480 /* This is the default */
482 logmode = LOGMODE_STDIO; */
485 /* Release so that the child can grab it */
486 xioctl(fd, DEVFSDIOC_RELEASE_EVENT_QUEUE, 0);
487 bb_daemonize_or_rexec(0, argv);
488 } else if (ENABLE_DEVFSD_FG_NP) {
489 setpgid(0, 0); /* Become process group leader */
493 do_scan = do_servicing(fd, event_mask);
496 read_config_file((char*)CONFIG_FILE, FALSE, &event_mask);
498 dir_operation(SERVICE, mount_point, 0, NULL);
500 if (ENABLE_FEATURE_CLEAN_UP) free(mount_point);
501 } /* End Function main */
504 /* Private functions follow */
506 static void read_config_file(char *path, int optional, unsigned long *event_mask)
507 /* [SUMMARY] Read a configuration database.
508 <path> The path to read the database from. If this is a directory, all
509 entries in that directory will be read(except hidden entries).
510 <optional> If TRUE, the routine will silently ignore a missing config file.
511 <event_mask> The event mask is written here. This is not initialised.
517 char buf[STRING_LENGTH];
521 if (stat(path, &statbuf) == 0) {
522 /* Don't read 0 length files: ignored */
523 /*if (statbuf.st_size == 0)
525 if (S_ISDIR(statbuf.st_mode)) {
526 p = bb_simplify_path(path);
527 dir_operation(READ_CONFIG, p, 0, event_mask);
531 fp = fopen_for_read(path);
533 while (fgets(buf, STRING_LENGTH, fp) != NULL) {
534 /* Skip whitespace */
536 line = skip_whitespace(line);
537 if (line[0] == '\0' || line[0] == '#')
539 process_config_line(line, event_mask);
543 goto read_config_file_err;
546 read_config_file_err:
547 if (optional == 0 && errno == ENOENT)
548 error_logger_and_die(LOG_ERR, "read config file: %s", path);
550 } /* End Function read_config_file */
552 static void process_config_line(const char *line, unsigned long *event_mask)
553 /* [SUMMARY] Process a line from a configuration file.
554 <line> The configuration line.
555 <event_mask> The event mask is written here. This is not initialised.
560 struct config_entry_struct *new;
561 char p[MAX_ARGS][STRING_LENGTH];
562 char when[STRING_LENGTH], what[STRING_LENGTH];
563 char name[STRING_LENGTH];
564 const char *msg = "";
568 /* !!!! Only Uppercase Keywords in devsfd.conf */
569 static const char options[] ALIGN1 =
570 "CLEAR_CONFIG\0""INCLUDE\0""OPTIONAL_INCLUDE\0"
571 "RESTORE\0""PERMISSIONS\0""MODLOAD\0""EXECUTE\0"
572 "COPY\0""IGNORE\0""MKOLDCOMPAT\0""MKNEWCOMPAT\0"
573 "RMOLDCOMPAT\0""RMNEWCOMPAT\0";
575 for (count = 0; count < MAX_ARGS; ++count)
577 num_args = sscanf(line, "%s %s %s %s %s %s %s %s %s %s",
579 p[0], p[1], p[2], p[3], p[4], p[5], p[6]);
581 i = index_in_strings(options, when);
591 goto process_config_line_err;
593 /* "INCLUDE" & "OPTIONAL_INCLUDE" */
594 if (i == 1 || i == 2) {
595 st_expr_expand(name, STRING_LENGTH, name, get_variable, NULL);
596 info_logger(LOG_INFO, "%sinclude: %s", (toupper(when[0]) == 'I') ? "": "optional_", name);
597 read_config_file(name, (toupper(when[0]) == 'I') ? FALSE : TRUE, event_mask);
602 dir_operation(RESTORE, name, strlen(name),NULL);
606 goto process_config_line_err;
608 new = xzalloc(sizeof *new);
610 for (count = 0; event_types[count].config_name != NULL; ++count) {
611 if (strcasecmp(when, event_types[count].config_name) != 0)
613 new->action.when = event_types[count].type;
616 if (event_types[count].config_name == NULL) {
618 goto process_config_line_err;
621 i = index_in_strings(options, what);
624 case 4: /* "PERMISSIONS" */
625 new->action.what = AC_PERMISSIONS;
626 /* Get user and group */
627 ptr = strchr(p[0], '.');
630 goto process_config_line_err; /*"missing '.' in UID.GID"*/
634 new->u.permissions.uid = get_uid_gid(UID, p[0]);
635 new->u.permissions.gid = get_uid_gid(GID, ptr);
637 new->u.permissions.mode = get_mode(p[1]);
639 case 5: /* MODLOAD */
640 /*This action will pass "/dev/$devname"(i.e. "/dev/" prefixed to
641 the device name) to the module loading facility. In addition,
642 the /etc/modules.devfs configuration file is used.*/
643 if (ENABLE_DEVFSD_MODLOAD)
644 new->action.what = AC_MODLOAD;
646 case 6: /* EXECUTE */
647 new->action.what = AC_EXECUTE;
650 for (count = 0; count < num_args; ++count)
651 new->u.execute.argv[count] = xstrdup(p[count]);
653 new->u.execute.argv[num_args] = NULL;
656 new->action.what = AC_COPY;
659 goto process_config_line_err; /* missing path and function in line */
661 new->u.copy.source = xstrdup(p[0]);
662 new->u.copy.destination = xstrdup(p[1]);
666 case 9: /* MKOLDCOMPAT */
668 case 10: /* MKNEWCOMPAT */
670 case 11:/* RMOLDCOMPAT */
672 case 12: /* RMNEWCOMPAT */
678 new->action.what = i - 2;
682 goto process_config_line_err;
686 xregcomp(&new->preg, name, REG_EXTENDED);
688 *event_mask |= 1 << new->action.when;
690 if (first_config == NULL)
693 last_config->next = new;
697 process_config_line_err:
698 msg_logger_and_die(LOG_ERR, bb_msg_bad_config, msg , line);
699 } /* End Function process_config_line */
701 static int do_servicing(int fd, unsigned long event_mask)
702 /* [SUMMARY] Service devfs changes until a signal is received.
703 <fd> The open control file.
704 <event_mask> The event mask.
705 [RETURNS] TRUE if SIGHUP was caught, else FALSE.
709 struct devfsd_notify_struct info;
711 /* (void*) cast is only in order to match prototype */
712 xioctl(fd, DEVFSDIOC_SET_EVENT_MASK, (void*)event_mask);
713 while (!caught_signal) {
715 bytes = read(fd, (char *) &info, sizeof info);
717 break; /* Must test for this first */
719 continue; /* Yes, the order is important */
725 int c_sighup = caught_sighup;
727 caught_signal = FALSE;
728 caught_sighup = FALSE;
731 msg_logger_and_die(LOG_ERR, "read error on control file");
732 } /* End Function do_servicing */
734 static void service_name(const struct devfsd_notify_struct *info)
735 /* [SUMMARY] Service a single devfs change.
736 <info> The devfs change.
741 regmatch_t mbuf[MAX_SUBEXPR];
742 struct config_entry_struct *entry;
744 if (ENABLE_DEBUG && info->overrun_count > 0)
745 msg_logger(LOG_ERR, "lost %u events", info->overrun_count);
747 /* Discard lookups on "/dev/log" and "/dev/initctl" */
748 if (info->type == DEVFSD_NOTIFY_LOOKUP
749 && ((info->devname[0] == 'l' && info->devname[1] == 'o'
750 && info->devname[2] == 'g' && !info->devname[3])
751 || (info->devname[0] == 'i' && info->devname[1] == 'n'
752 && info->devname[2] == 'i' && info->devname[3] == 't'
753 && info->devname[4] == 'c' && info->devname[5] == 't'
754 && info->devname[6] == 'l' && !info->devname[7]))
758 for (entry = first_config; entry != NULL; entry = entry->next) {
759 /* First check if action matches the type, then check if name matches */
760 if (info->type != entry->action.when
761 || regexec(&entry->preg, info->devname, MAX_SUBEXPR, mbuf, 0) != 0)
763 for (n = 0;(n < MAX_SUBEXPR) && (mbuf[n].rm_so != -1); ++n)
766 switch (entry->action.what) {
768 action_permissions(info, entry);
771 if (ENABLE_DEVFSD_MODLOAD)
772 action_modload(info, entry);
775 action_execute(info, entry, mbuf, n);
778 action_copy(info, entry, mbuf, n);
787 action_compat(info, entry->action.what);
790 msg_logger_and_die(LOG_ERR, "Unknown action");
793 } /* End Function service_name */
795 static void action_permissions(const struct devfsd_notify_struct *info,
796 const struct config_entry_struct *entry)
797 /* [SUMMARY] Update permissions for a device entry.
798 <info> The devfs change.
799 <entry> The config file entry.
805 if (stat(info->devname, &statbuf) != 0
806 || chmod(info->devname, (statbuf.st_mode & S_IFMT) | (entry->u.permissions.mode & ~S_IFMT)) != 0
807 || chown(info->devname, entry->u.permissions.uid, entry->u.permissions.gid) != 0
809 error_logger(LOG_ERR, "Can't chmod or chown: %s", info->devname);
810 } /* End Function action_permissions */
812 static void action_modload(const struct devfsd_notify_struct *info,
813 const struct config_entry_struct *entry UNUSED_PARAM)
814 /* [SUMMARY] Load a module.
815 <info> The devfs change.
816 <entry> The config file entry.
822 argv[0] = (char*)MODPROBE;
823 argv[1] = (char*)MODPROBE_SWITCH_1; /* "-k" */
824 argv[2] = (char*)MODPROBE_SWITCH_2; /* "-C" */
825 argv[3] = (char*)CONFIG_MODULES_DEVFS;
826 argv[4] = concat_path_file("/dev", info->devname); /* device */
829 spawn_and_wait(argv);
831 } /* End Function action_modload */
833 static void action_execute(const struct devfsd_notify_struct *info,
834 const struct config_entry_struct *entry,
835 const regmatch_t *regexpr, unsigned int numexpr)
836 /* [SUMMARY] Execute a programme.
837 <info> The devfs change.
838 <entry> The config file entry.
839 <regexpr> The number of subexpression(start, end) offsets within the
841 <numexpr> The number of elements within <<regexpr>>.
846 struct get_variable_info gv_info;
847 char *argv[MAX_ARGS + 1];
848 char largv[MAX_ARGS + 1][STRING_LENGTH];
851 gv_info.devname = info->devname;
852 snprintf(gv_info.devpath, sizeof(gv_info.devpath), "%s/%s", mount_point, info->devname);
853 for (count = 0; entry->u.execute.argv[count] != NULL; ++count) {
854 expand_expression(largv[count], STRING_LENGTH,
855 entry->u.execute.argv[count],
856 get_variable, &gv_info,
857 gv_info.devname, regexpr, numexpr);
858 argv[count] = largv[count];
861 spawn_and_wait(argv);
862 } /* End Function action_execute */
865 static void action_copy(const struct devfsd_notify_struct *info,
866 const struct config_entry_struct *entry,
867 const regmatch_t *regexpr, unsigned int numexpr)
868 /* [SUMMARY] Copy permissions.
869 <info> The devfs change.
870 <entry> The config file entry.
871 <regexpr> This list of subexpression(start, end) offsets within the
873 <numexpr> The number of elements in <<regexpr>>.
878 struct get_variable_info gv_info;
879 struct stat source_stat, dest_stat;
880 char source[STRING_LENGTH], destination[STRING_LENGTH];
883 dest_stat.st_mode = 0;
885 if ((info->type == DEVFSD_NOTIFY_CHANGE) && S_ISLNK(info->mode))
888 gv_info.devname = info->devname;
890 snprintf(gv_info.devpath, sizeof(gv_info.devpath), "%s/%s", mount_point, info->devname);
891 expand_expression(source, STRING_LENGTH, entry->u.copy.source,
892 get_variable, &gv_info, gv_info.devname,
895 expand_expression(destination, STRING_LENGTH, entry->u.copy.destination,
896 get_variable, &gv_info, gv_info.devname,
899 if (!make_dir_tree(destination) || lstat(source, &source_stat) != 0)
901 lstat(destination, &dest_stat);
902 new_mode = source_stat.st_mode & ~S_ISVTX;
903 if (info->type == DEVFSD_NOTIFY_CREATE)
905 else if ((info->type == DEVFSD_NOTIFY_CHANGE) &&(dest_stat.st_mode & S_ISVTX))
907 ret = copy_inode(destination, &dest_stat, new_mode, source, &source_stat);
908 if (ENABLE_DEBUG && ret && (errno != EEXIST))
909 error_logger(LOG_ERR, "copy_inode: %s to %s", source, destination);
910 } /* End Function action_copy */
912 static void action_compat(const struct devfsd_notify_struct *info, unsigned int action)
913 /* [SUMMARY] Process a compatibility request.
914 <info> The devfs change.
915 <action> The action to take.
920 const char *compat_name = NULL;
921 const char *dest_name = info->devname;
923 char compat_buf[STRING_LENGTH], dest_buf[STRING_LENGTH];
924 int mode, host, bus, target, lun;
927 /* 1 to 5 "scsi/" , 6 to 9 "ide/host" */
928 static const char *const fmt[] = {
930 "sg/c%db%dt%du%d", /* scsi/generic */
931 "sd/c%db%dt%du%d", /* scsi/disc */
932 "sr/c%db%dt%du%d", /* scsi/cd */
933 "sd/c%db%dt%du%dp%d", /* scsi/part */
934 "st/c%db%dt%du%dm%d%c", /* scsi/mt */
935 "ide/hd/c%db%dt%du%d", /* ide/host/disc */
936 "ide/cd/c%db%dt%du%d", /* ide/host/cd */
937 "ide/hd/c%db%dt%du%dp%d", /* ide/host/part */
938 "ide/mt/c%db%dt%du%d%s", /* ide/host/mt */
942 /* First construct compatibility name */
946 compat_name = get_old_name(info->devname, info->namelen, compat_buf, info->major, info->minor);
950 ptr = bb_basename(info->devname);
951 i = scan_dev_name(info->devname, info->namelen, ptr);
957 sscanf(info->devname + ((i < 6) ? 5 : 4), "host%d/bus%d/target%d/lun%d/", &host, &bus, &target, &lun);
958 snprintf(dest_buf, sizeof(dest_buf), "../%s", info->devname + (( i > 5) ? 4 : 0));
959 dest_name = dest_buf;
960 compat_name = compat_buf;
963 /* 1 == scsi/generic 2 == scsi/disc 3 == scsi/cd 6 == ide/host/disc 7 == ide/host/cd */
964 if (i == 1 || i == 2 || i == 3 || i == 6 || i ==7)
965 sprintf(compat_buf, fmt[i], host, bus, target, lun);
967 /* 4 == scsi/part 8 == ide/host/part */
968 if (i == 4 || i == 8)
969 sprintf(compat_buf, fmt[i], host, bus, target, lun, atoi(ptr + 4));
973 rewind_ = info->devname[info->namelen - 1];
977 if (ptr[2] == 'l' /*108*/ || ptr[2] == 'm'/*109*/)
978 mode = ptr[2] - 107; /* 1 or 2 */
981 sprintf(compat_buf, fmt[i], host, bus, target, lun, mode, rewind_);
984 /* 9 == ide/host/mt */
986 snprintf(compat_buf, sizeof(compat_buf), fmt[i], host, bus, target, lun, ptr + 2);
988 } /* switch (action) */
990 if (compat_name == NULL)
993 /* Now decide what to do with it */
997 mksymlink(dest_name, compat_name);
1000 case AC_RMNEWCOMPAT:
1001 ret = unlink(compat_name);
1002 if (ENABLE_DEBUG && ret)
1003 error_logger(LOG_ERR, "unlink: %s", compat_name);
1006 } /* switch (action) */
1007 } /* End Function action_compat */
1009 static void restore(char *spath, struct stat source_stat, int rootlen)
1012 struct stat dest_stat;
1014 dest_stat.st_mode = 0;
1015 dpath = concat_path_file(mount_point, spath + rootlen);
1016 lstat(dpath, &dest_stat);
1018 if (S_ISLNK(source_stat.st_mode) || (source_stat.st_mode & S_ISVTX))
1019 copy_inode(dpath, &dest_stat, (source_stat.st_mode & ~S_ISVTX), spath, &source_stat);
1021 if (S_ISDIR(source_stat.st_mode))
1022 dir_operation(RESTORE, spath, rootlen, NULL);
1026 static int copy_inode(const char *destpath, const struct stat *dest_stat,
1028 const char *sourcepath, const struct stat *source_stat)
1029 /* [SUMMARY] Copy an inode.
1030 <destpath> The destination path. An existing inode may be deleted.
1031 <dest_stat> The destination stat(2) information.
1032 <new_mode> The desired new mode for the destination.
1033 <sourcepath> The source path.
1034 <source_stat> The source stat(2) information.
1035 [RETURNS] TRUE on success, else FALSE.
1038 int source_len, dest_len;
1039 char source_link[STRING_LENGTH], dest_link[STRING_LENGTH];
1041 struct sockaddr_un un_addr;
1042 char symlink_val[STRING_LENGTH];
1044 if ((source_stat->st_mode & S_IFMT) ==(dest_stat->st_mode & S_IFMT)) {
1046 if (S_ISLNK(source_stat->st_mode)) {
1047 source_len = readlink(sourcepath, source_link, STRING_LENGTH - 1);
1048 if ((source_len < 0)
1049 || (dest_len = readlink(destpath, dest_link, STRING_LENGTH - 1)) < 0
1052 source_link[source_len] = '\0';
1053 dest_link[dest_len] = '\0';
1054 if ((source_len != dest_len) || (strcmp(source_link, dest_link) != 0)) {
1056 symlink(source_link, destpath);
1059 } /* Else not a symlink */
1060 chmod(destpath, new_mode & ~S_IFMT);
1061 chown(destpath, source_stat->st_uid, source_stat->st_gid);
1064 /* Different types: unlink and create */
1066 switch (source_stat->st_mode & S_IFMT) {
1068 fd = socket(AF_UNIX, SOCK_STREAM, 0);
1071 un_addr.sun_family = AF_UNIX;
1072 snprintf(un_addr.sun_path, sizeof(un_addr.sun_path), "%s", destpath);
1073 val = bind(fd, (struct sockaddr *) &un_addr, (int) sizeof un_addr);
1075 if (val != 0 || chmod(destpath, new_mode & ~S_IFMT) != 0)
1079 val = readlink(sourcepath, symlink_val, STRING_LENGTH - 1);
1082 symlink_val[val] = '\0';
1083 if (symlink(symlink_val, destpath) == 0)
1087 fd = open(destpath, O_RDONLY | O_CREAT, new_mode & ~S_IFMT);
1091 if (chmod(destpath, new_mode & ~S_IFMT) != 0)
1097 if (mknod(destpath, new_mode, source_stat->st_rdev) != 0)
1101 if (mkdir(destpath, new_mode & ~S_IFMT) != 0)
1104 if (chown(destpath, source_stat->st_uid, source_stat->st_gid) == 0)
1109 } /* End Function copy_inode */
1111 static void free_config(void)
1112 /* [SUMMARY] Free the configuration information.
1116 struct config_entry_struct *c_entry;
1119 for (c_entry = first_config; c_entry != NULL; c_entry = next) {
1122 next = c_entry->next;
1123 regfree(&c_entry->preg);
1124 if (c_entry->action.what == AC_EXECUTE) {
1125 for (count = 0; count < MAX_ARGS; ++count) {
1126 if (c_entry->u.execute.argv[count] == NULL)
1128 free(c_entry->u.execute.argv[count]);
1133 first_config = NULL;
1135 } /* End Function free_config */
1137 static int get_uid_gid(int flag, const char *string)
1138 /* [SUMMARY] Convert a string to a UID or GID value.
1139 <flag> "UID" or "GID".
1140 <string> The string.
1141 [RETURNS] The UID or GID value.
1144 struct passwd *pw_ent;
1145 struct group *grp_ent;
1148 if (isdigit(string[0]) || ((string[0] == '-') && isdigit(string[1])))
1149 return atoi(string);
1151 if (flag == UID && (pw_ent = getpwnam(string)) != NULL)
1152 return pw_ent->pw_uid;
1154 if (ENABLE_DEVFSD_VERBOSE)
1158 if ((grp_ent = getgrnam(string)) != NULL)
1159 return grp_ent->gr_gid;
1160 if (ENABLE_DEVFSD_VERBOSE)
1164 if (ENABLE_DEVFSD_VERBOSE)
1165 msg_logger(LOG_ERR, "unknown %s: %s, defaulting to %cid=0", msg, string, msg[0]);
1167 }/* End Function get_uid_gid */
1169 static mode_t get_mode(const char *string)
1170 /* [SUMMARY] Convert a string to a mode value.
1171 <string> The string.
1172 [RETURNS] The mode value.
1178 if (isdigit(string[0]))
1179 return strtoul(string, NULL, 8);
1180 if (strlen(string) != 9)
1181 msg_logger_and_die(LOG_ERR, "bad mode: %s", string);
1186 if (string[0] == 'r' || string[0] == 'w' || string[0] == 'x')
1192 } /* End Function get_mode */
1194 static void signal_handler(int sig)
1196 caught_signal = TRUE;
1198 caught_sighup = TRUE;
1200 info_logger(LOG_INFO, "Caught signal %d", sig);
1201 } /* End Function signal_handler */
1203 static const char *get_variable(const char *variable, void *info)
1205 static char *hostname;
1207 struct get_variable_info *gv_info = info;
1208 const char *field_names[] = {
1209 "hostname", "mntpt", "devpath", "devname", "uid", "gid", "mode",
1210 NULL, mount_point, gv_info->devpath, gv_info->devname, NULL
1215 hostname = safe_gethostname();
1216 field_names[7] = hostname;
1218 /* index_in_str_array returns i>=0 */
1219 i = index_in_str_array(field_names, variable);
1221 if (i > 6 || i < 0 || (i > 1 && gv_info == NULL))
1223 if (i >= 0 && i <= 3)
1224 return field_names[i + 7];
1227 return auto_string(xasprintf("%u", gv_info->info->uid));
1229 return auto_string(xasprintf("%u", gv_info->info->gid));
1231 return auto_string(xasprintf("%o", gv_info->info->mode));
1232 } /* End Function get_variable */
1234 static void service(struct stat statbuf, char *path)
1236 struct devfsd_notify_struct info;
1238 memset(&info, 0, sizeof info);
1239 info.type = DEVFSD_NOTIFY_REGISTERED;
1240 info.mode = statbuf.st_mode;
1241 info.major = major(statbuf.st_rdev);
1242 info.minor = minor(statbuf.st_rdev);
1243 info.uid = statbuf.st_uid;
1244 info.gid = statbuf.st_gid;
1245 snprintf(info.devname, sizeof(info.devname), "%s", path + strlen(mount_point) + 1);
1246 info.namelen = strlen(info.devname);
1247 service_name(&info);
1248 if (S_ISDIR(statbuf.st_mode))
1249 dir_operation(SERVICE, path, 0, NULL);
1252 static void dir_operation(int type, const char * dir_name, int var, unsigned long *event_mask)
1253 /* [SUMMARY] Scan a directory tree and generate register events on leaf nodes.
1254 <flag> To choose which function to perform
1255 <dp> The directory pointer. This is closed upon completion.
1256 <dir_name> The name of the directory.
1257 <rootlen> string length parameter.
1261 struct stat statbuf;
1266 dp = warn_opendir(dir_name);
1270 while ((de = readdir(dp)) != NULL) {
1272 if (de->d_name && DOT_OR_DOTDOT(de->d_name))
1274 path = concat_path_file(dir_name, de->d_name);
1275 if (lstat(path, &statbuf) == 0) {
1278 service(statbuf, path);
1281 restore(path, statbuf, var);
1284 read_config_file(path, var, event_mask);
1291 } /* End Function do_scan_and_service */
1293 static int mksymlink(const char *oldpath, const char *newpath)
1294 /* [SUMMARY] Create a symlink, creating intervening directories as required.
1295 <oldpath> The string contained in the symlink.
1296 <newpath> The name of the new symlink.
1297 [RETURNS] 0 on success, else -1.
1300 if (!make_dir_tree(newpath))
1303 if (symlink(oldpath, newpath) != 0) {
1304 if (errno != EEXIST)
1308 } /* End Function mksymlink */
1311 static int make_dir_tree(const char *path)
1312 /* [SUMMARY] Creating intervening directories for a path as required.
1313 <path> The full pathname(including the leaf node).
1314 [RETURNS] TRUE on success, else FALSE.
1317 if (bb_make_directory(dirname((char *)path), -1, FILEUTILS_RECUR) == -1)
1320 } /* End Function make_dir_tree */
1322 static int expand_expression(char *output, unsigned int outsize,
1324 const char *(*get_variable_func)(const char *variable, void *info),
1326 const char *devname,
1327 const regmatch_t *ex, unsigned int numexp)
1328 /* [SUMMARY] Expand environment variables and regular subexpressions in string.
1329 <output> The output expanded expression is written here.
1330 <length> The size of the output buffer.
1331 <input> The input expression. This may equal <<output>>.
1332 <get_variable> A function which will be used to get variable values. If
1333 this returns NULL, the environment is searched instead. If this is NULL,
1334 only the environment is searched.
1335 <info> An arbitrary pointer passed to <<get_variable>>.
1336 <devname> Device name; specifically, this is the string that contains all
1337 of the regular subexpressions.
1338 <ex> Array of start / end offsets into info->devname for each subexpression
1339 <numexp> Number of regular subexpressions found in <<devname>>.
1340 [RETURNS] TRUE on success, else FALSE.
1343 char temp[STRING_LENGTH];
1345 if (!st_expr_expand(temp, STRING_LENGTH, input, get_variable_func, info))
1347 expand_regexp(output, outsize, temp, devname, ex, numexp);
1349 } /* End Function expand_expression */
1351 static void expand_regexp(char *output, size_t outsize, const char *input,
1352 const char *devname,
1353 const regmatch_t *ex, unsigned int numex)
1354 /* [SUMMARY] Expand all occurrences of the regular subexpressions \0 to \9.
1355 <output> The output expanded expression is written here.
1356 <outsize> The size of the output buffer.
1357 <input> The input expression. This may NOT equal <<output>>, because
1358 supporting that would require yet another string-copy. However, it's not
1359 hard to write a simple wrapper function to add this functionality for those
1360 few cases that need it.
1361 <devname> Device name; specifically, this is the string that contains all
1362 of the regular subexpressions.
1363 <ex> An array of start and end offsets into <<devname>>, one for each
1365 <numex> Number of subexpressions in the offset-array <<ex>>.
1369 const char last_exp = '0' - 1 + numex;
1372 /* Guarantee NULL termination by writing an explicit '\0' character into
1373 the very last byte */
1375 output[--outsize] = '\0';
1376 /* Copy the input string into the output buffer, replacing '\\' with '\'
1377 and '\0' .. '\9' with subexpressions 0 .. 9, if they exist. Other \x
1378 codes are deleted */
1379 while ((c != '\0') && (outsize != 0)) {
1386 if ((c >= '0') && (c <= last_exp)) {
1387 const regmatch_t *subexp = ex + (c - '0');
1388 unsigned int sublen = subexp->rm_eo - subexp->rm_so;
1390 /* Range checking */
1391 if (sublen > outsize)
1393 strncpy(output, devname + subexp->rm_so, sublen);
1404 } /* End Function expand_regexp */
1407 /* from compat_name.c */
1409 struct translate_struct {
1410 const char *match; /* The string to match to(up to length) */
1411 const char *format; /* Format of output, "%s" takes data past match string,
1412 NULL is effectively "%s"(just more efficient) */
1415 static struct translate_struct translate_table[] =
1418 {"printers/", "lp%s"},
1420 {"parports/", "parport%s"},
1423 {"loop/", "loop%s"},
1424 {"floppy/", "fd%s"},
1426 {"md/", "md%s"}, /* Meta-devices */
1430 {"pg/", "pg%s"}, /* Parallel port generic ATAPI interface*/
1432 {"staliomem/", "staliomem%s"}, /* Stallion serial driver control */
1433 {"tts/E", "ttyE%s"}, /* Stallion serial driver */
1434 {"cua/E", "cue%s"}, /* Stallion serial driver callout */
1435 {"tts/R", "ttyR%s"}, /* Rocketport serial driver */
1436 {"cua/R", "cur%s"}, /* Rocketport serial driver callout */
1437 {"ip2/", "ip2%s"}, /* Computone serial driver control */
1438 {"tts/F", "ttyF%s"}, /* Computone serial driver */
1439 {"cua/F", "cuf%s"}, /* Computone serial driver callout */
1440 {"tts/C", "ttyC%s"}, /* Cyclades serial driver */
1441 {"cua/C", "cub%s"}, /* Cyclades serial driver callout */
1442 {"tts/", "ttyS%s"}, /* Generic serial: must be after others */
1443 {"cua/", "cua%s"}, /* Generic serial: must be after others */
1444 {"input/js", "js%s"}, /* Joystick driver */
1448 const char *get_old_name(const char *devname, unsigned int namelen,
1449 char *buffer, unsigned int major, unsigned int minor)
1450 /* [SUMMARY] Translate a kernel-supplied name into an old name.
1451 <devname> The device name provided by the kernel.
1452 <namelen> The length of the name.
1453 <buffer> A buffer that may be used. This should be at least 128 bytes long.
1454 <major> The major number for the device.
1455 <minor> The minor number for the device.
1456 [RETURNS] A pointer to the old name if known, else NULL.
1459 const char *compat_name = NULL;
1461 struct translate_struct *trans;
1467 /* 1 to 5 "scsi/" , 6 to 9 "ide/host", 10 sbp/, 11 vcc/, 12 pty/ */
1468 static const char *const fmt[] = {
1470 "sg%u", /* scsi/generic */
1471 NULL, /* scsi/disc */
1472 "sr%u", /* scsi/cd */
1473 NULL, /* scsi/part */
1474 "nst%u%c", /* scsi/mt */
1475 "hd%c" , /* ide/host/disc */
1476 "hd%c" , /* ide/host/cd */
1477 "hd%c%s", /* ide/host/part */
1478 "%sht%d", /* ide/host/mt */
1479 "sbpcd%u", /* sbp/ */
1481 "%cty%c%c", /* pty/ */
1485 for (trans = translate_table; trans->match != NULL; ++trans) {
1486 char *after_match = is_prefixed_with(devname, trans->match);
1488 if (trans->format == NULL)
1490 sprintf(buffer, trans->format, after_match);
1495 ptr = bb_basename(devname);
1496 i = scan_dev_name(devname, namelen, ptr);
1498 if (i > 0 && i < 13)
1499 compat_name = buffer;
1503 /* 1 == scsi/generic, 3 == scsi/cd, 10 == sbp/ */
1504 if (i == 1 || i == 3 || i == 10)
1505 sprintf(buffer, fmt[i], minor);
1507 /* 2 ==scsi/disc, 4 == scsi/part */
1508 if (i == 2 || i == 4)
1509 compat_name = write_old_sd_name(buffer, major, minor, ((i == 2) ? "" : (ptr + 4)));
1516 sprintf(buffer, fmt[i], minor & 0x1f, mode);
1517 if (devname[namelen - 1] != 'n')
1520 /* 6 == ide/host/disc, 7 == ide/host/cd, 8 == ide/host/part */
1521 if (i == 6 || i == 7 || i == 8)
1522 /* last arg should be ignored for i == 6 or i== 7 */
1523 sprintf(buffer, fmt[i] , get_old_ide_name(major, minor), ptr + 4);
1525 /* 9 == ide/host/mt */
1527 sprintf(buffer, fmt[i], ptr + 2, minor & 0x7f);
1531 sprintf(buffer, fmt[i], devname + 4);
1532 if (buffer[3] == '0')
1537 pty1 = "pqrstuvwxyzabcde";
1538 pty2 = "0123456789abcdef";
1539 indexx = atoi(devname + 5);
1540 sprintf(buffer, fmt[i], (devname[4] == 'm') ? 'p' : 't', pty1[indexx >> 4], pty2[indexx & 0x0f]);
1543 } /* End Function get_old_name */
1545 static char get_old_ide_name(unsigned int major, unsigned int minor)
1546 /* [SUMMARY] Get the old IDE name for a device.
1547 <major> The major number for the device.
1548 <minor> The minor number for the device.
1549 [RETURNS] The drive letter.
1552 char letter = 'y'; /* 121 */
1553 char c = 'a'; /* 97 */
1556 /* I hope it works like the previous code as it saves a few bytes. Tito ;P */
1558 if (i == IDE0_MAJOR || i == IDE1_MAJOR || i == IDE2_MAJOR
1559 || i == IDE3_MAJOR || i == IDE4_MAJOR || i == IDE5_MAJOR
1560 || i == IDE6_MAJOR || i == IDE7_MAJOR || i == IDE8_MAJOR
1563 if ((unsigned int)i == major) {
1570 } while (i <= IDE9_MAJOR);
1575 } /* End Function get_old_ide_name */
1577 static char *write_old_sd_name(char *buffer,
1578 unsigned int major, unsigned int minor,
1580 /* [SUMMARY] Write the old SCSI disc name to a buffer.
1581 <buffer> The buffer to write to.
1582 <major> The major number for the device.
1583 <minor> The minor number for the device.
1584 <part> The partition string. Must be "" for a whole-disc entry.
1585 [RETURNS] A pointer to the buffer on success, else NULL.
1588 unsigned int disc_index;
1591 sprintf(buffer, "sd%c%s", 'a' + (minor >> 4), part);
1594 if ((major > 64) && (major < 72)) {
1595 disc_index = ((major - 64) << 4) +(minor >> 4);
1596 if (disc_index < 26)
1597 sprintf(buffer, "sd%c%s", 'a' + disc_index, part);
1599 sprintf(buffer, "sd%c%c%s", 'a' +(disc_index / 26) - 1, 'a' + disc_index % 26, part);
1603 } /* End Function write_old_sd_name */
1608 /*EXPERIMENTAL_FUNCTION*/
1610 int st_expr_expand(char *output, unsigned int length, const char *input,
1611 const char *(*get_variable_func)(const char *variable,
1614 /* [SUMMARY] Expand an expression using Borne Shell-like unquoted rules.
1615 <output> The output expanded expression is written here.
1616 <length> The size of the output buffer.
1617 <input> The input expression. This may equal <<output>>.
1618 <get_variable> A function which will be used to get variable values. If
1619 this returns NULL, the environment is searched instead. If this is NULL,
1620 only the environment is searched.
1621 <info> An arbitrary pointer passed to <<get_variable>>.
1622 [RETURNS] TRUE on success, else FALSE.
1627 unsigned int out_pos = 0;
1630 struct passwd *pwent;
1631 char buffer[BUFFER_SIZE], tmp[STRING_LENGTH];
1633 if (length > BUFFER_SIZE)
1634 length = BUFFER_SIZE;
1635 for (; TRUE; ++input) {
1636 switch (ch = *input) {
1638 /* Variable expansion */
1639 input = expand_variable(buffer, length, &out_pos, ++input, get_variable_func, info);
1644 /* Home directory expansion */
1646 if (isspace(ch) ||(ch == '/') ||(ch == '\0')) {
1647 /* User's own home directory: leave separator for next time */
1648 env = getenv("HOME");
1650 info_logger(LOG_INFO, bb_msg_variable_not_found, "HOME");
1654 if (len + out_pos >= length)
1655 goto st_expr_expand_out;
1656 memcpy(buffer + out_pos, env, len + 1);
1660 /* Someone else's home directory */
1661 for (ptr = ++input; !isspace(ch) && (ch != '/') && (ch != '\0'); ch = *++ptr)
1664 if (len >= sizeof tmp)
1665 goto st_expr_expand_out;
1666 safe_memcpy(tmp, input, len);
1668 pwent = getpwnam(tmp);
1669 if (pwent == NULL) {
1670 info_logger(LOG_INFO, "no pwent for: %s", tmp);
1673 len = strlen(pwent->pw_dir);
1674 if (len + out_pos >= length)
1675 goto st_expr_expand_out;
1676 memcpy(buffer + out_pos, pwent->pw_dir, len + 1);
1682 if (out_pos >= length)
1683 goto st_expr_expand_out;
1684 buffer[out_pos++] = ch;
1686 memcpy(output, buffer, out_pos);
1695 info_logger(LOG_INFO, bb_msg_small_buffer);
1697 } /* End Function st_expr_expand */
1700 /* Private functions follow */
1702 static const char *expand_variable(char *buffer, unsigned int length,
1703 unsigned int *out_pos, const char *input,
1704 const char *(*func)(const char *variable,
1707 /* [SUMMARY] Expand a variable.
1708 <buffer> The buffer to write to.
1709 <length> The length of the output buffer.
1710 <out_pos> The current output position. This is updated.
1711 <input> A pointer to the input character pointer.
1712 <func> A function which will be used to get variable values. If this
1713 returns NULL, the environment is searched instead. If this is NULL, only
1714 the environment is searched.
1715 <info> An arbitrary pointer passed to <<func>>.
1716 <errfp> Diagnostic messages are written here.
1717 [RETURNS] A pointer to the end of this subexpression on success, else NULL.
1722 unsigned int open_braces;
1723 const char *env, *ptr;
1724 char tmp[STRING_LENGTH];
1728 /* Special case for "$$": PID */
1729 sprintf(tmp, "%d", (int) getpid());
1731 if (len + *out_pos >= length)
1732 goto expand_variable_out;
1734 memcpy(buffer + *out_pos, tmp, len + 1);
1738 /* Ordinary variable expansion, possibly in braces */
1740 /* Simple variable expansion */
1741 for (ptr = input; isalnum(ch) || (ch == '_') || (ch == ':'); ch = *++ptr)
1744 if ((size_t)len >= sizeof tmp)
1745 goto expand_variable_out;
1747 safe_memcpy(tmp, input, len);
1749 env = get_variable_v2(tmp, func, info);
1751 info_logger(LOG_INFO, bb_msg_variable_not_found, tmp);
1755 if (len + *out_pos >= length)
1756 goto expand_variable_out;
1758 memcpy(buffer + *out_pos, env, len + 1);
1762 /* Variable in braces: check for ':' tricks */
1764 for (ptr = input; isalnum(ch) || (ch == '_'); ch = *++ptr)
1767 /* Must be simple variable expansion with "${var}" */
1769 if ((size_t)len >= sizeof tmp)
1770 goto expand_variable_out;
1772 safe_memcpy(tmp, input, len);
1773 ptr = expand_variable(buffer, length, out_pos, tmp, func, info);
1778 if (ch != ':' || ptr[1] != '-') {
1779 info_logger(LOG_INFO, "illegal char in var name");
1782 /* It's that handy "${var:-word}" expression. Check if var is defined */
1784 if ((size_t)len >= sizeof tmp)
1785 goto expand_variable_out;
1787 safe_memcpy(tmp, input, len);
1788 /* Move input pointer to ':' */
1790 /* First skip to closing brace, taking note of nested expressions */
1793 for (open_braces = 1; open_braces > 0; ch = *++ptr) {
1802 info_logger(LOG_INFO, "\"}\" not found in: %s", input);
1809 /* At this point ptr should point to closing brace of "${var:-word}" */
1810 env = get_variable_v2(tmp, func, info);
1812 /* Found environment variable, so skip the input to the closing brace
1813 and return the variable */
1816 if (len + *out_pos >= length)
1817 goto expand_variable_out;
1819 memcpy(buffer + *out_pos, env, len + 1);
1823 /* Environment variable was not found, so process word. Advance input
1824 pointer to start of word in "${var:-word}" */
1827 if ((size_t)len >= sizeof tmp)
1828 goto expand_variable_out;
1830 safe_memcpy(tmp, input, len);
1832 if (!st_expr_expand(tmp, STRING_LENGTH, tmp, func, info))
1835 if (len + *out_pos >= length)
1836 goto expand_variable_out;
1838 memcpy(buffer + *out_pos, tmp, len + 1);
1841 expand_variable_out:
1842 info_logger(LOG_INFO, bb_msg_small_buffer);
1844 } /* End Function expand_variable */
1847 static const char *get_variable_v2(const char *variable,
1848 const char *(*func)(const char *variable, void *info),
1850 /* [SUMMARY] Get a variable from the environment or .
1851 <variable> The variable name.
1852 <func> A function which will be used to get the variable. If this returns
1853 NULL, the environment is searched instead. If this is NULL, only the
1854 environment is searched.
1855 [RETURNS] The value of the variable on success, else NULL.
1861 value = (*func)(variable, info);
1865 return getenv(variable);
1866 } /* End Function get_variable */