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_info_msg(fmt, ## args)
347 #define simple_info_logger(p, msg) bb_simple_info_msg(msg)
348 #define msg_logger(p, fmt, args...) bb_error_msg(fmt, ## args)
349 #define simple_msg_logger(p, msg) bb_simple_error_msg(msg)
350 #define msg_logger_and_die(p, fmt, args...) bb_error_msg_and_die(fmt, ## args)
351 #define simple_msg_logger_and_die(p, msg) bb_simple_error_msg_and_die(msg)
352 #define error_logger(p, fmt, args...) bb_perror_msg(fmt, ## args)
353 #define error_logger_and_die(p, fmt, args...) bb_perror_msg_and_die(fmt, ## args)
355 #define info_logger(p, fmt, args...)
356 #define simple_info_logger(p, msg)
357 #define msg_logger(p, fmt, args...)
358 #define simple_msg_logger(p, msg)
359 #define msg_logger_and_die(p, fmt, args...) exit(EXIT_FAILURE)
360 #define simple_msg_logger_and_die(p, msg) exit(EXIT_FAILURE)
361 #define error_logger(p, fmt, args...)
362 #define error_logger_and_die(p, fmt, args...) exit(EXIT_FAILURE)
365 static void safe_memcpy(char *dest, const char *src, int len)
367 memcpy(dest , src, len);
371 static unsigned int scan_dev_name_common(const char *d, unsigned int n, int addendum, const char *ptr)
373 if (d[n - 4] == 'd' && d[n - 3] == 'i' && d[n - 2] == 's' && d[n - 1] == 'c')
375 if (d[n - 2] == 'c' && d[n - 1] == 'd')
377 if (ptr[0] == 'p' && ptr[1] == 'a' && ptr[2] == 'r' && ptr[3] == 't')
379 if (ptr[n - 2] == 'm' && ptr[n - 1] == 't')
384 static unsigned int scan_dev_name(const char *d, unsigned int n, const char *ptr)
386 if (d[0] == 's' && d[1] == 'c' && d[2] == 's' && d[3] == 'i' && d[4] == '/') {
387 if (d[n - 7] == 'g' && d[n - 6] == 'e' && d[n - 5] == 'n'
388 && d[n - 4] == 'e' && d[n - 3] == 'r' && d[n - 2] == 'i' && d[n - 1] == 'c'
391 return scan_dev_name_common(d, n, 0, ptr);
393 if (d[0] == 'i' && d[1] == 'd' && d[2] == 'e' && d[3] == '/'
394 && d[4] == 'h' && d[5] == 'o' && d[6] == 's' && d[7] == 't'
396 return scan_dev_name_common(d, n, 4, ptr);
397 if (d[0] == 's' && d[1] == 'b' && d[2] == 'p' && d[3] == '/')
399 if (d[0] == 'v' && d[1] == 'c' && d[2] == 'c' && d[3] == '/')
401 if (d[0] == 'p' && d[1] == 't' && d[2] == 'y' && d[3] == '/')
406 /* Public functions follow */
408 int devfsd_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
409 int devfsd_main(int argc, char **argv)
411 int print_version = FALSE;
412 int do_daemon = TRUE;
413 int no_polling = FALSE;
415 int fd, proto_rev, count;
416 unsigned long event_mask = 0;
417 struct sigaction new_action;
418 struct initial_symlink_struct *curr;
423 for (count = 2; count < argc; ++count) {
424 if (argv[count][0] == '-') {
425 if (argv[count][1] == 'v' && !argv[count][2]) /* -v */
426 print_version = TRUE;
427 else if (ENABLE_DEVFSD_FG_NP && argv[count][1] == 'f'
428 && argv[count][2] == 'g' && !argv[count][3]) /* -fg */
430 else if (ENABLE_DEVFSD_FG_NP && argv[count][1] == 'n'
431 && argv[count][2] == 'p' && !argv[count][3]) /* -np */
438 mount_point = bb_simplify_path(argv[1]);
442 fd = xopen(".devfsd", O_RDONLY);
443 close_on_exec_on(fd);
444 xioctl(fd, DEVFSDIOC_GET_PROTO_REV, &proto_rev);
446 /*setup initial entries */
447 for (curr = initial_symlinks; curr->dest != NULL; ++curr)
448 symlink(curr->dest, curr->name);
450 /* NB: The check for CONFIG_FILE is done in read_config_file() */
452 if (print_version || (DEVFSD_PROTOCOL_REVISION_DAEMON != proto_rev)) {
453 printf("%s v%s\nDaemon %s:\t%d\nKernel-side %s:\t%d\n",
454 applet_name, DEVFSD_VERSION, bb_msg_proto_rev,
455 DEVFSD_PROTOCOL_REVISION_DAEMON, bb_msg_proto_rev, proto_rev);
456 if (DEVFSD_PROTOCOL_REVISION_DAEMON != proto_rev)
457 bb_error_msg_and_die("%s mismatch!", bb_msg_proto_rev);
458 exit(EXIT_SUCCESS); /* -v */
460 /* Tell kernel we are special(i.e. we get to see hidden entries) */
461 xioctl(fd, DEVFSDIOC_SET_EVENT_MASK, 0);
463 /* Set up SIGHUP and SIGUSR1 handlers */
464 sigemptyset(&new_action.sa_mask);
465 new_action.sa_flags = 0;
466 new_action.sa_handler = signal_handler;
467 sigaction_set(SIGHUP, &new_action);
468 sigaction_set(SIGUSR1, &new_action);
470 printf("%s v%s started for %s\n", applet_name, DEVFSD_VERSION, mount_point);
472 /* Set umask so that mknod(2), open(2) and mkdir(2) have complete control over permissions */
474 read_config_file((char*)CONFIG_FILE, FALSE, &event_mask);
475 /* Do the scan before forking, so that boot scripts see the finished product */
476 dir_operation(SERVICE, mount_point, 0, NULL);
478 if (ENABLE_DEVFSD_FG_NP && no_polling)
481 if (ENABLE_DEVFSD_VERBOSE || ENABLE_DEBUG)
482 logmode = LOGMODE_BOTH;
483 else if (do_daemon == TRUE)
484 logmode = LOGMODE_SYSLOG;
485 /* This is the default */
487 logmode = LOGMODE_STDIO; */
490 /* Release so that the child can grab it */
491 xioctl(fd, DEVFSDIOC_RELEASE_EVENT_QUEUE, 0);
492 bb_daemonize_or_rexec(0, argv);
493 } else if (ENABLE_DEVFSD_FG_NP) {
494 setpgid(0, 0); /* Become process group leader */
498 do_scan = do_servicing(fd, event_mask);
501 read_config_file((char*)CONFIG_FILE, FALSE, &event_mask);
503 dir_operation(SERVICE, mount_point, 0, NULL);
505 if (ENABLE_FEATURE_CLEAN_UP) free(mount_point);
506 } /* End Function main */
509 /* Private functions follow */
511 static void read_config_file(char *path, int optional, unsigned long *event_mask)
512 /* [SUMMARY] Read a configuration database.
513 <path> The path to read the database from. If this is a directory, all
514 entries in that directory will be read(except hidden entries).
515 <optional> If TRUE, the routine will silently ignore a missing config file.
516 <event_mask> The event mask is written here. This is not initialised.
522 char buf[STRING_LENGTH];
526 if (stat(path, &statbuf) == 0) {
527 /* Don't read 0 length files: ignored */
528 /*if (statbuf.st_size == 0)
530 if (S_ISDIR(statbuf.st_mode)) {
531 p = bb_simplify_path(path);
532 dir_operation(READ_CONFIG, p, 0, event_mask);
536 fp = fopen_for_read(path);
538 while (fgets(buf, STRING_LENGTH, fp) != NULL) {
539 /* Skip whitespace */
541 line = skip_whitespace(line);
542 if (line[0] == '\0' || line[0] == '#')
544 process_config_line(line, event_mask);
548 goto read_config_file_err;
551 read_config_file_err:
552 if (optional == 0 && errno == ENOENT)
553 error_logger_and_die(LOG_ERR, "read config file: %s", path);
555 } /* End Function read_config_file */
557 static void process_config_line(const char *line, unsigned long *event_mask)
558 /* [SUMMARY] Process a line from a configuration file.
559 <line> The configuration line.
560 <event_mask> The event mask is written here. This is not initialised.
565 struct config_entry_struct *new;
566 char p[MAX_ARGS][STRING_LENGTH];
567 char when[STRING_LENGTH], what[STRING_LENGTH];
568 char name[STRING_LENGTH];
569 const char *msg = "";
573 /* !!!! Only Uppercase Keywords in devsfd.conf */
574 static const char options[] ALIGN1 =
575 "CLEAR_CONFIG\0""INCLUDE\0""OPTIONAL_INCLUDE\0"
576 "RESTORE\0""PERMISSIONS\0""MODLOAD\0""EXECUTE\0"
577 "COPY\0""IGNORE\0""MKOLDCOMPAT\0""MKNEWCOMPAT\0"
578 "RMOLDCOMPAT\0""RMNEWCOMPAT\0";
580 for (count = 0; count < MAX_ARGS; ++count)
582 num_args = sscanf(line, "%s %s %s %s %s %s %s %s %s %s",
584 p[0], p[1], p[2], p[3], p[4], p[5], p[6]);
586 i = index_in_strings(options, when);
596 goto process_config_line_err;
598 /* "INCLUDE" & "OPTIONAL_INCLUDE" */
599 if (i == 1 || i == 2) {
600 st_expr_expand(name, STRING_LENGTH, name, get_variable, NULL);
601 info_logger(LOG_INFO, "%sinclude: %s", (toupper(when[0]) == 'I') ? "": "optional_", name);
602 read_config_file(name, (toupper(when[0]) == 'I') ? FALSE : TRUE, event_mask);
607 dir_operation(RESTORE, name, strlen(name),NULL);
611 goto process_config_line_err;
613 new = xzalloc(sizeof *new);
615 for (count = 0; event_types[count].config_name != NULL; ++count) {
616 if (strcasecmp(when, event_types[count].config_name) != 0)
618 new->action.when = event_types[count].type;
621 if (event_types[count].config_name == NULL) {
623 goto process_config_line_err;
626 i = index_in_strings(options, what);
629 case 4: /* "PERMISSIONS" */
630 new->action.what = AC_PERMISSIONS;
631 /* Get user and group */
632 ptr = strchr(p[0], '.');
635 goto process_config_line_err; /*"missing '.' in UID.GID"*/
639 new->u.permissions.uid = get_uid_gid(UID, p[0]);
640 new->u.permissions.gid = get_uid_gid(GID, ptr);
642 new->u.permissions.mode = get_mode(p[1]);
644 case 5: /* MODLOAD */
645 /*This action will pass "/dev/$devname"(i.e. "/dev/" prefixed to
646 the device name) to the module loading facility. In addition,
647 the /etc/modules.devfs configuration file is used.*/
648 if (ENABLE_DEVFSD_MODLOAD)
649 new->action.what = AC_MODLOAD;
651 case 6: /* EXECUTE */
652 new->action.what = AC_EXECUTE;
655 for (count = 0; count < num_args; ++count)
656 new->u.execute.argv[count] = xstrdup(p[count]);
658 new->u.execute.argv[num_args] = NULL;
661 new->action.what = AC_COPY;
664 goto process_config_line_err; /* missing path and function in line */
666 new->u.copy.source = xstrdup(p[0]);
667 new->u.copy.destination = xstrdup(p[1]);
671 case 9: /* MKOLDCOMPAT */
673 case 10: /* MKNEWCOMPAT */
675 case 11:/* RMOLDCOMPAT */
677 case 12: /* RMNEWCOMPAT */
683 new->action.what = i - 2;
687 goto process_config_line_err;
691 xregcomp(&new->preg, name, REG_EXTENDED);
693 *event_mask |= 1 << new->action.when;
695 if (first_config == NULL)
698 last_config->next = new;
702 process_config_line_err:
703 msg_logger_and_die(LOG_ERR, bb_msg_bad_config, msg, line);
704 } /* End Function process_config_line */
706 static int do_servicing(int fd, unsigned long event_mask)
707 /* [SUMMARY] Service devfs changes until a signal is received.
708 <fd> The open control file.
709 <event_mask> The event mask.
710 [RETURNS] TRUE if SIGHUP was caught, else FALSE.
714 struct devfsd_notify_struct info;
716 /* (void*) cast is only in order to match prototype */
717 xioctl(fd, DEVFSDIOC_SET_EVENT_MASK, (void*)event_mask);
718 while (!caught_signal) {
720 bytes = read(fd, (char *) &info, sizeof info);
722 break; /* Must test for this first */
724 continue; /* Yes, the order is important */
730 int c_sighup = caught_sighup;
732 caught_signal = FALSE;
733 caught_sighup = FALSE;
736 simple_msg_logger_and_die(LOG_ERR, "read error on control file");
737 } /* End Function do_servicing */
739 static void service_name(const struct devfsd_notify_struct *info)
740 /* [SUMMARY] Service a single devfs change.
741 <info> The devfs change.
746 regmatch_t mbuf[MAX_SUBEXPR];
747 struct config_entry_struct *entry;
749 if (ENABLE_DEBUG && info->overrun_count > 0)
750 msg_logger(LOG_ERR, "lost %u events", info->overrun_count);
752 /* Discard lookups on "/dev/log" and "/dev/initctl" */
753 if (info->type == DEVFSD_NOTIFY_LOOKUP
754 && ((info->devname[0] == 'l' && info->devname[1] == 'o'
755 && info->devname[2] == 'g' && !info->devname[3])
756 || (info->devname[0] == 'i' && info->devname[1] == 'n'
757 && info->devname[2] == 'i' && info->devname[3] == 't'
758 && info->devname[4] == 'c' && info->devname[5] == 't'
759 && info->devname[6] == 'l' && !info->devname[7]))
763 for (entry = first_config; entry != NULL; entry = entry->next) {
764 /* First check if action matches the type, then check if name matches */
765 if (info->type != entry->action.when
766 || regexec(&entry->preg, info->devname, MAX_SUBEXPR, mbuf, 0) != 0)
768 for (n = 0;(n < MAX_SUBEXPR) && (mbuf[n].rm_so != -1); ++n)
771 switch (entry->action.what) {
773 action_permissions(info, entry);
776 if (ENABLE_DEVFSD_MODLOAD)
777 action_modload(info, entry);
780 action_execute(info, entry, mbuf, n);
783 action_copy(info, entry, mbuf, n);
792 action_compat(info, entry->action.what);
795 simple_msg_logger_and_die(LOG_ERR, "Unknown action");
798 } /* End Function service_name */
800 static void action_permissions(const struct devfsd_notify_struct *info,
801 const struct config_entry_struct *entry)
802 /* [SUMMARY] Update permissions for a device entry.
803 <info> The devfs change.
804 <entry> The config file entry.
810 if (stat(info->devname, &statbuf) != 0
811 || chmod(info->devname, (statbuf.st_mode & S_IFMT) | (entry->u.permissions.mode & ~S_IFMT)) != 0
812 || chown(info->devname, entry->u.permissions.uid, entry->u.permissions.gid) != 0
814 error_logger(LOG_ERR, "Can't chmod or chown: %s", info->devname);
815 } /* End Function action_permissions */
817 static void action_modload(const struct devfsd_notify_struct *info,
818 const struct config_entry_struct *entry UNUSED_PARAM)
819 /* [SUMMARY] Load a module.
820 <info> The devfs change.
821 <entry> The config file entry.
827 argv[0] = (char*)MODPROBE;
828 argv[1] = (char*)MODPROBE_SWITCH_1; /* "-k" */
829 argv[2] = (char*)MODPROBE_SWITCH_2; /* "-C" */
830 argv[3] = (char*)CONFIG_MODULES_DEVFS;
831 argv[4] = concat_path_file("/dev", info->devname); /* device */
834 spawn_and_wait(argv);
836 } /* End Function action_modload */
838 static void action_execute(const struct devfsd_notify_struct *info,
839 const struct config_entry_struct *entry,
840 const regmatch_t *regexpr, unsigned int numexpr)
841 /* [SUMMARY] Execute a programme.
842 <info> The devfs change.
843 <entry> The config file entry.
844 <regexpr> The number of subexpression(start, end) offsets within the
846 <numexpr> The number of elements within <<regexpr>>.
851 struct get_variable_info gv_info;
852 char *argv[MAX_ARGS + 1];
853 char largv[MAX_ARGS + 1][STRING_LENGTH];
856 gv_info.devname = info->devname;
857 snprintf(gv_info.devpath, sizeof(gv_info.devpath), "%s/%s", mount_point, info->devname);
858 for (count = 0; entry->u.execute.argv[count] != NULL; ++count) {
859 expand_expression(largv[count], STRING_LENGTH,
860 entry->u.execute.argv[count],
861 get_variable, &gv_info,
862 gv_info.devname, regexpr, numexpr);
863 argv[count] = largv[count];
866 spawn_and_wait(argv);
867 } /* End Function action_execute */
870 static void action_copy(const struct devfsd_notify_struct *info,
871 const struct config_entry_struct *entry,
872 const regmatch_t *regexpr, unsigned int numexpr)
873 /* [SUMMARY] Copy permissions.
874 <info> The devfs change.
875 <entry> The config file entry.
876 <regexpr> This list of subexpression(start, end) offsets within the
878 <numexpr> The number of elements in <<regexpr>>.
883 struct get_variable_info gv_info;
884 struct stat source_stat, dest_stat;
885 char source[STRING_LENGTH], destination[STRING_LENGTH];
888 dest_stat.st_mode = 0;
890 if ((info->type == DEVFSD_NOTIFY_CHANGE) && S_ISLNK(info->mode))
893 gv_info.devname = info->devname;
895 snprintf(gv_info.devpath, sizeof(gv_info.devpath), "%s/%s", mount_point, info->devname);
896 expand_expression(source, STRING_LENGTH, entry->u.copy.source,
897 get_variable, &gv_info, gv_info.devname,
900 expand_expression(destination, STRING_LENGTH, entry->u.copy.destination,
901 get_variable, &gv_info, gv_info.devname,
904 if (!make_dir_tree(destination) || lstat(source, &source_stat) != 0)
906 lstat(destination, &dest_stat);
907 new_mode = source_stat.st_mode & ~S_ISVTX;
908 if (info->type == DEVFSD_NOTIFY_CREATE)
910 else if ((info->type == DEVFSD_NOTIFY_CHANGE) &&(dest_stat.st_mode & S_ISVTX))
912 ret = copy_inode(destination, &dest_stat, new_mode, source, &source_stat);
913 if (ENABLE_DEBUG && ret && (errno != EEXIST))
914 error_logger(LOG_ERR, "copy_inode: %s to %s", source, destination);
915 } /* End Function action_copy */
917 static void action_compat(const struct devfsd_notify_struct *info, unsigned int action)
918 /* [SUMMARY] Process a compatibility request.
919 <info> The devfs change.
920 <action> The action to take.
925 const char *compat_name = NULL;
926 const char *dest_name = info->devname;
928 char compat_buf[STRING_LENGTH], dest_buf[STRING_LENGTH];
929 int mode, host, bus, target, lun;
932 /* 1 to 5 "scsi/" , 6 to 9 "ide/host" */
933 static const char *const fmt[] = {
935 "sg/c%db%dt%du%d", /* scsi/generic */
936 "sd/c%db%dt%du%d", /* scsi/disc */
937 "sr/c%db%dt%du%d", /* scsi/cd */
938 "sd/c%db%dt%du%dp%d", /* scsi/part */
939 "st/c%db%dt%du%dm%d%c", /* scsi/mt */
940 "ide/hd/c%db%dt%du%d", /* ide/host/disc */
941 "ide/cd/c%db%dt%du%d", /* ide/host/cd */
942 "ide/hd/c%db%dt%du%dp%d", /* ide/host/part */
943 "ide/mt/c%db%dt%du%d%s", /* ide/host/mt */
947 /* First construct compatibility name */
951 compat_name = get_old_name(info->devname, info->namelen, compat_buf, info->major, info->minor);
955 ptr = bb_basename(info->devname);
956 i = scan_dev_name(info->devname, info->namelen, ptr);
962 sscanf(info->devname + ((i < 6) ? 5 : 4), "host%d/bus%d/target%d/lun%d/", &host, &bus, &target, &lun);
963 snprintf(dest_buf, sizeof(dest_buf), "../%s", info->devname + (( i > 5) ? 4 : 0));
964 dest_name = dest_buf;
965 compat_name = compat_buf;
968 /* 1 == scsi/generic 2 == scsi/disc 3 == scsi/cd 6 == ide/host/disc 7 == ide/host/cd */
969 if (i == 1 || i == 2 || i == 3 || i == 6 || i ==7)
970 sprintf(compat_buf, fmt[i], host, bus, target, lun);
972 /* 4 == scsi/part 8 == ide/host/part */
973 if (i == 4 || i == 8)
974 sprintf(compat_buf, fmt[i], host, bus, target, lun, atoi(ptr + 4));
978 rewind_ = info->devname[info->namelen - 1];
982 if (ptr[2] == 'l' /*108*/ || ptr[2] == 'm'/*109*/)
983 mode = ptr[2] - 107; /* 1 or 2 */
986 sprintf(compat_buf, fmt[i], host, bus, target, lun, mode, rewind_);
989 /* 9 == ide/host/mt */
991 snprintf(compat_buf, sizeof(compat_buf), fmt[i], host, bus, target, lun, ptr + 2);
993 } /* switch (action) */
995 if (compat_name == NULL)
998 /* Now decide what to do with it */
1000 case AC_MKOLDCOMPAT:
1001 case AC_MKNEWCOMPAT:
1002 mksymlink(dest_name, compat_name);
1004 case AC_RMOLDCOMPAT:
1005 case AC_RMNEWCOMPAT:
1006 ret = unlink(compat_name);
1007 if (ENABLE_DEBUG && ret)
1008 error_logger(LOG_ERR, "unlink: %s", compat_name);
1011 } /* switch (action) */
1012 } /* End Function action_compat */
1014 static void restore(char *spath, struct stat source_stat, int rootlen)
1017 struct stat dest_stat;
1019 dest_stat.st_mode = 0;
1020 dpath = concat_path_file(mount_point, spath + rootlen);
1021 lstat(dpath, &dest_stat);
1023 if (S_ISLNK(source_stat.st_mode) || (source_stat.st_mode & S_ISVTX))
1024 copy_inode(dpath, &dest_stat, (source_stat.st_mode & ~S_ISVTX), spath, &source_stat);
1026 if (S_ISDIR(source_stat.st_mode))
1027 dir_operation(RESTORE, spath, rootlen, NULL);
1031 static int copy_inode(const char *destpath, const struct stat *dest_stat,
1033 const char *sourcepath, const struct stat *source_stat)
1034 /* [SUMMARY] Copy an inode.
1035 <destpath> The destination path. An existing inode may be deleted.
1036 <dest_stat> The destination stat(2) information.
1037 <new_mode> The desired new mode for the destination.
1038 <sourcepath> The source path.
1039 <source_stat> The source stat(2) information.
1040 [RETURNS] TRUE on success, else FALSE.
1043 int source_len, dest_len;
1044 char source_link[STRING_LENGTH], dest_link[STRING_LENGTH];
1046 struct sockaddr_un un_addr;
1047 char symlink_val[STRING_LENGTH];
1049 if ((source_stat->st_mode & S_IFMT) ==(dest_stat->st_mode & S_IFMT)) {
1051 if (S_ISLNK(source_stat->st_mode)) {
1052 source_len = readlink(sourcepath, source_link, STRING_LENGTH - 1);
1053 if ((source_len < 0)
1054 || (dest_len = readlink(destpath, dest_link, STRING_LENGTH - 1)) < 0
1057 source_link[source_len] = '\0';
1058 dest_link[dest_len] = '\0';
1059 if ((source_len != dest_len) || (strcmp(source_link, dest_link) != 0)) {
1061 symlink(source_link, destpath);
1064 } /* Else not a symlink */
1065 chmod(destpath, new_mode & ~S_IFMT);
1066 chown(destpath, source_stat->st_uid, source_stat->st_gid);
1069 /* Different types: unlink and create */
1071 switch (source_stat->st_mode & S_IFMT) {
1073 fd = socket(AF_UNIX, SOCK_STREAM, 0);
1076 un_addr.sun_family = AF_UNIX;
1077 snprintf(un_addr.sun_path, sizeof(un_addr.sun_path), "%s", destpath);
1078 val = bind(fd, (struct sockaddr *) &un_addr, (int) sizeof un_addr);
1080 if (val != 0 || chmod(destpath, new_mode & ~S_IFMT) != 0)
1084 val = readlink(sourcepath, symlink_val, STRING_LENGTH - 1);
1087 symlink_val[val] = '\0';
1088 if (symlink(symlink_val, destpath) == 0)
1092 fd = open(destpath, O_RDONLY | O_CREAT, new_mode & ~S_IFMT);
1096 if (chmod(destpath, new_mode & ~S_IFMT) != 0)
1102 if (mknod(destpath, new_mode, source_stat->st_rdev) != 0)
1106 if (mkdir(destpath, new_mode & ~S_IFMT) != 0)
1109 if (chown(destpath, source_stat->st_uid, source_stat->st_gid) == 0)
1114 } /* End Function copy_inode */
1116 static void free_config(void)
1117 /* [SUMMARY] Free the configuration information.
1121 struct config_entry_struct *c_entry;
1124 for (c_entry = first_config; c_entry != NULL; c_entry = next) {
1127 next = c_entry->next;
1128 regfree(&c_entry->preg);
1129 if (c_entry->action.what == AC_EXECUTE) {
1130 for (count = 0; count < MAX_ARGS; ++count) {
1131 if (c_entry->u.execute.argv[count] == NULL)
1133 free(c_entry->u.execute.argv[count]);
1138 first_config = NULL;
1140 } /* End Function free_config */
1142 static int get_uid_gid(int flag, const char *string)
1143 /* [SUMMARY] Convert a string to a UID or GID value.
1144 <flag> "UID" or "GID".
1145 <string> The string.
1146 [RETURNS] The UID or GID value.
1149 struct passwd *pw_ent;
1150 struct group *grp_ent;
1153 if (isdigit(string[0]) || ((string[0] == '-') && isdigit(string[1])))
1154 return atoi(string);
1156 if (flag == UID && (pw_ent = getpwnam(string)) != NULL)
1157 return pw_ent->pw_uid;
1159 if (ENABLE_DEVFSD_VERBOSE)
1163 if ((grp_ent = getgrnam(string)) != NULL)
1164 return grp_ent->gr_gid;
1165 if (ENABLE_DEVFSD_VERBOSE)
1169 if (ENABLE_DEVFSD_VERBOSE)
1170 msg_logger(LOG_ERR, "unknown %s: %s, defaulting to %cid=0", msg, string, msg[0]);
1172 }/* End Function get_uid_gid */
1174 static mode_t get_mode(const char *string)
1175 /* [SUMMARY] Convert a string to a mode value.
1176 <string> The string.
1177 [RETURNS] The mode value.
1183 if (isdigit(string[0]))
1184 return strtoul(string, NULL, 8);
1185 if (strlen(string) != 9)
1186 msg_logger_and_die(LOG_ERR, "bad mode: %s", string);
1191 if (string[0] == 'r' || string[0] == 'w' || string[0] == 'x')
1197 } /* End Function get_mode */
1199 static void signal_handler(int sig)
1201 caught_signal = TRUE;
1203 caught_sighup = TRUE;
1205 info_logger(LOG_INFO, "Caught signal %d", sig);
1206 } /* End Function signal_handler */
1208 static const char *get_variable(const char *variable, void *info)
1210 static char *hostname;
1212 struct get_variable_info *gv_info = info;
1213 const char *field_names[] = {
1214 "hostname", "mntpt", "devpath", "devname", "uid", "gid", "mode",
1215 NULL, mount_point, gv_info->devpath, gv_info->devname, NULL
1220 hostname = safe_gethostname();
1221 field_names[7] = hostname;
1223 /* index_in_str_array returns i>=0 */
1224 i = index_in_str_array(field_names, variable);
1226 if (i > 6 || i < 0 || (i > 1 && gv_info == NULL))
1228 if (i >= 0 && i <= 3)
1229 return field_names[i + 7];
1232 return auto_string(xasprintf("%u", gv_info->info->uid));
1234 return auto_string(xasprintf("%u", gv_info->info->gid));
1236 return auto_string(xasprintf("%o", gv_info->info->mode));
1237 } /* End Function get_variable */
1239 static void service(struct stat statbuf, char *path)
1241 struct devfsd_notify_struct info;
1243 memset(&info, 0, sizeof info);
1244 info.type = DEVFSD_NOTIFY_REGISTERED;
1245 info.mode = statbuf.st_mode;
1246 info.major = major(statbuf.st_rdev);
1247 info.minor = minor(statbuf.st_rdev);
1248 info.uid = statbuf.st_uid;
1249 info.gid = statbuf.st_gid;
1250 snprintf(info.devname, sizeof(info.devname), "%s", path + strlen(mount_point) + 1);
1251 info.namelen = strlen(info.devname);
1252 service_name(&info);
1253 if (S_ISDIR(statbuf.st_mode))
1254 dir_operation(SERVICE, path, 0, NULL);
1257 static void dir_operation(int type, const char * dir_name, int var, unsigned long *event_mask)
1258 /* [SUMMARY] Scan a directory tree and generate register events on leaf nodes.
1259 <flag> To choose which function to perform
1260 <dp> The directory pointer. This is closed upon completion.
1261 <dir_name> The name of the directory.
1262 <rootlen> string length parameter.
1266 struct stat statbuf;
1271 dp = warn_opendir(dir_name);
1275 while ((de = readdir(dp)) != NULL) {
1277 if (de->d_name && DOT_OR_DOTDOT(de->d_name))
1279 path = concat_path_file(dir_name, de->d_name);
1280 if (lstat(path, &statbuf) == 0) {
1283 service(statbuf, path);
1286 restore(path, statbuf, var);
1289 read_config_file(path, var, event_mask);
1296 } /* End Function do_scan_and_service */
1298 static int mksymlink(const char *oldpath, const char *newpath)
1299 /* [SUMMARY] Create a symlink, creating intervening directories as required.
1300 <oldpath> The string contained in the symlink.
1301 <newpath> The name of the new symlink.
1302 [RETURNS] 0 on success, else -1.
1305 if (!make_dir_tree(newpath))
1308 if (symlink(oldpath, newpath) != 0) {
1309 if (errno != EEXIST)
1313 } /* End Function mksymlink */
1316 static int make_dir_tree(const char *path)
1317 /* [SUMMARY] Creating intervening directories for a path as required.
1318 <path> The full pathname(including the leaf node).
1319 [RETURNS] TRUE on success, else FALSE.
1322 if (bb_make_directory(dirname((char *)path), -1, FILEUTILS_RECUR) == -1)
1325 } /* End Function make_dir_tree */
1327 static int expand_expression(char *output, unsigned int outsize,
1329 const char *(*get_variable_func)(const char *variable, void *info),
1331 const char *devname,
1332 const regmatch_t *ex, unsigned int numexp)
1333 /* [SUMMARY] Expand environment variables and regular subexpressions in string.
1334 <output> The output expanded expression is written here.
1335 <length> The size of the output buffer.
1336 <input> The input expression. This may equal <<output>>.
1337 <get_variable> A function which will be used to get variable values. If
1338 this returns NULL, the environment is searched instead. If this is NULL,
1339 only the environment is searched.
1340 <info> An arbitrary pointer passed to <<get_variable>>.
1341 <devname> Device name; specifically, this is the string that contains all
1342 of the regular subexpressions.
1343 <ex> Array of start / end offsets into info->devname for each subexpression
1344 <numexp> Number of regular subexpressions found in <<devname>>.
1345 [RETURNS] TRUE on success, else FALSE.
1348 char temp[STRING_LENGTH];
1350 if (!st_expr_expand(temp, STRING_LENGTH, input, get_variable_func, info))
1352 expand_regexp(output, outsize, temp, devname, ex, numexp);
1354 } /* End Function expand_expression */
1356 static void expand_regexp(char *output, size_t outsize, const char *input,
1357 const char *devname,
1358 const regmatch_t *ex, unsigned int numex)
1359 /* [SUMMARY] Expand all occurrences of the regular subexpressions \0 to \9.
1360 <output> The output expanded expression is written here.
1361 <outsize> The size of the output buffer.
1362 <input> The input expression. This may NOT equal <<output>>, because
1363 supporting that would require yet another string-copy. However, it's not
1364 hard to write a simple wrapper function to add this functionality for those
1365 few cases that need it.
1366 <devname> Device name; specifically, this is the string that contains all
1367 of the regular subexpressions.
1368 <ex> An array of start and end offsets into <<devname>>, one for each
1370 <numex> Number of subexpressions in the offset-array <<ex>>.
1374 const char last_exp = '0' - 1 + numex;
1377 /* Guarantee NULL termination by writing an explicit '\0' character into
1378 the very last byte */
1380 output[--outsize] = '\0';
1381 /* Copy the input string into the output buffer, replacing '\\' with '\'
1382 and '\0' .. '\9' with subexpressions 0 .. 9, if they exist. Other \x
1383 codes are deleted */
1384 while ((c != '\0') && (outsize != 0)) {
1391 if ((c >= '0') && (c <= last_exp)) {
1392 const regmatch_t *subexp = ex + (c - '0');
1393 unsigned int sublen = subexp->rm_eo - subexp->rm_so;
1395 /* Range checking */
1396 if (sublen > outsize)
1398 strncpy(output, devname + subexp->rm_so, sublen);
1409 } /* End Function expand_regexp */
1412 /* from compat_name.c */
1414 struct translate_struct {
1415 const char *match; /* The string to match to(up to length) */
1416 const char *format; /* Format of output, "%s" takes data past match string,
1417 NULL is effectively "%s"(just more efficient) */
1420 static struct translate_struct translate_table[] =
1423 {"printers/", "lp%s"},
1425 {"parports/", "parport%s"},
1428 {"loop/", "loop%s"},
1429 {"floppy/", "fd%s"},
1431 {"md/", "md%s"}, /* Meta-devices */
1435 {"pg/", "pg%s"}, /* Parallel port generic ATAPI interface*/
1437 {"staliomem/", "staliomem%s"}, /* Stallion serial driver control */
1438 {"tts/E", "ttyE%s"}, /* Stallion serial driver */
1439 {"cua/E", "cue%s"}, /* Stallion serial driver callout */
1440 {"tts/R", "ttyR%s"}, /* Rocketport serial driver */
1441 {"cua/R", "cur%s"}, /* Rocketport serial driver callout */
1442 {"ip2/", "ip2%s"}, /* Computone serial driver control */
1443 {"tts/F", "ttyF%s"}, /* Computone serial driver */
1444 {"cua/F", "cuf%s"}, /* Computone serial driver callout */
1445 {"tts/C", "ttyC%s"}, /* Cyclades serial driver */
1446 {"cua/C", "cub%s"}, /* Cyclades serial driver callout */
1447 {"tts/", "ttyS%s"}, /* Generic serial: must be after others */
1448 {"cua/", "cua%s"}, /* Generic serial: must be after others */
1449 {"input/js", "js%s"}, /* Joystick driver */
1453 const char *get_old_name(const char *devname, unsigned int namelen,
1454 char *buffer, unsigned int major, unsigned int minor)
1455 /* [SUMMARY] Translate a kernel-supplied name into an old name.
1456 <devname> The device name provided by the kernel.
1457 <namelen> The length of the name.
1458 <buffer> A buffer that may be used. This should be at least 128 bytes long.
1459 <major> The major number for the device.
1460 <minor> The minor number for the device.
1461 [RETURNS] A pointer to the old name if known, else NULL.
1464 const char *compat_name = NULL;
1466 struct translate_struct *trans;
1472 /* 1 to 5 "scsi/" , 6 to 9 "ide/host", 10 sbp/, 11 vcc/, 12 pty/ */
1473 static const char *const fmt[] = {
1475 "sg%u", /* scsi/generic */
1476 NULL, /* scsi/disc */
1477 "sr%u", /* scsi/cd */
1478 NULL, /* scsi/part */
1479 "nst%u%c", /* scsi/mt */
1480 "hd%c" , /* ide/host/disc */
1481 "hd%c" , /* ide/host/cd */
1482 "hd%c%s", /* ide/host/part */
1483 "%sht%d", /* ide/host/mt */
1484 "sbpcd%u", /* sbp/ */
1486 "%cty%c%c", /* pty/ */
1490 for (trans = translate_table; trans->match != NULL; ++trans) {
1491 char *after_match = is_prefixed_with(devname, trans->match);
1493 if (trans->format == NULL)
1495 sprintf(buffer, trans->format, after_match);
1500 ptr = bb_basename(devname);
1501 i = scan_dev_name(devname, namelen, ptr);
1503 if (i > 0 && i < 13)
1504 compat_name = buffer;
1508 /* 1 == scsi/generic, 3 == scsi/cd, 10 == sbp/ */
1509 if (i == 1 || i == 3 || i == 10)
1510 sprintf(buffer, fmt[i], minor);
1512 /* 2 ==scsi/disc, 4 == scsi/part */
1513 if (i == 2 || i == 4)
1514 compat_name = write_old_sd_name(buffer, major, minor, ((i == 2) ? "" : (ptr + 4)));
1521 sprintf(buffer, fmt[i], minor & 0x1f, mode);
1522 if (devname[namelen - 1] != 'n')
1525 /* 6 == ide/host/disc, 7 == ide/host/cd, 8 == ide/host/part */
1526 if (i == 6 || i == 7 || i == 8)
1527 /* last arg should be ignored for i == 6 or i== 7 */
1528 sprintf(buffer, fmt[i] , get_old_ide_name(major, minor), ptr + 4);
1530 /* 9 == ide/host/mt */
1532 sprintf(buffer, fmt[i], ptr + 2, minor & 0x7f);
1536 sprintf(buffer, fmt[i], devname + 4);
1537 if (buffer[3] == '0')
1542 pty1 = "pqrstuvwxyzabcde";
1543 pty2 = "0123456789abcdef";
1544 indexx = atoi(devname + 5);
1545 sprintf(buffer, fmt[i], (devname[4] == 'm') ? 'p' : 't', pty1[indexx >> 4], pty2[indexx & 0x0f]);
1548 } /* End Function get_old_name */
1550 static char get_old_ide_name(unsigned int major, unsigned int minor)
1551 /* [SUMMARY] Get the old IDE name for a device.
1552 <major> The major number for the device.
1553 <minor> The minor number for the device.
1554 [RETURNS] The drive letter.
1557 char letter = 'y'; /* 121 */
1558 char c = 'a'; /* 97 */
1561 /* I hope it works like the previous code as it saves a few bytes. Tito ;P */
1563 if (i == IDE0_MAJOR || i == IDE1_MAJOR || i == IDE2_MAJOR
1564 || i == IDE3_MAJOR || i == IDE4_MAJOR || i == IDE5_MAJOR
1565 || i == IDE6_MAJOR || i == IDE7_MAJOR || i == IDE8_MAJOR
1568 if ((unsigned int)i == major) {
1575 } while (i <= IDE9_MAJOR);
1580 } /* End Function get_old_ide_name */
1582 static char *write_old_sd_name(char *buffer,
1583 unsigned int major, unsigned int minor,
1585 /* [SUMMARY] Write the old SCSI disc name to a buffer.
1586 <buffer> The buffer to write to.
1587 <major> The major number for the device.
1588 <minor> The minor number for the device.
1589 <part> The partition string. Must be "" for a whole-disc entry.
1590 [RETURNS] A pointer to the buffer on success, else NULL.
1593 unsigned int disc_index;
1596 sprintf(buffer, "sd%c%s", 'a' + (minor >> 4), part);
1599 if ((major > 64) && (major < 72)) {
1600 disc_index = ((major - 64) << 4) +(minor >> 4);
1601 if (disc_index < 26)
1602 sprintf(buffer, "sd%c%s", 'a' + disc_index, part);
1604 sprintf(buffer, "sd%c%c%s", 'a' +(disc_index / 26) - 1, 'a' + disc_index % 26, part);
1608 } /* End Function write_old_sd_name */
1613 /*EXPERIMENTAL_FUNCTION*/
1615 int st_expr_expand(char *output, unsigned int length, const char *input,
1616 const char *(*get_variable_func)(const char *variable,
1619 /* [SUMMARY] Expand an expression using Borne Shell-like unquoted rules.
1620 <output> The output expanded expression is written here.
1621 <length> The size of the output buffer.
1622 <input> The input expression. This may equal <<output>>.
1623 <get_variable> A function which will be used to get variable values. If
1624 this returns NULL, the environment is searched instead. If this is NULL,
1625 only the environment is searched.
1626 <info> An arbitrary pointer passed to <<get_variable>>.
1627 [RETURNS] TRUE on success, else FALSE.
1632 unsigned int out_pos = 0;
1635 struct passwd *pwent;
1636 char buffer[BUFFER_SIZE], tmp[STRING_LENGTH];
1638 if (length > BUFFER_SIZE)
1639 length = BUFFER_SIZE;
1640 for (; TRUE; ++input) {
1641 switch (ch = *input) {
1643 /* Variable expansion */
1644 input = expand_variable(buffer, length, &out_pos, ++input, get_variable_func, info);
1649 /* Home directory expansion */
1651 if (isspace(ch) ||(ch == '/') ||(ch == '\0')) {
1652 /* User's own home directory: leave separator for next time */
1653 env = getenv("HOME");
1655 info_logger(LOG_INFO, bb_msg_variable_not_found, "HOME");
1659 if (len + out_pos >= length)
1660 goto st_expr_expand_out;
1661 memcpy(buffer + out_pos, env, len + 1);
1665 /* Someone else's home directory */
1666 for (ptr = ++input; !isspace(ch) && (ch != '/') && (ch != '\0'); ch = *++ptr)
1669 if (len >= sizeof tmp)
1670 goto st_expr_expand_out;
1671 safe_memcpy(tmp, input, len);
1673 pwent = getpwnam(tmp);
1674 if (pwent == NULL) {
1675 info_logger(LOG_INFO, "no pwent for: %s", tmp);
1678 len = strlen(pwent->pw_dir);
1679 if (len + out_pos >= length)
1680 goto st_expr_expand_out;
1681 memcpy(buffer + out_pos, pwent->pw_dir, len + 1);
1687 if (out_pos >= length)
1688 goto st_expr_expand_out;
1689 buffer[out_pos++] = ch;
1691 memcpy(output, buffer, out_pos);
1700 simple_info_logger(LOG_INFO, bb_msg_small_buffer);
1702 } /* End Function st_expr_expand */
1705 /* Private functions follow */
1707 static const char *expand_variable(char *buffer, unsigned int length,
1708 unsigned int *out_pos, const char *input,
1709 const char *(*func)(const char *variable,
1712 /* [SUMMARY] Expand a variable.
1713 <buffer> The buffer to write to.
1714 <length> The length of the output buffer.
1715 <out_pos> The current output position. This is updated.
1716 <input> A pointer to the input character pointer.
1717 <func> A function which will be used to get variable values. If this
1718 returns NULL, the environment is searched instead. If this is NULL, only
1719 the environment is searched.
1720 <info> An arbitrary pointer passed to <<func>>.
1721 <errfp> Diagnostic messages are written here.
1722 [RETURNS] A pointer to the end of this subexpression on success, else NULL.
1727 unsigned int open_braces;
1728 const char *env, *ptr;
1729 char tmp[STRING_LENGTH];
1733 /* Special case for "$$": PID */
1734 sprintf(tmp, "%d", (int) getpid());
1736 if (len + *out_pos >= length)
1737 goto expand_variable_out;
1739 memcpy(buffer + *out_pos, tmp, len + 1);
1743 /* Ordinary variable expansion, possibly in braces */
1745 /* Simple variable expansion */
1746 for (ptr = input; isalnum(ch) || (ch == '_') || (ch == ':'); ch = *++ptr)
1749 if ((size_t)len >= sizeof tmp)
1750 goto expand_variable_out;
1752 safe_memcpy(tmp, input, len);
1754 env = get_variable_v2(tmp, func, info);
1756 info_logger(LOG_INFO, bb_msg_variable_not_found, tmp);
1760 if (len + *out_pos >= length)
1761 goto expand_variable_out;
1763 memcpy(buffer + *out_pos, env, len + 1);
1767 /* Variable in braces: check for ':' tricks */
1769 for (ptr = input; isalnum(ch) || (ch == '_'); ch = *++ptr)
1772 /* Must be simple variable expansion with "${var}" */
1774 if ((size_t)len >= sizeof tmp)
1775 goto expand_variable_out;
1777 safe_memcpy(tmp, input, len);
1778 ptr = expand_variable(buffer, length, out_pos, tmp, func, info);
1783 if (ch != ':' || ptr[1] != '-') {
1784 simple_info_logger(LOG_INFO, "illegal char in var name");
1787 /* It's that handy "${var:-word}" expression. Check if var is defined */
1789 if ((size_t)len >= sizeof tmp)
1790 goto expand_variable_out;
1792 safe_memcpy(tmp, input, len);
1793 /* Move input pointer to ':' */
1795 /* First skip to closing brace, taking note of nested expressions */
1798 for (open_braces = 1; open_braces > 0; ch = *++ptr) {
1807 info_logger(LOG_INFO, "\"}\" not found in: %s", input);
1814 /* At this point ptr should point to closing brace of "${var:-word}" */
1815 env = get_variable_v2(tmp, func, info);
1817 /* Found environment variable, so skip the input to the closing brace
1818 and return the variable */
1821 if (len + *out_pos >= length)
1822 goto expand_variable_out;
1824 memcpy(buffer + *out_pos, env, len + 1);
1828 /* Environment variable was not found, so process word. Advance input
1829 pointer to start of word in "${var:-word}" */
1832 if ((size_t)len >= sizeof tmp)
1833 goto expand_variable_out;
1835 safe_memcpy(tmp, input, len);
1837 if (!st_expr_expand(tmp, STRING_LENGTH, tmp, func, info))
1840 if (len + *out_pos >= length)
1841 goto expand_variable_out;
1843 memcpy(buffer + *out_pos, tmp, len + 1);
1846 expand_variable_out:
1847 simple_info_logger(LOG_INFO, bb_msg_small_buffer);
1849 } /* End Function expand_variable */
1852 static const char *get_variable_v2(const char *variable,
1853 const char *(*func)(const char *variable, void *info),
1855 /* [SUMMARY] Get a variable from the environment or .
1856 <variable> The variable name.
1857 <func> A function which will be used to get the variable. If this returns
1858 NULL, the environment is searched instead. If this is NULL, only the
1859 environment is searched.
1860 [RETURNS] The value of the variable on success, else NULL.
1866 value = (*func)(variable, info);
1870 return getenv(variable);
1871 } /* End Function get_variable */