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 config. Do not poll for events.
92 //config:config DEVFSD_VERBOSE
93 //config: bool "Increases logging (and size)"
95 //config: depends on DEVFSD
97 //config: Increases logging to stderr or syslog.
99 //config:config FEATURE_DEVFS
100 //config: bool "Use devfs names for all devices (obsolete)"
102 //config: select PLATFORM_LINUX
104 //config: This is obsolete and should NOT be used anymore.
105 //config: Use linux >= 2.6 (optionally with hotplug) and mdev instead!
107 //config: For legacy systems -- if there is no way around devfsd -- this
108 //config: tells busybox to look for names like /dev/loop/0 instead of
109 //config: /dev/loop0. If your /dev directory has normal names instead of
110 //config: devfs names, you don't want this.
112 //applet:IF_DEVFSD(APPLET(devfsd, BB_DIR_SBIN, BB_SUID_DROP))
114 //kbuild:lib-$(CONFIG_DEVFSD) += devfsd.o
116 //usage:#define devfsd_trivial_usage
117 //usage: "mntpnt [-v]" IF_DEVFSD_FG_NP("[-fg][-np]")
118 //usage:#define devfsd_full_usage "\n\n"
119 //usage: "Manage devfs permissions and old device name symlinks\n"
120 //usage: "\n mntpnt The mount point where devfs is mounted"
121 //usage: "\n -v Print the protocol version numbers for devfsd"
122 //usage: "\n and the kernel-side protocol version and exit"
123 //usage: IF_DEVFSD_FG_NP(
124 //usage: "\n -fg Run in foreground"
125 //usage: "\n -np Exit after parsing the configuration file"
126 //usage: "\n and processing synthetic REGISTER events,"
127 //usage: "\n don't poll for events"
135 #include <sys/sysmacros.h>
137 /* Various defines taken from linux/major.h */
139 #define IDE1_MAJOR 22
140 #define IDE2_MAJOR 33
141 #define IDE3_MAJOR 34
142 #define IDE4_MAJOR 56
143 #define IDE5_MAJOR 57
144 #define IDE6_MAJOR 88
145 #define IDE7_MAJOR 89
146 #define IDE8_MAJOR 90
147 #define IDE9_MAJOR 91
150 /* Various defines taken from linux/devfs_fs.h */
151 #define DEVFSD_PROTOCOL_REVISION_KERNEL 5
152 #define DEVFSD_IOCTL_BASE 'd'
153 /* These are the various ioctls */
154 #define DEVFSDIOC_GET_PROTO_REV _IOR(DEVFSD_IOCTL_BASE, 0, int)
155 #define DEVFSDIOC_SET_EVENT_MASK _IOW(DEVFSD_IOCTL_BASE, 2, int)
156 #define DEVFSDIOC_RELEASE_EVENT_QUEUE _IOW(DEVFSD_IOCTL_BASE, 3, int)
157 #define DEVFSDIOC_SET_CONFIG_DEBUG_MASK _IOW(DEVFSD_IOCTL_BASE, 4, int)
158 #define DEVFSD_NOTIFY_REGISTERED 0
159 #define DEVFSD_NOTIFY_UNREGISTERED 1
160 #define DEVFSD_NOTIFY_ASYNC_OPEN 2
161 #define DEVFSD_NOTIFY_CLOSE 3
162 #define DEVFSD_NOTIFY_LOOKUP 4
163 #define DEVFSD_NOTIFY_CHANGE 5
164 #define DEVFSD_NOTIFY_CREATE 6
165 #define DEVFSD_NOTIFY_DELETE 7
166 #define DEVFS_PATHLEN 1024
167 /* Never change this otherwise the binary interface will change */
169 struct devfsd_notify_struct {
170 /* Use native C types to ensure same types in kernel and user space */
171 unsigned int type; /* DEVFSD_NOTIFY_* value */
172 unsigned int mode; /* Mode of the inode or device entry */
173 unsigned int major; /* Major number of device entry */
174 unsigned int minor; /* Minor number of device entry */
175 unsigned int uid; /* Uid of process, inode or device entry */
176 unsigned int gid; /* Gid of process, inode or device entry */
177 unsigned int overrun_count; /* Number of lost events */
178 unsigned int namelen; /* Number of characters not including '\0' */
179 /* The device name MUST come last */
180 char devname[DEVFS_PATHLEN]; /* This will be '\0' terminated */
183 #define BUFFER_SIZE 16384
184 #define DEVFSD_VERSION "1.3.25"
185 #define CONFIG_FILE "/etc/devfsd.conf"
186 #define MODPROBE "/sbin/modprobe"
187 #define MODPROBE_SWITCH_1 "-k"
188 #define MODPROBE_SWITCH_2 "-C"
189 #define CONFIG_MODULES_DEVFS "/etc/modules.devfs"
190 #define MAX_ARGS (6 + 1)
191 #define MAX_SUBEXPR 10
192 #define STRING_LENGTH 255
194 /* for get_uid_gid() */
198 /* fork_and_execute() */
202 /* for dir_operation() */
205 #define READ_CONFIG 2
207 /* Update only after changing code to reflect new protocol */
208 #define DEVFSD_PROTOCOL_REVISION_DAEMON 5
210 /* Compile-time check */
211 #if DEVFSD_PROTOCOL_REVISION_KERNEL != DEVFSD_PROTOCOL_REVISION_DAEMON
212 #error protocol version mismatch. Update your kernel headers
215 #define AC_PERMISSIONS 0
218 #define AC_MFUNCTION 3 /* not supported by busybox */
219 #define AC_CFUNCTION 4 /* not supported by busybox */
222 #define AC_MKOLDCOMPAT 7
223 #define AC_MKNEWCOMPAT 8
224 #define AC_RMOLDCOMPAT 9
225 #define AC_RMNEWCOMPAT 10
226 #define AC_RESTORE 11
228 struct permissions_type {
234 struct execute_type {
235 char *argv[MAX_ARGS + 1]; /* argv[0] must always be the programme */
240 const char *destination;
248 struct config_entry_struct {
249 struct action_type action;
253 struct permissions_type permissions;
254 struct execute_type execute;
255 struct copy_type copy;
258 struct config_entry_struct *next;
261 struct get_variable_info {
262 const struct devfsd_notify_struct *info;
264 char devpath[STRING_LENGTH];
267 static void dir_operation(int , const char * , int, unsigned long*);
268 static void service(struct stat statbuf, char *path);
269 static int st_expr_expand(char *, unsigned, const char *, const char *(*)(const char *, void *), void *);
270 static const char *get_old_name(const char *, unsigned, char *, unsigned, unsigned);
271 static int mksymlink(const char *oldpath, const char *newpath);
272 static void read_config_file(char *path, int optional, unsigned long *event_mask);
273 static void process_config_line(const char *, unsigned long *);
274 static int do_servicing(int, unsigned long);
275 static void service_name(const struct devfsd_notify_struct *);
276 static void action_permissions(const struct devfsd_notify_struct *, const struct config_entry_struct *);
277 static void action_execute(const struct devfsd_notify_struct *, const struct config_entry_struct *,
278 const regmatch_t *, unsigned);
279 static void action_modload(const struct devfsd_notify_struct *info, const struct config_entry_struct *entry);
280 static void action_copy(const struct devfsd_notify_struct *, const struct config_entry_struct *,
281 const regmatch_t *, unsigned);
282 static void action_compat(const struct devfsd_notify_struct *, unsigned);
283 static void free_config(void);
284 static void restore(char *spath, struct stat source_stat, int rootlen);
285 static int copy_inode(const char *, const struct stat *, mode_t, const char *, const struct stat *);
286 static mode_t get_mode(const char *);
287 static void signal_handler(int);
288 static const char *get_variable(const char *, void *);
289 static int make_dir_tree(const char *);
290 static int expand_expression(char *, unsigned, const char *, const char *(*)(const char *, void *), void *,
291 const char *, const regmatch_t *, unsigned);
292 static void expand_regexp(char *, size_t, const char *, const char *, const regmatch_t *, unsigned);
293 static const char *expand_variable( char *, unsigned, unsigned *, const char *,
294 const char *(*)(const char *, void *), void *);
295 static const char *get_variable_v2(const char *, const char *(*)(const char *, void *), void *);
296 static char get_old_ide_name(unsigned, unsigned);
297 static char *write_old_sd_name(char *, unsigned, unsigned, const char *);
299 /* busybox functions */
300 static int get_uid_gid(int flag, const char *string);
301 static void safe_memcpy(char * dest, const char * src, int len);
302 static unsigned int scan_dev_name_common(const char *d, unsigned int n, int addendum, const char *ptr);
303 static unsigned int scan_dev_name(const char *d, unsigned int n, const char *ptr);
305 /* Structs and vars */
306 static struct config_entry_struct *first_config = NULL;
307 static struct config_entry_struct *last_config = NULL;
308 static char *mount_point = NULL;
309 static volatile int caught_signal = FALSE;
310 static volatile int caught_sighup = FALSE;
311 static struct initial_symlink_struct {
314 } initial_symlinks[] = {
315 {"/proc/self/fd", "fd"},
322 static struct event_type {
323 unsigned int type; /* The DEVFSD_NOTIFY_* value */
324 const char *config_name; /* The name used in the config file */
326 {DEVFSD_NOTIFY_REGISTERED, "REGISTER"},
327 {DEVFSD_NOTIFY_UNREGISTERED, "UNREGISTER"},
328 {DEVFSD_NOTIFY_ASYNC_OPEN, "ASYNC_OPEN"},
329 {DEVFSD_NOTIFY_CLOSE, "CLOSE"},
330 {DEVFSD_NOTIFY_LOOKUP, "LOOKUP"},
331 {DEVFSD_NOTIFY_CHANGE, "CHANGE"},
332 {DEVFSD_NOTIFY_CREATE, "CREATE"},
333 {DEVFSD_NOTIFY_DELETE, "DELETE"},
337 /* Busybox messages */
339 static const char bb_msg_proto_rev[] ALIGN1 = "protocol revision";
340 static const char bb_msg_bad_config[] ALIGN1 = "bad %s config file: %s";
341 static const char bb_msg_small_buffer[] ALIGN1 = "buffer too small";
342 static const char bb_msg_variable_not_found[] ALIGN1 = "variable: %s not found";
345 #if ENABLE_DEVFSD_VERBOSE || ENABLE_DEBUG
346 #define info_logger(p, fmt, args...) bb_error_msg(fmt, ## args)
347 #define msg_logger(p, fmt, args...) bb_error_msg(fmt, ## args)
348 #define msg_logger_and_die(p, fmt, args...) bb_error_msg_and_die(fmt, ## args)
349 #define error_logger(p, fmt, args...) bb_perror_msg(fmt, ## args)
350 #define error_logger_and_die(p, fmt, args...) bb_perror_msg_and_die(fmt, ## args)
352 #define info_logger(p, fmt, args...)
353 #define msg_logger(p, fmt, args...)
354 #define msg_logger_and_die(p, fmt, args...) exit(EXIT_FAILURE)
355 #define error_logger(p, fmt, args...)
356 #define error_logger_and_die(p, fmt, args...) exit(EXIT_FAILURE)
359 static void safe_memcpy(char *dest, const char *src, int len)
361 memcpy(dest , src, len);
365 static unsigned int scan_dev_name_common(const char *d, unsigned int n, int addendum, const char *ptr)
367 if (d[n - 4] == 'd' && d[n - 3] == 'i' && d[n - 2] == 's' && d[n - 1] == 'c')
369 if (d[n - 2] == 'c' && d[n - 1] == 'd')
371 if (ptr[0] == 'p' && ptr[1] == 'a' && ptr[2] == 'r' && ptr[3] == 't')
373 if (ptr[n - 2] == 'm' && ptr[n - 1] == 't')
378 static unsigned int scan_dev_name(const char *d, unsigned int n, const char *ptr)
380 if (d[0] == 's' && d[1] == 'c' && d[2] == 's' && d[3] == 'i' && d[4] == '/') {
381 if (d[n - 7] == 'g' && d[n - 6] == 'e' && d[n - 5] == 'n'
382 && d[n - 4] == 'e' && d[n - 3] == 'r' && d[n - 2] == 'i' && d[n - 1] == 'c'
385 return scan_dev_name_common(d, n, 0, ptr);
387 if (d[0] == 'i' && d[1] == 'd' && d[2] == 'e' && d[3] == '/'
388 && d[4] == 'h' && d[5] == 'o' && d[6] == 's' && d[7] == 't'
390 return scan_dev_name_common(d, n, 4, ptr);
391 if (d[0] == 's' && d[1] == 'b' && d[2] == 'p' && d[3] == '/')
393 if (d[0] == 'v' && d[1] == 'c' && d[2] == 'c' && d[3] == '/')
395 if (d[0] == 'p' && d[1] == 't' && d[2] == 'y' && d[3] == '/')
400 /* Public functions follow */
402 int devfsd_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
403 int devfsd_main(int argc, char **argv)
405 int print_version = FALSE;
406 int do_daemon = TRUE;
407 int no_polling = FALSE;
409 int fd, proto_rev, count;
410 unsigned long event_mask = 0;
411 struct sigaction new_action;
412 struct initial_symlink_struct *curr;
417 for (count = 2; count < argc; ++count) {
418 if (argv[count][0] == '-') {
419 if (argv[count][1] == 'v' && !argv[count][2]) /* -v */
420 print_version = TRUE;
421 else if (ENABLE_DEVFSD_FG_NP && argv[count][1] == 'f'
422 && argv[count][2] == 'g' && !argv[count][3]) /* -fg */
424 else if (ENABLE_DEVFSD_FG_NP && argv[count][1] == 'n'
425 && argv[count][2] == 'p' && !argv[count][3]) /* -np */
432 mount_point = bb_simplify_path(argv[1]);
436 fd = xopen(".devfsd", O_RDONLY);
437 close_on_exec_on(fd);
438 xioctl(fd, DEVFSDIOC_GET_PROTO_REV, &proto_rev);
440 /*setup initial entries */
441 for (curr = initial_symlinks; curr->dest != NULL; ++curr)
442 symlink(curr->dest, curr->name);
444 /* NB: The check for CONFIG_FILE is done in read_config_file() */
446 if (print_version || (DEVFSD_PROTOCOL_REVISION_DAEMON != proto_rev)) {
447 printf("%s v%s\nDaemon %s:\t%d\nKernel-side %s:\t%d\n",
448 applet_name, DEVFSD_VERSION, bb_msg_proto_rev,
449 DEVFSD_PROTOCOL_REVISION_DAEMON, bb_msg_proto_rev, proto_rev);
450 if (DEVFSD_PROTOCOL_REVISION_DAEMON != proto_rev)
451 bb_error_msg_and_die("%s mismatch!", bb_msg_proto_rev);
452 exit(EXIT_SUCCESS); /* -v */
454 /* Tell kernel we are special(i.e. we get to see hidden entries) */
455 xioctl(fd, DEVFSDIOC_SET_EVENT_MASK, 0);
457 /* Set up SIGHUP and SIGUSR1 handlers */
458 sigemptyset(&new_action.sa_mask);
459 new_action.sa_flags = 0;
460 new_action.sa_handler = signal_handler;
461 sigaction_set(SIGHUP, &new_action);
462 sigaction_set(SIGUSR1, &new_action);
464 printf("%s v%s started for %s\n", applet_name, DEVFSD_VERSION, mount_point);
466 /* Set umask so that mknod(2), open(2) and mkdir(2) have complete control over permissions */
468 read_config_file((char*)CONFIG_FILE, FALSE, &event_mask);
469 /* Do the scan before forking, so that boot scripts see the finished product */
470 dir_operation(SERVICE, mount_point, 0, NULL);
472 if (ENABLE_DEVFSD_FG_NP && no_polling)
475 if (ENABLE_DEVFSD_VERBOSE || ENABLE_DEBUG)
476 logmode = LOGMODE_BOTH;
477 else if (do_daemon == TRUE)
478 logmode = LOGMODE_SYSLOG;
479 /* This is the default */
481 logmode = LOGMODE_STDIO; */
484 /* Release so that the child can grab it */
485 xioctl(fd, DEVFSDIOC_RELEASE_EVENT_QUEUE, 0);
486 bb_daemonize_or_rexec(0, argv);
487 } else if (ENABLE_DEVFSD_FG_NP) {
488 setpgid(0, 0); /* Become process group leader */
492 do_scan = do_servicing(fd, event_mask);
495 read_config_file((char*)CONFIG_FILE, FALSE, &event_mask);
497 dir_operation(SERVICE, mount_point, 0, NULL);
499 if (ENABLE_FEATURE_CLEAN_UP) free(mount_point);
500 } /* End Function main */
503 /* Private functions follow */
505 static void read_config_file(char *path, int optional, unsigned long *event_mask)
506 /* [SUMMARY] Read a configuration database.
507 <path> The path to read the database from. If this is a directory, all
508 entries in that directory will be read(except hidden entries).
509 <optional> If TRUE, the routine will silently ignore a missing config file.
510 <event_mask> The event mask is written here. This is not initialised.
516 char buf[STRING_LENGTH];
520 if (stat(path, &statbuf) == 0) {
521 /* Don't read 0 length files: ignored */
522 /*if (statbuf.st_size == 0)
524 if (S_ISDIR(statbuf.st_mode)) {
525 p = bb_simplify_path(path);
526 dir_operation(READ_CONFIG, p, 0, event_mask);
530 fp = fopen_for_read(path);
532 while (fgets(buf, STRING_LENGTH, fp) != NULL) {
533 /* Skip whitespace */
535 line = skip_whitespace(line);
536 if (line[0] == '\0' || line[0] == '#')
538 process_config_line(line, event_mask);
542 goto read_config_file_err;
545 read_config_file_err:
546 if (optional == 0 && errno == ENOENT)
547 error_logger_and_die(LOG_ERR, "read config file: %s", path);
549 } /* End Function read_config_file */
551 static void process_config_line(const char *line, unsigned long *event_mask)
552 /* [SUMMARY] Process a line from a configuration file.
553 <line> The configuration line.
554 <event_mask> The event mask is written here. This is not initialised.
559 struct config_entry_struct *new;
560 char p[MAX_ARGS][STRING_LENGTH];
561 char when[STRING_LENGTH], what[STRING_LENGTH];
562 char name[STRING_LENGTH];
563 const char *msg = "";
567 /* !!!! Only Uppercase Keywords in devsfd.conf */
568 static const char options[] ALIGN1 =
569 "CLEAR_CONFIG\0""INCLUDE\0""OPTIONAL_INCLUDE\0"
570 "RESTORE\0""PERMISSIONS\0""MODLOAD\0""EXECUTE\0"
571 "COPY\0""IGNORE\0""MKOLDCOMPAT\0""MKNEWCOMPAT\0"
572 "RMOLDCOMPAT\0""RMNEWCOMPAT\0";
574 for (count = 0; count < MAX_ARGS; ++count)
576 num_args = sscanf(line, "%s %s %s %s %s %s %s %s %s %s",
578 p[0], p[1], p[2], p[3], p[4], p[5], p[6]);
580 i = index_in_strings(options, when);
590 goto process_config_line_err;
592 /* "INCLUDE" & "OPTIONAL_INCLUDE" */
593 if (i == 1 || i == 2) {
594 st_expr_expand(name, STRING_LENGTH, name, get_variable, NULL);
595 info_logger(LOG_INFO, "%sinclude: %s", (toupper(when[0]) == 'I') ? "": "optional_", name);
596 read_config_file(name, (toupper(when[0]) == 'I') ? FALSE : TRUE, event_mask);
601 dir_operation(RESTORE, name, strlen(name),NULL);
605 goto process_config_line_err;
607 new = xzalloc(sizeof *new);
609 for (count = 0; event_types[count].config_name != NULL; ++count) {
610 if (strcasecmp(when, event_types[count].config_name) != 0)
612 new->action.when = event_types[count].type;
615 if (event_types[count].config_name == NULL) {
617 goto process_config_line_err;
620 i = index_in_strings(options, what);
623 case 4: /* "PERMISSIONS" */
624 new->action.what = AC_PERMISSIONS;
625 /* Get user and group */
626 ptr = strchr(p[0], '.');
629 goto process_config_line_err; /*"missing '.' in UID.GID"*/
633 new->u.permissions.uid = get_uid_gid(UID, p[0]);
634 new->u.permissions.gid = get_uid_gid(GID, ptr);
636 new->u.permissions.mode = get_mode(p[1]);
638 case 5: /* MODLOAD */
639 /*This action will pass "/dev/$devname"(i.e. "/dev/" prefixed to
640 the device name) to the module loading facility. In addition,
641 the /etc/modules.devfs configuration file is used.*/
642 if (ENABLE_DEVFSD_MODLOAD)
643 new->action.what = AC_MODLOAD;
645 case 6: /* EXECUTE */
646 new->action.what = AC_EXECUTE;
649 for (count = 0; count < num_args; ++count)
650 new->u.execute.argv[count] = xstrdup(p[count]);
652 new->u.execute.argv[num_args] = NULL;
655 new->action.what = AC_COPY;
658 goto process_config_line_err; /* missing path and function in line */
660 new->u.copy.source = xstrdup(p[0]);
661 new->u.copy.destination = xstrdup(p[1]);
665 case 9: /* MKOLDCOMPAT */
667 case 10: /* MKNEWCOMPAT */
669 case 11:/* RMOLDCOMPAT */
671 case 12: /* RMNEWCOMPAT */
677 new->action.what = i - 2;
681 goto process_config_line_err;
685 xregcomp(&new->preg, name, REG_EXTENDED);
687 *event_mask |= 1 << new->action.when;
689 if (first_config == NULL)
692 last_config->next = new;
696 process_config_line_err:
697 msg_logger_and_die(LOG_ERR, bb_msg_bad_config, msg , line);
698 } /* End Function process_config_line */
700 static int do_servicing(int fd, unsigned long event_mask)
701 /* [SUMMARY] Service devfs changes until a signal is received.
702 <fd> The open control file.
703 <event_mask> The event mask.
704 [RETURNS] TRUE if SIGHUP was caught, else FALSE.
708 struct devfsd_notify_struct info;
710 /* (void*) cast is only in order to match prototype */
711 xioctl(fd, DEVFSDIOC_SET_EVENT_MASK, (void*)event_mask);
712 while (!caught_signal) {
714 bytes = read(fd, (char *) &info, sizeof info);
716 break; /* Must test for this first */
718 continue; /* Yes, the order is important */
724 int c_sighup = caught_sighup;
726 caught_signal = FALSE;
727 caught_sighup = FALSE;
730 msg_logger_and_die(LOG_ERR, "read error on control file");
731 } /* End Function do_servicing */
733 static void service_name(const struct devfsd_notify_struct *info)
734 /* [SUMMARY] Service a single devfs change.
735 <info> The devfs change.
740 regmatch_t mbuf[MAX_SUBEXPR];
741 struct config_entry_struct *entry;
743 if (ENABLE_DEBUG && info->overrun_count > 0)
744 msg_logger(LOG_ERR, "lost %u events", info->overrun_count);
746 /* Discard lookups on "/dev/log" and "/dev/initctl" */
747 if (info->type == DEVFSD_NOTIFY_LOOKUP
748 && ((info->devname[0] == 'l' && info->devname[1] == 'o'
749 && info->devname[2] == 'g' && !info->devname[3])
750 || (info->devname[0] == 'i' && info->devname[1] == 'n'
751 && info->devname[2] == 'i' && info->devname[3] == 't'
752 && info->devname[4] == 'c' && info->devname[5] == 't'
753 && info->devname[6] == 'l' && !info->devname[7]))
757 for (entry = first_config; entry != NULL; entry = entry->next) {
758 /* First check if action matches the type, then check if name matches */
759 if (info->type != entry->action.when
760 || regexec(&entry->preg, info->devname, MAX_SUBEXPR, mbuf, 0) != 0)
762 for (n = 0;(n < MAX_SUBEXPR) && (mbuf[n].rm_so != -1); ++n)
765 switch (entry->action.what) {
767 action_permissions(info, entry);
770 if (ENABLE_DEVFSD_MODLOAD)
771 action_modload(info, entry);
774 action_execute(info, entry, mbuf, n);
777 action_copy(info, entry, mbuf, n);
786 action_compat(info, entry->action.what);
789 msg_logger_and_die(LOG_ERR, "Unknown action");
792 } /* End Function service_name */
794 static void action_permissions(const struct devfsd_notify_struct *info,
795 const struct config_entry_struct *entry)
796 /* [SUMMARY] Update permissions for a device entry.
797 <info> The devfs change.
798 <entry> The config file entry.
804 if (stat(info->devname, &statbuf) != 0
805 || chmod(info->devname, (statbuf.st_mode & S_IFMT) | (entry->u.permissions.mode & ~S_IFMT)) != 0
806 || chown(info->devname, entry->u.permissions.uid, entry->u.permissions.gid) != 0
808 error_logger(LOG_ERR, "Can't chmod or chown: %s", info->devname);
809 } /* End Function action_permissions */
811 static void action_modload(const struct devfsd_notify_struct *info,
812 const struct config_entry_struct *entry UNUSED_PARAM)
813 /* [SUMMARY] Load a module.
814 <info> The devfs change.
815 <entry> The config file entry.
821 argv[0] = (char*)MODPROBE;
822 argv[1] = (char*)MODPROBE_SWITCH_1; /* "-k" */
823 argv[2] = (char*)MODPROBE_SWITCH_2; /* "-C" */
824 argv[3] = (char*)CONFIG_MODULES_DEVFS;
825 argv[4] = concat_path_file("/dev", info->devname); /* device */
828 spawn_and_wait(argv);
830 } /* End Function action_modload */
832 static void action_execute(const struct devfsd_notify_struct *info,
833 const struct config_entry_struct *entry,
834 const regmatch_t *regexpr, unsigned int numexpr)
835 /* [SUMMARY] Execute a programme.
836 <info> The devfs change.
837 <entry> The config file entry.
838 <regexpr> The number of subexpression(start, end) offsets within the
840 <numexpr> The number of elements within <<regexpr>>.
845 struct get_variable_info gv_info;
846 char *argv[MAX_ARGS + 1];
847 char largv[MAX_ARGS + 1][STRING_LENGTH];
850 gv_info.devname = info->devname;
851 snprintf(gv_info.devpath, sizeof(gv_info.devpath), "%s/%s", mount_point, info->devname);
852 for (count = 0; entry->u.execute.argv[count] != NULL; ++count) {
853 expand_expression(largv[count], STRING_LENGTH,
854 entry->u.execute.argv[count],
855 get_variable, &gv_info,
856 gv_info.devname, regexpr, numexpr);
857 argv[count] = largv[count];
860 spawn_and_wait(argv);
861 } /* End Function action_execute */
864 static void action_copy(const struct devfsd_notify_struct *info,
865 const struct config_entry_struct *entry,
866 const regmatch_t *regexpr, unsigned int numexpr)
867 /* [SUMMARY] Copy permissions.
868 <info> The devfs change.
869 <entry> The config file entry.
870 <regexpr> This list of subexpression(start, end) offsets within the
872 <numexpr> The number of elements in <<regexpr>>.
877 struct get_variable_info gv_info;
878 struct stat source_stat, dest_stat;
879 char source[STRING_LENGTH], destination[STRING_LENGTH];
882 dest_stat.st_mode = 0;
884 if ((info->type == DEVFSD_NOTIFY_CHANGE) && S_ISLNK(info->mode))
887 gv_info.devname = info->devname;
889 snprintf(gv_info.devpath, sizeof(gv_info.devpath), "%s/%s", mount_point, info->devname);
890 expand_expression(source, STRING_LENGTH, entry->u.copy.source,
891 get_variable, &gv_info, gv_info.devname,
894 expand_expression(destination, STRING_LENGTH, entry->u.copy.destination,
895 get_variable, &gv_info, gv_info.devname,
898 if (!make_dir_tree(destination) || lstat(source, &source_stat) != 0)
900 lstat(destination, &dest_stat);
901 new_mode = source_stat.st_mode & ~S_ISVTX;
902 if (info->type == DEVFSD_NOTIFY_CREATE)
904 else if ((info->type == DEVFSD_NOTIFY_CHANGE) &&(dest_stat.st_mode & S_ISVTX))
906 ret = copy_inode(destination, &dest_stat, new_mode, source, &source_stat);
907 if (ENABLE_DEBUG && ret && (errno != EEXIST))
908 error_logger(LOG_ERR, "copy_inode: %s to %s", source, destination);
909 } /* End Function action_copy */
911 static void action_compat(const struct devfsd_notify_struct *info, unsigned int action)
912 /* [SUMMARY] Process a compatibility request.
913 <info> The devfs change.
914 <action> The action to take.
919 const char *compat_name = NULL;
920 const char *dest_name = info->devname;
922 char compat_buf[STRING_LENGTH], dest_buf[STRING_LENGTH];
923 int mode, host, bus, target, lun;
926 /* 1 to 5 "scsi/" , 6 to 9 "ide/host" */
927 static const char *const fmt[] = {
929 "sg/c%db%dt%du%d", /* scsi/generic */
930 "sd/c%db%dt%du%d", /* scsi/disc */
931 "sr/c%db%dt%du%d", /* scsi/cd */
932 "sd/c%db%dt%du%dp%d", /* scsi/part */
933 "st/c%db%dt%du%dm%d%c", /* scsi/mt */
934 "ide/hd/c%db%dt%du%d", /* ide/host/disc */
935 "ide/cd/c%db%dt%du%d", /* ide/host/cd */
936 "ide/hd/c%db%dt%du%dp%d", /* ide/host/part */
937 "ide/mt/c%db%dt%du%d%s", /* ide/host/mt */
941 /* First construct compatibility name */
945 compat_name = get_old_name(info->devname, info->namelen, compat_buf, info->major, info->minor);
949 ptr = bb_basename(info->devname);
950 i = scan_dev_name(info->devname, info->namelen, ptr);
956 sscanf(info->devname + ((i < 6) ? 5 : 4), "host%d/bus%d/target%d/lun%d/", &host, &bus, &target, &lun);
957 snprintf(dest_buf, sizeof(dest_buf), "../%s", info->devname + (( i > 5) ? 4 : 0));
958 dest_name = dest_buf;
959 compat_name = compat_buf;
962 /* 1 == scsi/generic 2 == scsi/disc 3 == scsi/cd 6 == ide/host/disc 7 == ide/host/cd */
963 if (i == 1 || i == 2 || i == 3 || i == 6 || i ==7)
964 sprintf(compat_buf, fmt[i], host, bus, target, lun);
966 /* 4 == scsi/part 8 == ide/host/part */
967 if (i == 4 || i == 8)
968 sprintf(compat_buf, fmt[i], host, bus, target, lun, atoi(ptr + 4));
972 rewind_ = info->devname[info->namelen - 1];
976 if (ptr[2] == 'l' /*108*/ || ptr[2] == 'm'/*109*/)
977 mode = ptr[2] - 107; /* 1 or 2 */
980 sprintf(compat_buf, fmt[i], host, bus, target, lun, mode, rewind_);
983 /* 9 == ide/host/mt */
985 snprintf(compat_buf, sizeof(compat_buf), fmt[i], host, bus, target, lun, ptr + 2);
987 } /* switch (action) */
989 if (compat_name == NULL)
992 /* Now decide what to do with it */
996 mksymlink(dest_name, compat_name);
1000 ret = unlink(compat_name);
1001 if (ENABLE_DEBUG && ret)
1002 error_logger(LOG_ERR, "unlink: %s", compat_name);
1005 } /* switch (action) */
1006 } /* End Function action_compat */
1008 static void restore(char *spath, struct stat source_stat, int rootlen)
1011 struct stat dest_stat;
1013 dest_stat.st_mode = 0;
1014 dpath = concat_path_file(mount_point, spath + rootlen);
1015 lstat(dpath, &dest_stat);
1017 if (S_ISLNK(source_stat.st_mode) || (source_stat.st_mode & S_ISVTX))
1018 copy_inode(dpath, &dest_stat, (source_stat.st_mode & ~S_ISVTX), spath, &source_stat);
1020 if (S_ISDIR(source_stat.st_mode))
1021 dir_operation(RESTORE, spath, rootlen, NULL);
1025 static int copy_inode(const char *destpath, const struct stat *dest_stat,
1027 const char *sourcepath, const struct stat *source_stat)
1028 /* [SUMMARY] Copy an inode.
1029 <destpath> The destination path. An existing inode may be deleted.
1030 <dest_stat> The destination stat(2) information.
1031 <new_mode> The desired new mode for the destination.
1032 <sourcepath> The source path.
1033 <source_stat> The source stat(2) information.
1034 [RETURNS] TRUE on success, else FALSE.
1037 int source_len, dest_len;
1038 char source_link[STRING_LENGTH], dest_link[STRING_LENGTH];
1040 struct sockaddr_un un_addr;
1041 char symlink_val[STRING_LENGTH];
1043 if ((source_stat->st_mode & S_IFMT) ==(dest_stat->st_mode & S_IFMT)) {
1045 if (S_ISLNK(source_stat->st_mode)) {
1046 source_len = readlink(sourcepath, source_link, STRING_LENGTH - 1);
1047 if ((source_len < 0)
1048 || (dest_len = readlink(destpath, dest_link, STRING_LENGTH - 1)) < 0
1051 source_link[source_len] = '\0';
1052 dest_link[dest_len] = '\0';
1053 if ((source_len != dest_len) || (strcmp(source_link, dest_link) != 0)) {
1055 symlink(source_link, destpath);
1058 } /* Else not a symlink */
1059 chmod(destpath, new_mode & ~S_IFMT);
1060 chown(destpath, source_stat->st_uid, source_stat->st_gid);
1063 /* Different types: unlink and create */
1065 switch (source_stat->st_mode & S_IFMT) {
1067 fd = socket(AF_UNIX, SOCK_STREAM, 0);
1070 un_addr.sun_family = AF_UNIX;
1071 snprintf(un_addr.sun_path, sizeof(un_addr.sun_path), "%s", destpath);
1072 val = bind(fd, (struct sockaddr *) &un_addr, (int) sizeof un_addr);
1074 if (val != 0 || chmod(destpath, new_mode & ~S_IFMT) != 0)
1078 val = readlink(sourcepath, symlink_val, STRING_LENGTH - 1);
1081 symlink_val[val] = '\0';
1082 if (symlink(symlink_val, destpath) == 0)
1086 fd = open(destpath, O_RDONLY | O_CREAT, new_mode & ~S_IFMT);
1090 if (chmod(destpath, new_mode & ~S_IFMT) != 0)
1096 if (mknod(destpath, new_mode, source_stat->st_rdev) != 0)
1100 if (mkdir(destpath, new_mode & ~S_IFMT) != 0)
1103 if (chown(destpath, source_stat->st_uid, source_stat->st_gid) == 0)
1108 } /* End Function copy_inode */
1110 static void free_config(void)
1111 /* [SUMMARY] Free the configuration information.
1115 struct config_entry_struct *c_entry;
1118 for (c_entry = first_config; c_entry != NULL; c_entry = next) {
1121 next = c_entry->next;
1122 regfree(&c_entry->preg);
1123 if (c_entry->action.what == AC_EXECUTE) {
1124 for (count = 0; count < MAX_ARGS; ++count) {
1125 if (c_entry->u.execute.argv[count] == NULL)
1127 free(c_entry->u.execute.argv[count]);
1132 first_config = NULL;
1134 } /* End Function free_config */
1136 static int get_uid_gid(int flag, const char *string)
1137 /* [SUMMARY] Convert a string to a UID or GID value.
1138 <flag> "UID" or "GID".
1139 <string> The string.
1140 [RETURNS] The UID or GID value.
1143 struct passwd *pw_ent;
1144 struct group *grp_ent;
1147 if (isdigit(string[0]) || ((string[0] == '-') && isdigit(string[1])))
1148 return atoi(string);
1150 if (flag == UID && (pw_ent = getpwnam(string)) != NULL)
1151 return pw_ent->pw_uid;
1153 if (ENABLE_DEVFSD_VERBOSE)
1157 if ((grp_ent = getgrnam(string)) != NULL)
1158 return grp_ent->gr_gid;
1159 if (ENABLE_DEVFSD_VERBOSE)
1163 if (ENABLE_DEVFSD_VERBOSE)
1164 msg_logger(LOG_ERR, "unknown %s: %s, defaulting to %cid=0", msg, string, msg[0]);
1166 }/* End Function get_uid_gid */
1168 static mode_t get_mode(const char *string)
1169 /* [SUMMARY] Convert a string to a mode value.
1170 <string> The string.
1171 [RETURNS] The mode value.
1177 if (isdigit(string[0]))
1178 return strtoul(string, NULL, 8);
1179 if (strlen(string) != 9)
1180 msg_logger_and_die(LOG_ERR, "bad mode: %s", string);
1185 if (string[0] == 'r' || string[0] == 'w' || string[0] == 'x')
1191 } /* End Function get_mode */
1193 static void signal_handler(int sig)
1195 caught_signal = TRUE;
1197 caught_sighup = TRUE;
1199 info_logger(LOG_INFO, "Caught signal %d", sig);
1200 } /* End Function signal_handler */
1202 static const char *get_variable(const char *variable, void *info)
1204 static char *hostname;
1206 struct get_variable_info *gv_info = info;
1207 const char *field_names[] = {
1208 "hostname", "mntpt", "devpath", "devname", "uid", "gid", "mode",
1209 NULL, mount_point, gv_info->devpath, gv_info->devname, NULL
1214 hostname = safe_gethostname();
1215 field_names[7] = hostname;
1217 /* index_in_str_array returns i>=0 */
1218 i = index_in_str_array(field_names, variable);
1220 if (i > 6 || i < 0 || (i > 1 && gv_info == NULL))
1222 if (i >= 0 && i <= 3)
1223 return field_names[i + 7];
1226 return auto_string(xasprintf("%u", gv_info->info->uid));
1228 return auto_string(xasprintf("%u", gv_info->info->gid));
1230 return auto_string(xasprintf("%o", gv_info->info->mode));
1231 } /* End Function get_variable */
1233 static void service(struct stat statbuf, char *path)
1235 struct devfsd_notify_struct info;
1237 memset(&info, 0, sizeof info);
1238 info.type = DEVFSD_NOTIFY_REGISTERED;
1239 info.mode = statbuf.st_mode;
1240 info.major = major(statbuf.st_rdev);
1241 info.minor = minor(statbuf.st_rdev);
1242 info.uid = statbuf.st_uid;
1243 info.gid = statbuf.st_gid;
1244 snprintf(info.devname, sizeof(info.devname), "%s", path + strlen(mount_point) + 1);
1245 info.namelen = strlen(info.devname);
1246 service_name(&info);
1247 if (S_ISDIR(statbuf.st_mode))
1248 dir_operation(SERVICE, path, 0, NULL);
1251 static void dir_operation(int type, const char * dir_name, int var, unsigned long *event_mask)
1252 /* [SUMMARY] Scan a directory tree and generate register events on leaf nodes.
1253 <flag> To choose which function to perform
1254 <dp> The directory pointer. This is closed upon completion.
1255 <dir_name> The name of the directory.
1256 <rootlen> string length parameter.
1260 struct stat statbuf;
1265 dp = warn_opendir(dir_name);
1269 while ((de = readdir(dp)) != NULL) {
1271 if (de->d_name && DOT_OR_DOTDOT(de->d_name))
1273 path = concat_path_file(dir_name, de->d_name);
1274 if (lstat(path, &statbuf) == 0) {
1277 service(statbuf, path);
1280 restore(path, statbuf, var);
1283 read_config_file(path, var, event_mask);
1290 } /* End Function do_scan_and_service */
1292 static int mksymlink(const char *oldpath, const char *newpath)
1293 /* [SUMMARY] Create a symlink, creating intervening directories as required.
1294 <oldpath> The string contained in the symlink.
1295 <newpath> The name of the new symlink.
1296 [RETURNS] 0 on success, else -1.
1299 if (!make_dir_tree(newpath))
1302 if (symlink(oldpath, newpath) != 0) {
1303 if (errno != EEXIST)
1307 } /* End Function mksymlink */
1310 static int make_dir_tree(const char *path)
1311 /* [SUMMARY] Creating intervening directories for a path as required.
1312 <path> The full pathname(including the leaf node).
1313 [RETURNS] TRUE on success, else FALSE.
1316 if (bb_make_directory(dirname((char *)path), -1, FILEUTILS_RECUR) == -1)
1319 } /* End Function make_dir_tree */
1321 static int expand_expression(char *output, unsigned int outsize,
1323 const char *(*get_variable_func)(const char *variable, void *info),
1325 const char *devname,
1326 const regmatch_t *ex, unsigned int numexp)
1327 /* [SUMMARY] Expand environment variables and regular subexpressions in string.
1328 <output> The output expanded expression is written here.
1329 <length> The size of the output buffer.
1330 <input> The input expression. This may equal <<output>>.
1331 <get_variable> A function which will be used to get variable values. If
1332 this returns NULL, the environment is searched instead. If this is NULL,
1333 only the environment is searched.
1334 <info> An arbitrary pointer passed to <<get_variable>>.
1335 <devname> Device name; specifically, this is the string that contains all
1336 of the regular subexpressions.
1337 <ex> Array of start / end offsets into info->devname for each subexpression
1338 <numexp> Number of regular subexpressions found in <<devname>>.
1339 [RETURNS] TRUE on success, else FALSE.
1342 char temp[STRING_LENGTH];
1344 if (!st_expr_expand(temp, STRING_LENGTH, input, get_variable_func, info))
1346 expand_regexp(output, outsize, temp, devname, ex, numexp);
1348 } /* End Function expand_expression */
1350 static void expand_regexp(char *output, size_t outsize, const char *input,
1351 const char *devname,
1352 const regmatch_t *ex, unsigned int numex)
1353 /* [SUMMARY] Expand all occurrences of the regular subexpressions \0 to \9.
1354 <output> The output expanded expression is written here.
1355 <outsize> The size of the output buffer.
1356 <input> The input expression. This may NOT equal <<output>>, because
1357 supporting that would require yet another string-copy. However, it's not
1358 hard to write a simple wrapper function to add this functionality for those
1359 few cases that need it.
1360 <devname> Device name; specifically, this is the string that contains all
1361 of the regular subexpressions.
1362 <ex> An array of start and end offsets into <<devname>>, one for each
1364 <numex> Number of subexpressions in the offset-array <<ex>>.
1368 const char last_exp = '0' - 1 + numex;
1371 /* Guarantee NULL termination by writing an explicit '\0' character into
1372 the very last byte */
1374 output[--outsize] = '\0';
1375 /* Copy the input string into the output buffer, replacing '\\' with '\'
1376 and '\0' .. '\9' with subexpressions 0 .. 9, if they exist. Other \x
1377 codes are deleted */
1378 while ((c != '\0') && (outsize != 0)) {
1385 if ((c >= '0') && (c <= last_exp)) {
1386 const regmatch_t *subexp = ex + (c - '0');
1387 unsigned int sublen = subexp->rm_eo - subexp->rm_so;
1389 /* Range checking */
1390 if (sublen > outsize)
1392 strncpy(output, devname + subexp->rm_so, sublen);
1403 } /* End Function expand_regexp */
1406 /* from compat_name.c */
1408 struct translate_struct {
1409 const char *match; /* The string to match to(up to length) */
1410 const char *format; /* Format of output, "%s" takes data past match string,
1411 NULL is effectively "%s"(just more efficient) */
1414 static struct translate_struct translate_table[] =
1417 {"printers/", "lp%s"},
1419 {"parports/", "parport%s"},
1422 {"loop/", "loop%s"},
1423 {"floppy/", "fd%s"},
1425 {"md/", "md%s"}, /* Meta-devices */
1429 {"pg/", "pg%s"}, /* Parallel port generic ATAPI interface*/
1431 {"staliomem/", "staliomem%s"}, /* Stallion serial driver control */
1432 {"tts/E", "ttyE%s"}, /* Stallion serial driver */
1433 {"cua/E", "cue%s"}, /* Stallion serial driver callout */
1434 {"tts/R", "ttyR%s"}, /* Rocketport serial driver */
1435 {"cua/R", "cur%s"}, /* Rocketport serial driver callout */
1436 {"ip2/", "ip2%s"}, /* Computone serial driver control */
1437 {"tts/F", "ttyF%s"}, /* Computone serial driver */
1438 {"cua/F", "cuf%s"}, /* Computone serial driver callout */
1439 {"tts/C", "ttyC%s"}, /* Cyclades serial driver */
1440 {"cua/C", "cub%s"}, /* Cyclades serial driver callout */
1441 {"tts/", "ttyS%s"}, /* Generic serial: must be after others */
1442 {"cua/", "cua%s"}, /* Generic serial: must be after others */
1443 {"input/js", "js%s"}, /* Joystick driver */
1447 const char *get_old_name(const char *devname, unsigned int namelen,
1448 char *buffer, unsigned int major, unsigned int minor)
1449 /* [SUMMARY] Translate a kernel-supplied name into an old name.
1450 <devname> The device name provided by the kernel.
1451 <namelen> The length of the name.
1452 <buffer> A buffer that may be used. This should be at least 128 bytes long.
1453 <major> The major number for the device.
1454 <minor> The minor number for the device.
1455 [RETURNS] A pointer to the old name if known, else NULL.
1458 const char *compat_name = NULL;
1460 struct translate_struct *trans;
1466 /* 1 to 5 "scsi/" , 6 to 9 "ide/host", 10 sbp/, 11 vcc/, 12 pty/ */
1467 static const char *const fmt[] = {
1469 "sg%u", /* scsi/generic */
1470 NULL, /* scsi/disc */
1471 "sr%u", /* scsi/cd */
1472 NULL, /* scsi/part */
1473 "nst%u%c", /* scsi/mt */
1474 "hd%c" , /* ide/host/disc */
1475 "hd%c" , /* ide/host/cd */
1476 "hd%c%s", /* ide/host/part */
1477 "%sht%d", /* ide/host/mt */
1478 "sbpcd%u", /* sbp/ */
1480 "%cty%c%c", /* pty/ */
1484 for (trans = translate_table; trans->match != NULL; ++trans) {
1485 char *after_match = is_prefixed_with(devname, trans->match);
1487 if (trans->format == NULL)
1489 sprintf(buffer, trans->format, after_match);
1494 ptr = bb_basename(devname);
1495 i = scan_dev_name(devname, namelen, ptr);
1497 if (i > 0 && i < 13)
1498 compat_name = buffer;
1502 /* 1 == scsi/generic, 3 == scsi/cd, 10 == sbp/ */
1503 if (i == 1 || i == 3 || i == 10)
1504 sprintf(buffer, fmt[i], minor);
1506 /* 2 ==scsi/disc, 4 == scsi/part */
1507 if (i == 2 || i == 4)
1508 compat_name = write_old_sd_name(buffer, major, minor, ((i == 2) ? "" : (ptr + 4)));
1515 sprintf(buffer, fmt[i], minor & 0x1f, mode);
1516 if (devname[namelen - 1] != 'n')
1519 /* 6 == ide/host/disc, 7 == ide/host/cd, 8 == ide/host/part */
1520 if (i == 6 || i == 7 || i == 8)
1521 /* last arg should be ignored for i == 6 or i== 7 */
1522 sprintf(buffer, fmt[i] , get_old_ide_name(major, minor), ptr + 4);
1524 /* 9 == ide/host/mt */
1526 sprintf(buffer, fmt[i], ptr + 2, minor & 0x7f);
1530 sprintf(buffer, fmt[i], devname + 4);
1531 if (buffer[3] == '0')
1536 pty1 = "pqrstuvwxyzabcde";
1537 pty2 = "0123456789abcdef";
1538 indexx = atoi(devname + 5);
1539 sprintf(buffer, fmt[i], (devname[4] == 'm') ? 'p' : 't', pty1[indexx >> 4], pty2[indexx & 0x0f]);
1542 } /* End Function get_old_name */
1544 static char get_old_ide_name(unsigned int major, unsigned int minor)
1545 /* [SUMMARY] Get the old IDE name for a device.
1546 <major> The major number for the device.
1547 <minor> The minor number for the device.
1548 [RETURNS] The drive letter.
1551 char letter = 'y'; /* 121 */
1552 char c = 'a'; /* 97 */
1555 /* I hope it works like the previous code as it saves a few bytes. Tito ;P */
1557 if (i == IDE0_MAJOR || i == IDE1_MAJOR || i == IDE2_MAJOR
1558 || i == IDE3_MAJOR || i == IDE4_MAJOR || i == IDE5_MAJOR
1559 || i == IDE6_MAJOR || i == IDE7_MAJOR || i == IDE8_MAJOR
1562 if ((unsigned int)i == major) {
1569 } while (i <= IDE9_MAJOR);
1574 } /* End Function get_old_ide_name */
1576 static char *write_old_sd_name(char *buffer,
1577 unsigned int major, unsigned int minor,
1579 /* [SUMMARY] Write the old SCSI disc name to a buffer.
1580 <buffer> The buffer to write to.
1581 <major> The major number for the device.
1582 <minor> The minor number for the device.
1583 <part> The partition string. Must be "" for a whole-disc entry.
1584 [RETURNS] A pointer to the buffer on success, else NULL.
1587 unsigned int disc_index;
1590 sprintf(buffer, "sd%c%s", 'a' + (minor >> 4), part);
1593 if ((major > 64) && (major < 72)) {
1594 disc_index = ((major - 64) << 4) +(minor >> 4);
1595 if (disc_index < 26)
1596 sprintf(buffer, "sd%c%s", 'a' + disc_index, part);
1598 sprintf(buffer, "sd%c%c%s", 'a' +(disc_index / 26) - 1, 'a' + disc_index % 26, part);
1602 } /* End Function write_old_sd_name */
1607 /*EXPERIMENTAL_FUNCTION*/
1609 int st_expr_expand(char *output, unsigned int length, const char *input,
1610 const char *(*get_variable_func)(const char *variable,
1613 /* [SUMMARY] Expand an expression using Borne Shell-like unquoted rules.
1614 <output> The output expanded expression is written here.
1615 <length> The size of the output buffer.
1616 <input> The input expression. This may equal <<output>>.
1617 <get_variable> A function which will be used to get variable values. If
1618 this returns NULL, the environment is searched instead. If this is NULL,
1619 only the environment is searched.
1620 <info> An arbitrary pointer passed to <<get_variable>>.
1621 [RETURNS] TRUE on success, else FALSE.
1626 unsigned int out_pos = 0;
1629 struct passwd *pwent;
1630 char buffer[BUFFER_SIZE], tmp[STRING_LENGTH];
1632 if (length > BUFFER_SIZE)
1633 length = BUFFER_SIZE;
1634 for (; TRUE; ++input) {
1635 switch (ch = *input) {
1637 /* Variable expansion */
1638 input = expand_variable(buffer, length, &out_pos, ++input, get_variable_func, info);
1643 /* Home directory expansion */
1645 if (isspace(ch) ||(ch == '/') ||(ch == '\0')) {
1646 /* User's own home directory: leave separator for next time */
1647 env = getenv("HOME");
1649 info_logger(LOG_INFO, bb_msg_variable_not_found, "HOME");
1653 if (len + out_pos >= length)
1654 goto st_expr_expand_out;
1655 memcpy(buffer + out_pos, env, len + 1);
1659 /* Someone else's home directory */
1660 for (ptr = ++input; !isspace(ch) && (ch != '/') && (ch != '\0'); ch = *++ptr)
1663 if (len >= sizeof tmp)
1664 goto st_expr_expand_out;
1665 safe_memcpy(tmp, input, len);
1667 pwent = getpwnam(tmp);
1668 if (pwent == NULL) {
1669 info_logger(LOG_INFO, "no pwent for: %s", tmp);
1672 len = strlen(pwent->pw_dir);
1673 if (len + out_pos >= length)
1674 goto st_expr_expand_out;
1675 memcpy(buffer + out_pos, pwent->pw_dir, len + 1);
1681 if (out_pos >= length)
1682 goto st_expr_expand_out;
1683 buffer[out_pos++] = ch;
1685 memcpy(output, buffer, out_pos);
1694 info_logger(LOG_INFO, bb_msg_small_buffer);
1696 } /* End Function st_expr_expand */
1699 /* Private functions follow */
1701 static const char *expand_variable(char *buffer, unsigned int length,
1702 unsigned int *out_pos, const char *input,
1703 const char *(*func)(const char *variable,
1706 /* [SUMMARY] Expand a variable.
1707 <buffer> The buffer to write to.
1708 <length> The length of the output buffer.
1709 <out_pos> The current output position. This is updated.
1710 <input> A pointer to the input character pointer.
1711 <func> A function which will be used to get variable values. If this
1712 returns NULL, the environment is searched instead. If this is NULL, only
1713 the environment is searched.
1714 <info> An arbitrary pointer passed to <<func>>.
1715 <errfp> Diagnostic messages are written here.
1716 [RETURNS] A pointer to the end of this subexpression on success, else NULL.
1721 unsigned int open_braces;
1722 const char *env, *ptr;
1723 char tmp[STRING_LENGTH];
1727 /* Special case for "$$": PID */
1728 sprintf(tmp, "%d", (int) getpid());
1730 if (len + *out_pos >= length)
1731 goto expand_variable_out;
1733 memcpy(buffer + *out_pos, tmp, len + 1);
1737 /* Ordinary variable expansion, possibly in braces */
1739 /* Simple variable expansion */
1740 for (ptr = input; isalnum(ch) || (ch == '_') || (ch == ':'); ch = *++ptr)
1743 if ((size_t)len >= sizeof tmp)
1744 goto expand_variable_out;
1746 safe_memcpy(tmp, input, len);
1748 env = get_variable_v2(tmp, func, info);
1750 info_logger(LOG_INFO, bb_msg_variable_not_found, tmp);
1754 if (len + *out_pos >= length)
1755 goto expand_variable_out;
1757 memcpy(buffer + *out_pos, env, len + 1);
1761 /* Variable in braces: check for ':' tricks */
1763 for (ptr = input; isalnum(ch) || (ch == '_'); ch = *++ptr)
1766 /* Must be simple variable expansion with "${var}" */
1768 if ((size_t)len >= sizeof tmp)
1769 goto expand_variable_out;
1771 safe_memcpy(tmp, input, len);
1772 ptr = expand_variable(buffer, length, out_pos, tmp, func, info);
1777 if (ch != ':' || ptr[1] != '-') {
1778 info_logger(LOG_INFO, "illegal char in var name");
1781 /* It's that handy "${var:-word}" expression. Check if var is defined */
1783 if ((size_t)len >= sizeof tmp)
1784 goto expand_variable_out;
1786 safe_memcpy(tmp, input, len);
1787 /* Move input pointer to ':' */
1789 /* First skip to closing brace, taking note of nested expressions */
1792 for (open_braces = 1; open_braces > 0; ch = *++ptr) {
1801 info_logger(LOG_INFO, "\"}\" not found in: %s", input);
1808 /* At this point ptr should point to closing brace of "${var:-word}" */
1809 env = get_variable_v2(tmp, func, info);
1811 /* Found environment variable, so skip the input to the closing brace
1812 and return the variable */
1815 if (len + *out_pos >= length)
1816 goto expand_variable_out;
1818 memcpy(buffer + *out_pos, env, len + 1);
1822 /* Environment variable was not found, so process word. Advance input
1823 pointer to start of word in "${var:-word}" */
1826 if ((size_t)len >= sizeof tmp)
1827 goto expand_variable_out;
1829 safe_memcpy(tmp, input, len);
1831 if (!st_expr_expand(tmp, STRING_LENGTH, tmp, func, info))
1834 if (len + *out_pos >= length)
1835 goto expand_variable_out;
1837 memcpy(buffer + *out_pos, tmp, len + 1);
1840 expand_variable_out:
1841 info_logger(LOG_INFO, bb_msg_small_buffer);
1843 } /* End Function expand_variable */
1846 static const char *get_variable_v2(const char *variable,
1847 const char *(*func)(const char *variable, void *info),
1849 /* [SUMMARY] Get a variable from the environment or .
1850 <variable> The variable name.
1851 <func> A function which will be used to get the variable. If this returns
1852 NULL, the environment is searched instead. If this is NULL, only the
1853 environment is searched.
1854 [RETURNS] The value of the variable on success, else NULL.
1860 value = (*func)(variable, info);
1864 return getenv(variable);
1865 } /* End Function get_variable */