1 /* vi: set sw=4 ts=4: */
3 * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
7 devfsd implementation for busybox
9 Copyright (C) 2003 by Tito Ragusa <farmatito@tiscali.it>
11 Busybox version is based on some previous work and ideas
12 Copyright (C) [2003] by [Matteo Croce] <3297627799@wind.it>
16 Main file for devfsd (devfs daemon for Linux).
18 Copyright (C) 1998-2002 Richard Gooch
22 Header file for devfsd (devfs daemon for Linux).
24 Copyright (C) 1998-2000 Richard Gooch
28 Compatibility name file for devfsd (build compatibility names).
30 Copyright (C) 1998-2002 Richard Gooch
34 This code provides Borne Shell-like expression expansion.
36 Copyright (C) 1997-1999 Richard Gooch
38 This program is free software; you can redistribute it and/or modify
39 it under the terms of the GNU General Public License as published by
40 the Free Software Foundation; either version 2 of the License, or
41 (at your option) any later version.
43 This program is distributed in the hope that it will be useful,
44 but WITHOUT ANY WARRANTY; without even the implied warranty of
45 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
46 GNU General Public License for more details.
48 You should have received a copy of the GNU General Public License
49 along with this program; if not, write to the Free Software
50 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
52 Richard Gooch may be reached by email at rgooch@atnf.csiro.au
53 The postal address is:
54 Richard Gooch, c/o ATNF, P. O. Box 76, Epping, N.S.W., 2121, Australia.
57 //#include <sys/wait.h>
58 //#include <sys/ioctl.h>
59 //#include <sys/socket.h>
63 #include <sys/sysmacros.h>
68 /* Various defines taken from linux/major.h */
81 /* Various defines taken from linux/devfs_fs.h */
82 #define DEVFSD_PROTOCOL_REVISION_KERNEL 5
83 #define DEVFSD_IOCTL_BASE 'd'
84 /* These are the various ioctls */
85 #define DEVFSDIOC_GET_PROTO_REV _IOR(DEVFSD_IOCTL_BASE, 0, int)
86 #define DEVFSDIOC_SET_EVENT_MASK _IOW(DEVFSD_IOCTL_BASE, 2, int)
87 #define DEVFSDIOC_RELEASE_EVENT_QUEUE _IOW(DEVFSD_IOCTL_BASE, 3, int)
88 #define DEVFSDIOC_SET_CONFIG_DEBUG_MASK _IOW(DEVFSD_IOCTL_BASE, 4, int)
89 #define DEVFSD_NOTIFY_REGISTERED 0
90 #define DEVFSD_NOTIFY_UNREGISTERED 1
91 #define DEVFSD_NOTIFY_ASYNC_OPEN 2
92 #define DEVFSD_NOTIFY_CLOSE 3
93 #define DEVFSD_NOTIFY_LOOKUP 4
94 #define DEVFSD_NOTIFY_CHANGE 5
95 #define DEVFSD_NOTIFY_CREATE 6
96 #define DEVFSD_NOTIFY_DELETE 7
97 #define DEVFS_PATHLEN 1024
98 /* Never change this otherwise the binary interface will change */
100 struct devfsd_notify_struct
101 { /* Use native C types to ensure same types in kernel and user space */
102 unsigned int type; /* DEVFSD_NOTIFY_* value */
103 unsigned int mode; /* Mode of the inode or device entry */
104 unsigned int major; /* Major number of device entry */
105 unsigned int minor; /* Minor number of device entry */
106 unsigned int uid; /* Uid of process, inode or device entry */
107 unsigned int gid; /* Gid of process, inode or device entry */
108 unsigned int overrun_count; /* Number of lost events */
109 unsigned int namelen; /* Number of characters not including '\0' */
110 /* The device name MUST come last */
111 char devname[DEVFS_PATHLEN]; /* This will be '\0' terminated */
114 #define BUFFER_SIZE 16384
115 #define DEVFSD_VERSION "1.3.25"
116 #define CONFIG_FILE "/etc/devfsd.conf"
117 #define MODPROBE "/sbin/modprobe"
118 #define MODPROBE_SWITCH_1 "-k"
119 #define MODPROBE_SWITCH_2 "-C"
120 #define CONFIG_MODULES_DEVFS "/etc/modules.devfs"
121 #define MAX_ARGS (6 + 1)
122 #define MAX_SUBEXPR 10
123 #define STRING_LENGTH 255
125 /* for get_uid_gid() */
129 /* fork_and_execute() */
133 /* for dir_operation() */
136 #define READ_CONFIG 2
138 /* Update only after changing code to reflect new protocol */
139 #define DEVFSD_PROTOCOL_REVISION_DAEMON 5
141 /* Compile-time check */
142 #if DEVFSD_PROTOCOL_REVISION_KERNEL != DEVFSD_PROTOCOL_REVISION_DAEMON
143 #error protocol version mismatch. Update your kernel headers
146 #define AC_PERMISSIONS 0
149 #define AC_MFUNCTION 3 /* not supported by busybox */
150 #define AC_CFUNCTION 4 /* not supported by busybox */
153 #define AC_MKOLDCOMPAT 7
154 #define AC_MKNEWCOMPAT 8
155 #define AC_RMOLDCOMPAT 9
156 #define AC_RMNEWCOMPAT 10
157 #define AC_RESTORE 11
159 struct permissions_type
168 char *argv[MAX_ARGS + 1]; /* argv[0] must always be the programme */
174 const char *destination;
183 struct config_entry_struct
185 struct action_type action;
189 struct permissions_type permissions;
190 struct execute_type execute;
191 struct copy_type copy;
194 struct config_entry_struct *next;
197 struct get_variable_info
199 const struct devfsd_notify_struct *info;
201 char devpath[STRING_LENGTH];
204 static void dir_operation(int , const char * , int, unsigned long*);
205 static void service(struct stat statbuf, char *path);
206 static int st_expr_expand(char *, unsigned, const char *, const char *(*)(const char *, void *), void *);
207 static const char *get_old_name(const char *, unsigned, char *, unsigned, unsigned);
208 static int mksymlink(const char *oldpath, const char *newpath);
209 static void read_config_file(char *path, int optional, unsigned long *event_mask);
210 static void process_config_line(const char *, unsigned long *);
211 static int do_servicing(int, unsigned long);
212 static void service_name(const struct devfsd_notify_struct *);
213 static void action_permissions(const struct devfsd_notify_struct *, const struct config_entry_struct *);
214 static void action_execute(const struct devfsd_notify_struct *, const struct config_entry_struct *,
215 const regmatch_t *, unsigned);
216 static void action_modload(const struct devfsd_notify_struct *info, const struct config_entry_struct *entry);
217 static void action_copy(const struct devfsd_notify_struct *, const struct config_entry_struct *,
218 const regmatch_t *, unsigned);
219 static void action_compat(const struct devfsd_notify_struct *, unsigned);
220 static void free_config(void);
221 static void restore(char *spath, struct stat source_stat, int rootlen);
222 static int copy_inode(const char *, const struct stat *, mode_t, const char *, const struct stat *);
223 static mode_t get_mode(const char *);
224 static void signal_handler(int);
225 static const char *get_variable(const char *, void *);
226 static int make_dir_tree(const char *);
227 static int expand_expression(char *, unsigned, const char *, const char *(*)(const char *, void *), void *,
228 const char *, const regmatch_t *, unsigned);
229 static void expand_regexp(char *, size_t, const char *, const char *, const regmatch_t *, unsigned);
230 static const char *expand_variable( char *, unsigned, unsigned *, const char *,
231 const char *(*)(const char *, void *), void *);
232 static const char *get_variable_v2(const char *, const char *(*)(const char *, void *), void *);
233 static char get_old_ide_name(unsigned , unsigned);
234 static char *write_old_sd_name(char *, unsigned, unsigned, const char *);
236 /* busybox functions */
237 static void msg_logger(int pri, const char * fmt, ...)__attribute__((format(printf, 2, 3)));
238 static void msg_logger_and_die(int pri, const char * fmt, ...)__attribute__((noreturn, format(printf, 2, 3)));
239 static void do_ioctl_and_die(int fd, int request, unsigned long event_mask_flag);
240 static void fork_and_execute(int die, char *arg0, char **arg);
241 static int get_uid_gid(int, const char *);
242 static void safe_memcpy(char * dest, const char * src, int len);
243 static unsigned int scan_dev_name_common(const char *d, unsigned int n, int addendum, char *ptr);
244 static unsigned int scan_dev_name(const char *d, unsigned int n, char *ptr);
246 /* Structs and vars */
247 static struct config_entry_struct *first_config = NULL;
248 static struct config_entry_struct *last_config = NULL;
249 static const char *mount_point = NULL;
250 static volatile int caught_signal = FALSE;
251 static volatile int caught_sighup = FALSE;
252 static struct initial_symlink_struct
256 } initial_symlinks[] =
258 {"/proc/self/fd", "fd"},
265 static struct event_type
267 unsigned int type; /* The DEVFSD_NOTIFY_* value */
268 const char *config_name; /* The name used in the config file */
271 {DEVFSD_NOTIFY_REGISTERED, "REGISTER"},
272 {DEVFSD_NOTIFY_UNREGISTERED, "UNREGISTER"},
273 {DEVFSD_NOTIFY_ASYNC_OPEN, "ASYNC_OPEN"},
274 {DEVFSD_NOTIFY_CLOSE, "CLOSE"},
275 {DEVFSD_NOTIFY_LOOKUP, "LOOKUP"},
276 {DEVFSD_NOTIFY_CHANGE, "CHANGE"},
277 {DEVFSD_NOTIFY_CREATE, "CREATE"},
278 {DEVFSD_NOTIFY_DELETE, "DELETE"},
282 /* Busybox messages */
284 static const char * const bb_msg_proto_rev = "protocol revision";
285 static const char * const bb_msg_bad_config = "bad %s config file: %s";
286 static const char * const bb_msg_small_buffer = "buffer too small";
287 static const char * const bb_msg_variable_not_found = "variable: %s not found";
289 /* Busybox functions */
290 static void msg_logger(int pri, const char * fmt, ...)
296 ret = access("/dev/log", F_OK);
298 openlog(applet_name, 0, LOG_DAEMON);
299 vsyslog(pri , fmt, ap);
300 /* Man: A trailing newline is added when needed. */
303 /* ENABLE_DEVFSD_VERBOSE is always enabled if msg_logger is used */
304 if ((ENABLE_DEVFSD_VERBOSE && ret) || ENABLE_DEBUG) {
305 bb_error_msg(fmt, ap);
310 static void msg_logger_and_die(int pri, const char* fmt, ...)
315 msg_logger(pri, fmt, ap);
321 #if defined(CONFIG_DEVFSD_VERBOSE) || defined(CONFIG_DEBUG)
322 #define devfsd_error_msg(fmt, args...) bb_error_msg(fmt, ## args)
323 #define devfsd_perror_msg_and_die(fmt, args...) bb_perror_msg_and_die(fmt, ## args)
324 #define devfsd_error_msg_and_die(fmt, args...) bb_error_msg_and_die(fmt, ## args)
325 #if defined(CONFIG_DEBUG)
326 #define debug_msg_logger(x, fmt, args...) msg_logger(x, fmt, ## args)
328 #define debug_msg_logger(x, fmt, args...)
331 #define debug_msg_logger(x, fmt, args...)
332 #define msg_logger(p, fmt, args...)
333 #define msg_logger_and_die(p, fmt, args...) exit(1)
334 #define devfsd_perror_msg_and_die(fmt, args...) exit(1)
335 #define devfsd_error_msg_and_die(fmt, args...) exit(1)
336 #define devfsd_error_msg(fmt, args...)
339 static void do_ioctl_and_die(int fd, int request, unsigned long event_mask_flag)
341 if (ioctl(fd, request, event_mask_flag) == -1)
342 msg_logger_and_die(LOG_ERR, "ioctl");
345 static void fork_and_execute(int die, char *arg0, char **arg)
352 /* Parent: Error : die or return */
353 msg_logger(LOG_ERR,(char *)bb_msg_memory_exhausted);
358 /* Parent : ok : return or exit */
365 /* Child : if arg0 != NULL do execvp */
367 BB_EXECVP(arg0, arg);
368 msg_logger_and_die(LOG_ERR, "execvp");
372 static void safe_memcpy(char *dest, const char *src, int len)
374 memcpy(dest , src, len);
378 static unsigned int scan_dev_name_common(const char *d, unsigned int n, int addendum, char *ptr)
380 if (d[n - 4] == 'd' && d[n - 3] == 'i' && d[n - 2] == 's' && d[n - 1] == 'c')
382 if (d[n - 2] == 'c' && d[n - 1] == 'd')
384 if (ptr[0] == 'p' && ptr[1] == 'a' && ptr[2] == 'r' && ptr[3] == 't')
386 if (ptr[n - 2] == 'm' && ptr[n - 1] == 't')
391 static unsigned int scan_dev_name(const char *d, unsigned int n, char *ptr)
393 if (d[0] == 's' && d[1] == 'c' && d[2] == 's' && d[3] == 'i' && d[4] == '/') {
394 if (d[n - 7] == 'g' && d[n - 6] == 'e' && d[n - 5] == 'n'
395 && d[n - 4] == 'e' && d[n - 3] == 'r' && d[n - 2] == 'i' && d[n - 1] == 'c'
398 return scan_dev_name_common(d, n, 0, ptr);
400 if (d[0] == 'i' && d[1] == 'd' && d[2] == 'e' && d[3] == '/'
401 && d[4] == 'h' && d[5] == 'o' && d[6] == 's' && d[7] == 't'
403 return scan_dev_name_common(d, n, 4, ptr);
404 if (d[0] == 's' && d[1] == 'b' && d[2] == 'p' && d[3] == '/')
406 if (d[0] == 'v' && d[1] == 'c' && d[2] == 'c' && d[3] == '/')
408 if (d[0] == 'p' && d[1] == 't' && d[2] == 'y' && d[3] == '/')
413 /* Public functions follow */
415 int devfsd_main(int argc, char **argv);
416 int devfsd_main(int argc, char **argv)
418 int print_version = FALSE;
419 int do_daemon = TRUE;
420 int no_polling = FALSE;
422 int fd, proto_rev, count;
423 unsigned long event_mask = 0;
424 struct sigaction new_action;
425 struct initial_symlink_struct *curr;
430 for (count = 2; count < argc; ++count) {
431 if (argv[count][0] == '-') {
432 if (argv[count][1] == 'v' && !argv[count][2]) /* -v */
433 print_version = TRUE;
434 else if (ENABLE_DEVFSD_FG_NP && argv[count][1] == 'f'
435 && argv[count][2] == 'g' && !argv[count][3]) /* -fg */
437 else if (ENABLE_DEVFSD_FG_NP && argv[count][1] == 'n'
438 && argv[count][2] == 'p' && !argv[count][3]) /* -np */
445 /* strip last / from mount point, so we don't need to check for it later */
446 while (argv[1][1] != '\0' && argv[1][strlen(argv[1]) - 1] == '/')
447 argv[1][strlen(argv[1]) - 1] = '\0';
449 mount_point = argv[1];
451 if (chdir(mount_point) != 0)
452 devfsd_perror_msg_and_die(mount_point);
454 fd = xopen(".devfsd", O_RDONLY);
456 if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0)
457 devfsd_perror_msg_and_die("FD_CLOEXEC");
459 if (ioctl(fd, DEVFSDIOC_GET_PROTO_REV, &proto_rev) == -1)
460 msg_logger_and_die(LOG_ERR, "ioctl");
462 /*setup initial entries */
463 for (curr = initial_symlinks; curr->dest != NULL; ++curr)
464 symlink(curr->dest, curr->name);
466 /* NB: The check for CONFIG_FILE is done in read_config_file() */
468 if (print_version ||(DEVFSD_PROTOCOL_REVISION_DAEMON != proto_rev)) {
469 printf("%s v%s\nDaemon %s:\t%d\nKernel-side %s:\t%d\n",
470 applet_name, DEVFSD_VERSION, bb_msg_proto_rev,
471 DEVFSD_PROTOCOL_REVISION_DAEMON,bb_msg_proto_rev, proto_rev);
472 if (DEVFSD_PROTOCOL_REVISION_DAEMON != proto_rev)
473 bb_error_msg_and_die("%s mismatch!", bb_msg_proto_rev);
474 exit(EXIT_SUCCESS); /* -v */
476 /* Tell kernel we are special(i.e. we get to see hidden entries) */
477 do_ioctl_and_die(fd, DEVFSDIOC_SET_EVENT_MASK, 0);
479 sigemptyset(&new_action.sa_mask);
480 new_action.sa_flags = 0;
482 /* Set up SIGHUP and SIGUSR1 handlers */
483 new_action.sa_handler = signal_handler;
484 if (sigaction(SIGHUP, &new_action, NULL) != 0 || sigaction(SIGUSR1, &new_action, NULL) != 0)
485 devfsd_error_msg_and_die("sigaction");
487 printf("%s v%s started for %s\n",applet_name, DEVFSD_VERSION, mount_point);
489 /* Set umask so that mknod(2), open(2) and mkdir(2) have complete control over permissions */
491 read_config_file((char*)CONFIG_FILE, FALSE, &event_mask);
492 /* Do the scan before forking, so that boot scripts see the finished product */
493 dir_operation(SERVICE, mount_point, 0, NULL);
495 if (ENABLE_DEVFSD_FG_NP && no_polling)
498 /* Release so that the child can grab it */
499 do_ioctl_and_die(fd, DEVFSDIOC_RELEASE_EVENT_QUEUE, 0);
500 fork_and_execute(DIE, NULL, NULL);
501 setsid(); /* Prevent hangups and become pgrp leader */
502 } else if (ENABLE_DEVFSD_FG_NP) {
503 setpgid(0, 0); /* Become process group leader */
507 do_scan = do_servicing(fd, event_mask);
510 read_config_file((char*)CONFIG_FILE, FALSE, &event_mask);
512 dir_operation(SERVICE,mount_point,0,NULL);
514 } /* End Function main */
517 /* Private functions follow */
519 static void read_config_file(char *path, int optional, unsigned long *event_mask)
520 /* [SUMMARY] Read a configuration database.
521 <path> The path to read the database from. If this is a directory, all
522 entries in that directory will be read(except hidden entries).
523 <optional> If TRUE, the routine will silently ignore a missing config file.
524 <event_mask> The event mask is written here. This is not initialised.
530 char buf[STRING_LENGTH];
533 debug_msg_logger(LOG_INFO, "%s: %s", __FUNCTION__, path);
535 if (stat(path, &statbuf) == 0) {
536 /* Don't read 0 length files: ignored */
537 /*if (statbuf.st_size == 0)
539 if (S_ISDIR(statbuf.st_mode)) {
540 /* strip last / from dirname so we don't need to check for it later */
541 while (path && path[1] != '\0' && path[strlen(path) - 1] == '/')
542 path[strlen(path) - 1] = '\0';
544 dir_operation(READ_CONFIG, path, 0, event_mask);
547 if ((fp = fopen(path, "r")) != NULL) {
548 while (fgets(buf, STRING_LENGTH, fp) != NULL) {
549 /* Skip whitespace */
550 for (line = buf; isspace(*line); ++line)
552 if (line[0] == '\0' || line[0] == '#')
554 process_config_line(line, event_mask);
558 goto read_config_file_err;
561 read_config_file_err:
562 if (optional == 0 && errno == ENOENT)
563 msg_logger_and_die(LOG_ERR, "read config file: %s: %m", path);
565 } /* End Function read_config_file */
567 static void process_config_line(const char *line, unsigned long *event_mask)
568 /* [SUMMARY] Process a line from a configuration file.
569 <line> The configuration line.
570 <event_mask> The event mask is written here. This is not initialised.
575 struct config_entry_struct *new;
576 char p[MAX_ARGS][STRING_LENGTH];
577 char when[STRING_LENGTH], what[STRING_LENGTH];
578 char name[STRING_LENGTH];
579 const char *msg = "";
583 /* !!!! Only Uppercase Keywords in devsfd.conf */
584 static const char *const options[] = {
585 "CLEAR_CONFIG", "INCLUDE", "OPTIONAL_INCLUDE",
586 "RESTORE", "PERMISSIONS", "MODLOAD", "EXECUTE",
587 "COPY", "IGNORE", "MKOLDCOMPAT", "MKNEWCOMPAT",
588 "RMOLDCOMPAT", "RMNEWCOMPAT", 0
591 debug_msg_logger(LOG_INFO, __FUNCTION__);
593 for (count = 0; count < MAX_ARGS; ++count) p[count][0] = '\0';
594 num_args = sscanf(line, "%s %s %s %s %s %s %s %s %s %s",
596 p[0], p[1], p[2], p[3], p[4], p[5], p[6]);
598 i = index_in_str_array(options, when);
608 goto process_config_line_err;
610 /* "INCLUDE" & "OPTIONAL_INCLUDE" */
611 if (i == 1 || i == 2) {
612 st_expr_expand(name, STRING_LENGTH, name, get_variable, NULL);
613 msg_logger(LOG_INFO, "%sinclude: %s", (toupper(when[0]) == 'I') ? "": "optional_", name);
614 read_config_file(name, (toupper(when[0]) == 'I') ? FALSE : TRUE, event_mask);
619 dir_operation(RESTORE,name, strlen(name),NULL);
623 goto process_config_line_err;
625 new = xmalloc(sizeof *new);
626 memset(new, 0, sizeof *new);
628 for (count = 0; event_types[count].config_name != NULL; ++count) {
629 if (strcasecmp(when, event_types[count].config_name) != 0)
631 new->action.when = event_types[count].type;
634 if (event_types[count].config_name == NULL) {
636 goto process_config_line_err;
639 i = index_in_str_array(options, what);
642 case 4: /* "PERMISSIONS" */
643 new->action.what = AC_PERMISSIONS;
644 /* Get user and group */
645 if ((ptr = strchr(p[0], '.')) == NULL) {
647 goto process_config_line_err; /*"missing '.' in UID.GID"*/
651 new->u.permissions.uid = get_uid_gid(UID, p[0]);
652 new->u.permissions.gid = get_uid_gid(GID, ptr);
654 new->u.permissions.mode = get_mode(p[1]);
656 case 5: /* MODLOAD */
657 /*This action will pass "/dev/$devname"(i.e. "/dev/" prefixed to
658 the device name) to the module loading facility. In addition,
659 the /etc/modules.devfs configuration file is used.*/
660 if (ENABLE_DEVFSD_MODLOAD)
661 new->action.what = AC_MODLOAD;
663 case 6: /* EXECUTE */
664 new->action.what = AC_EXECUTE;
667 for (count = 0; count < num_args; ++count)
668 new->u.execute.argv[count] = xstrdup(p[count]);
670 new->u.execute.argv[num_args] = NULL;
673 new->action.what = AC_COPY;
676 goto process_config_line_err; /* missing path and function in line */
678 new->u.copy.source = xstrdup(p[0]);
679 new->u.copy.destination = xstrdup(p[1]);
683 case 9: /* MKOLDCOMPAT */
685 case 10: /* MKNEWCOMPAT */
687 case 11:/* RMOLDCOMPAT */
689 case 12: /* RMNEWCOMPAT */
695 new->action.what = i - 2;
699 goto process_config_line_err;
703 xregcomp(&new->preg, name, REG_EXTENDED);
705 *event_mask |= 1 << new->action.when;
707 if (first_config == NULL)
710 last_config->next = new;
713 process_config_line_err:
714 msg_logger_and_die(LOG_ERR, bb_msg_bad_config, msg , line);
715 } /* End Function process_config_line */
717 static int do_servicing(int fd, unsigned long event_mask)
718 /* [SUMMARY] Service devfs changes until a signal is received.
719 <fd> The open control file.
720 <event_mask> The event mask.
721 [RETURNS] TRUE if SIGHUP was caught, else FALSE.
725 struct devfsd_notify_struct info;
726 unsigned long tmp_event_mask;
728 debug_msg_logger(LOG_INFO, __FUNCTION__);
730 /* Tell devfs what events we care about */
731 tmp_event_mask = event_mask;
732 do_ioctl_and_die(fd, DEVFSDIOC_SET_EVENT_MASK, tmp_event_mask);
733 while (!caught_signal) {
735 bytes = read(fd,(char *) &info, sizeof info);
737 break; /* Must test for this first */
739 continue; /* Yes, the order is important */
745 int c_sighup = caught_sighup;
747 caught_signal = FALSE;
748 caught_sighup = FALSE;
751 msg_logger_and_die(LOG_ERR, "read error on control file");
752 } /* End Function do_servicing */
754 static void service_name(const struct devfsd_notify_struct *info)
755 /* [SUMMARY] Service a single devfs change.
756 <info> The devfs change.
761 regmatch_t mbuf[MAX_SUBEXPR];
762 struct config_entry_struct *entry;
764 debug_msg_logger(LOG_INFO, __FUNCTION__);
765 if (ENABLE_DEBUG && info->overrun_count > 0)
766 debug_msg_logger(LOG_ERR, "lost %u events", info->overrun_count);
768 /* Discard lookups on "/dev/log" and "/dev/initctl" */
769 if (info->type == DEVFSD_NOTIFY_LOOKUP
770 && ((info->devname[0] == 'l' && info->devname[1] == 'o'
771 && info->devname[2] == 'g' && !info->devname[3])
772 || (info->devname[0] == 'i' && info->devname[1] == 'n'
773 && info->devname[2] == 'i' && info->devname[3] == 't'
774 && info->devname[4] == 'c' && info->devname[5] == 't'
775 && info->devname[6] == 'l' && !info->devname[7]))
779 for (entry = first_config; entry != NULL; entry = entry->next) {
780 /* First check if action matches the type, then check if name matches */
781 if (info->type != entry->action.when
782 || regexec(&entry->preg, info->devname, MAX_SUBEXPR, mbuf, 0) != 0)
784 for (n = 0;(n < MAX_SUBEXPR) && (mbuf[n].rm_so != -1); ++n)
787 debug_msg_logger(LOG_INFO, "%s: action.what %d", __FUNCTION__, entry->action.what);
789 switch (entry->action.what) {
791 action_permissions(info, entry);
794 if (ENABLE_DEVFSD_MODLOAD)
795 action_modload(info, entry);
798 action_execute(info, entry, mbuf, n);
801 action_copy(info, entry, mbuf, n);
810 action_compat(info, entry->action.what);
813 msg_logger_and_die(LOG_ERR, "Unknown action");
816 } /* End Function service_name */
818 static void action_permissions(const struct devfsd_notify_struct *info,
819 const struct config_entry_struct *entry)
820 /* [SUMMARY] Update permissions for a device entry.
821 <info> The devfs change.
822 <entry> The config file entry.
828 debug_msg_logger(LOG_INFO, __FUNCTION__);
830 if (stat(info->devname, &statbuf) != 0 ||
831 chmod(info->devname,(statbuf.st_mode & S_IFMT) |(entry->u.permissions.mode & ~S_IFMT)) != 0 ||
832 chown(info->devname, entry->u.permissions.uid, entry->u.permissions.gid) != 0) {
833 msg_logger(LOG_ERR, "Can't chmod or chown: %s: %m",info->devname);
835 } /* End Function action_permissions */
837 static void action_modload(const struct devfsd_notify_struct *info,
838 const struct config_entry_struct *entry ATTRIBUTE_UNUSED)
839 /* [SUMMARY] Load a module.
840 <info> The devfs change.
841 <entry> The config file entry.
846 char device[STRING_LENGTH];
848 argv[0] =(char*)MODPROBE;
849 argv[1] =(char*)MODPROBE_SWITCH_1; /* "-k" */
850 argv[2] =(char*)MODPROBE_SWITCH_2; /* "-C" */
851 argv[3] =(char*)CONFIG_MODULES_DEVFS;
855 snprintf(device, sizeof(device), "/dev/%s", info->devname);
856 debug_msg_logger(LOG_INFO, "%s: %s %s %s %s %s",__FUNCTION__, argv[0],argv[1],argv[2],argv[3],argv[4]);
857 fork_and_execute(DIE, argv[0], argv);
858 } /* End Function action_modload */
860 static void action_execute(const struct devfsd_notify_struct *info,
861 const struct config_entry_struct *entry,
862 const regmatch_t *regexpr, unsigned int numexpr)
863 /* [SUMMARY] Execute a programme.
864 <info> The devfs change.
865 <entry> The config file entry.
866 <regexpr> The number of subexpression(start, end) offsets within the
868 <numexpr> The number of elements within <<regexpr>>.
873 struct get_variable_info gv_info;
874 char *argv[MAX_ARGS + 1];
875 char largv[MAX_ARGS + 1][STRING_LENGTH];
877 debug_msg_logger(LOG_INFO ,__FUNCTION__);
879 gv_info.devname = info->devname;
880 snprintf(gv_info.devpath, sizeof(gv_info.devpath), "%s/%s", mount_point, info->devname);
881 for (count = 0; entry->u.execute.argv[count] != NULL; ++count) {
882 expand_expression(largv[count], STRING_LENGTH,
883 entry->u.execute.argv[count],
884 get_variable, &gv_info,
885 gv_info.devname, regexpr, numexpr);
886 argv[count] = largv[count];
889 fork_and_execute(NO_DIE, argv[0], argv);
890 } /* End Function action_execute */
893 static void action_copy(const struct devfsd_notify_struct *info,
894 const struct config_entry_struct *entry,
895 const regmatch_t *regexpr, unsigned int numexpr)
896 /* [SUMMARY] Copy permissions.
897 <info> The devfs change.
898 <entry> The config file entry.
899 <regexpr> This list of subexpression(start, end) offsets within the
901 <numexpr> The number of elements in <<regexpr>>.
906 struct get_variable_info gv_info;
907 struct stat source_stat, dest_stat;
908 char source[STRING_LENGTH], destination[STRING_LENGTH];
911 debug_msg_logger(LOG_INFO, __FUNCTION__);
913 dest_stat.st_mode = 0;
915 if ((info->type == DEVFSD_NOTIFY_CHANGE) && S_ISLNK(info->mode))
918 gv_info.devname = info->devname;
920 snprintf(gv_info.devpath, sizeof(gv_info.devpath), "%s/%s", mount_point, info->devname);
921 expand_expression(source, STRING_LENGTH, entry->u.copy.source,
922 get_variable, &gv_info, gv_info.devname,
925 expand_expression(destination, STRING_LENGTH, entry->u.copy.destination,
926 get_variable, &gv_info, gv_info.devname,
929 if (!make_dir_tree(destination) || lstat(source, &source_stat) != 0)
931 lstat(destination, &dest_stat);
932 new_mode = source_stat.st_mode & ~S_ISVTX;
933 if (info->type == DEVFSD_NOTIFY_CREATE)
935 else if ((info->type == DEVFSD_NOTIFY_CHANGE) &&(dest_stat.st_mode & S_ISVTX))
937 ret = copy_inode(destination, &dest_stat, new_mode, source, &source_stat);
938 if (ENABLE_DEBUG && ret &&(errno != EEXIST))
939 debug_msg_logger(LOG_ERR, "copy_inode: %s to %s: %m", source, destination);
940 } /* End Function action_copy */
942 static void action_compat(const struct devfsd_notify_struct *info, unsigned int action)
943 /* [SUMMARY] Process a compatibility request.
944 <info> The devfs change.
945 <action> The action to take.
950 const char *compat_name = NULL;
951 const char *dest_name = info->devname;
953 char compat_buf[STRING_LENGTH], dest_buf[STRING_LENGTH];
954 int mode, host, bus, target, lun;
957 /* 1 to 5 "scsi/" , 6 to 9 "ide/host" */
958 static const char *const fmt[] = {
960 "sg/c%db%dt%du%d", /* scsi/generic */
961 "sd/c%db%dt%du%d", /* scsi/disc */
962 "sr/c%db%dt%du%d", /* scsi/cd */
963 "sd/c%db%dt%du%dp%d", /* scsi/part */
964 "st/c%db%dt%du%dm%d%c", /* scsi/mt */
965 "ide/hd/c%db%dt%du%d", /* ide/host/disc */
966 "ide/cd/c%db%dt%du%d", /* ide/host/cd */
967 "ide/hd/c%db%dt%du%dp%d", /* ide/host/part */
968 "ide/mt/c%db%dt%du%d%s", /* ide/host/mt */
972 /* First construct compatibility name */
976 compat_name = get_old_name(info->devname, info->namelen, compat_buf, info->major, info->minor);
980 ptr = strrchr(info->devname, '/') + 1;
981 i=scan_dev_name(info->devname, info->namelen, ptr);
983 debug_msg_logger(LOG_INFO, "%s: scan_dev_name = %d", __FUNCTION__, i);
989 sscanf(info->devname +((i<6)?5:4), "host%d/bus%d/target%d/lun%d/", &host, &bus, &target, &lun);
990 snprintf(dest_buf, sizeof(dest_buf), "../%s", info->devname +((i>5)?4:0));
991 dest_name = dest_buf;
992 compat_name = compat_buf;
995 /* 1 == scsi/generic 2 == scsi/disc 3 == scsi/cd 6 == ide/host/disc 7 == ide/host/cd */
996 if (i == 1 || i == 2 || i == 3 || i == 6 || i ==7)
997 sprintf(compat_buf, fmt[i], host, bus, target, lun);
999 /* 4 == scsi/part 8 == ide/host/part */
1000 if (i == 4 || i == 8)
1001 sprintf(compat_buf, fmt[i], host, bus, target, lun, atoi(ptr + 4));
1005 rewind_ = info->devname[info->namelen - 1];
1009 if (ptr[2] == 'l' /*108*/ || ptr[2] == 'm'/*109*/)
1010 mode = ptr[2] - 107; /* 1 or 2 */
1013 sprintf(compat_buf, fmt [i], host, bus, target, lun, mode, rewind_);
1016 /* 9 == ide/host/mt */
1018 snprintf(compat_buf, sizeof(compat_buf), fmt[i], host, bus, target, lun, ptr + 2);
1020 } /* switch (action) */
1022 if (compat_name == NULL)
1025 debug_msg_logger(LOG_INFO, "%s: %s", __FUNCTION__, compat_name);
1027 /* Now decide what to do with it */
1029 case AC_MKOLDCOMPAT:
1030 case AC_MKNEWCOMPAT:
1031 mksymlink(dest_name, compat_name);
1033 case AC_RMOLDCOMPAT:
1034 case AC_RMNEWCOMPAT:
1035 ret = unlink(compat_name);
1036 if (ENABLE_DEBUG && ret)
1037 debug_msg_logger(LOG_ERR, "unlink: %s: %m", compat_name);
1040 } /* switch (action) */
1041 } /* End Function action_compat */
1043 static void restore(char *spath, struct stat source_stat, int rootlen)
1045 char dpath[STRING_LENGTH];
1046 struct stat dest_stat;
1048 debug_msg_logger(LOG_INFO, __FUNCTION__);
1050 dest_stat.st_mode = 0;
1051 snprintf(dpath, sizeof dpath, "%s%s", mount_point, spath + rootlen);
1052 lstat(dpath, &dest_stat);
1054 if (S_ISLNK(source_stat.st_mode) ||(source_stat.st_mode & S_ISVTX))
1055 copy_inode(dpath, &dest_stat,(source_stat.st_mode & ~S_ISVTX) , spath, &source_stat);
1057 if (S_ISDIR(source_stat.st_mode))
1058 dir_operation(RESTORE, spath, rootlen,NULL);
1062 static int copy_inode(const char *destpath, const struct stat *dest_stat,
1064 const char *sourcepath, const struct stat *source_stat)
1065 /* [SUMMARY] Copy an inode.
1066 <destpath> The destination path. An existing inode may be deleted.
1067 <dest_stat> The destination stat(2) information.
1068 <new_mode> The desired new mode for the destination.
1069 <sourcepath> The source path.
1070 <source_stat> The source stat(2) information.
1071 [RETURNS] TRUE on success, else FALSE.
1074 int source_len, dest_len;
1075 char source_link[STRING_LENGTH], dest_link[STRING_LENGTH];
1077 struct sockaddr_un un_addr;
1078 char symlink_val[STRING_LENGTH];
1080 debug_msg_logger(LOG_INFO, __FUNCTION__);
1082 if ((source_stat->st_mode & S_IFMT) ==(dest_stat->st_mode & S_IFMT)) {
1084 if (S_ISLNK(source_stat->st_mode)) {
1085 if ((source_len = readlink(sourcepath, source_link, STRING_LENGTH - 1)) < 0
1086 || (dest_len = readlink(destpath , dest_link , STRING_LENGTH - 1)) < 0
1089 source_link[source_len] = '\0';
1090 dest_link[dest_len] = '\0';
1091 if ((source_len != dest_len) || (strcmp(source_link, dest_link) != 0)) {
1093 symlink(source_link, destpath);
1096 } /* Else not a symlink */
1097 chmod(destpath, new_mode & ~S_IFMT);
1098 chown(destpath, source_stat->st_uid, source_stat->st_gid);
1101 /* Different types: unlink and create */
1103 switch (source_stat->st_mode & S_IFMT) {
1105 if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0)
1107 un_addr.sun_family = AF_UNIX;
1108 snprintf(un_addr.sun_path, sizeof(un_addr.sun_path), "%s", destpath);
1109 val = bind(fd,(struct sockaddr *) &un_addr,(int) sizeof un_addr);
1111 if (val != 0 || chmod(destpath, new_mode & ~S_IFMT) != 0)
1115 if ((val = readlink(sourcepath, symlink_val, STRING_LENGTH - 1)) < 0)
1117 symlink_val[val] = '\0';
1118 if (symlink(symlink_val, destpath) == 0)
1122 if ((fd = open(destpath, O_RDONLY | O_CREAT, new_mode & ~S_IFMT)) < 0)
1125 if (chmod(destpath, new_mode & ~S_IFMT) != 0)
1131 if (mknod(destpath, new_mode, source_stat->st_rdev) != 0)
1135 if (mkdir(destpath, new_mode & ~S_IFMT) != 0)
1138 if (chown(destpath, source_stat->st_uid, source_stat->st_gid) == 0)
1143 } /* End Function copy_inode */
1145 static void free_config(void)
1146 /* [SUMMARY] Free the configuration information.
1150 struct config_entry_struct *c_entry;
1153 debug_msg_logger(LOG_INFO, __FUNCTION__);
1155 for (c_entry = first_config; c_entry != NULL; c_entry = next) {
1158 next = c_entry->next;
1159 regfree(&c_entry->preg);
1160 if (c_entry->action.what == AC_EXECUTE) {
1161 for (count = 0; count < MAX_ARGS; ++count) {
1162 if (c_entry->u.execute.argv[count] == NULL)
1164 free(c_entry->u.execute.argv[count]);
1169 first_config = NULL;
1171 } /* End Function free_config */
1173 static int get_uid_gid(int flag, const char *string)
1174 /* [SUMMARY] Convert a string to a UID or GID value.
1175 <flag> "UID" or "GID".
1176 <string> The string.
1177 [RETURNS] The UID or GID value.
1180 struct passwd *pw_ent;
1181 struct group *grp_ent;
1182 static const char *msg;
1184 if (ENABLE_DEVFSD_VERBOSE)
1187 debug_msg_logger(LOG_INFO, __FUNCTION__);
1189 if (ENABLE_DEBUG && flag != UID && flag != GID)
1190 msg_logger_and_die(LOG_ERR,"%s: flag != UID && flag != GID", __FUNCTION__);
1192 if (isdigit(string[0]) ||((string[0] == '-') && isdigit(string[1])))
1193 return atoi(string);
1195 if (flag == UID && (pw_ent = getpwnam(string)) != NULL)
1196 return pw_ent->pw_uid;
1198 if (flag == GID && (grp_ent = getgrnam(string)) != NULL)
1199 return grp_ent->gr_gid;
1200 else if (ENABLE_DEVFSD_VERBOSE)
1203 if (ENABLE_DEVFSD_VERBOSE)
1204 msg_logger(LOG_ERR,"unknown %s: %s, defaulting to %cid=0", msg, string, msg[0]);
1206 }/* End Function get_uid_gid */
1208 static mode_t get_mode(const char *string)
1209 /* [SUMMARY] Convert a string to a mode value.
1210 <string> The string.
1211 [RETURNS] The mode value.
1217 debug_msg_logger(LOG_INFO, __FUNCTION__);
1219 if (isdigit(string[0]))
1220 return strtoul(string, NULL, 8);
1221 if (strlen(string) != 9)
1222 msg_logger_and_die(LOG_ERR, "bad mode: %s", string);
1227 if (string[0] == 'r' || string[0] == 'w' || string[0] == 'x')
1233 } /* End Function get_mode */
1235 static void signal_handler(int sig)
1237 debug_msg_logger(LOG_INFO, __FUNCTION__);
1239 caught_signal = TRUE;
1241 caught_sighup = TRUE;
1243 msg_logger(LOG_INFO, "Caught signal %d", sig);
1244 } /* End Function signal_handler */
1246 static const char *get_variable(const char *variable, void *info)
1248 struct get_variable_info *gv_info = info;
1249 static char hostname[STRING_LENGTH], sbuf[STRING_LENGTH];
1250 const char *field_names[] = { "hostname", "mntpt", "devpath", "devname",
1251 "uid", "gid", "mode", hostname, mount_point,
1252 gv_info->devpath, gv_info->devname, 0 };
1255 debug_msg_logger(LOG_INFO, __FUNCTION__);
1257 if (gethostname(hostname, STRING_LENGTH - 1) != 0)
1258 msg_logger_and_die(LOG_ERR, "gethostname: %m");
1260 /* Here on error we should do exit(RV_SYS_ERROR), instead we do exit(EXIT_FAILURE) */
1261 hostname[STRING_LENGTH - 1] = '\0';
1263 /* index_in_str_array returns i>=0 */
1264 i = index_in_str_array(field_names, variable);
1266 if (i > 6 || i < 0 || (i > 1 && gv_info == NULL))
1268 if (i >= 0 && i <= 3) {
1269 debug_msg_logger(LOG_INFO, "%s: i=%d %s", __FUNCTION__, i, field_names[i + 7]);
1270 return field_names[i + 7];
1274 sprintf(sbuf, "%u", gv_info->info->uid);
1276 sprintf(sbuf, "%u", gv_info->info->gid);
1278 sprintf(sbuf, "%o", gv_info->info->mode);
1280 debug_msg_logger(LOG_INFO, "%s: %s", __FUNCTION__, sbuf);
1283 } /* End Function get_variable */
1285 static void service(struct stat statbuf, char *path)
1287 struct devfsd_notify_struct info;
1289 debug_msg_logger(LOG_INFO, __FUNCTION__);
1291 memset(&info, 0, sizeof info);
1292 info.type = DEVFSD_NOTIFY_REGISTERED;
1293 info.mode = statbuf.st_mode;
1294 info.major = major(statbuf.st_rdev);
1295 info.minor = minor(statbuf.st_rdev);
1296 info.uid = statbuf.st_uid;
1297 info.gid = statbuf.st_gid;
1298 snprintf(info.devname, sizeof(info.devname), "%s", path + strlen(mount_point) + 1);
1299 info.namelen = strlen(info.devname);
1300 service_name(&info);
1301 if (S_ISDIR(statbuf.st_mode))
1302 dir_operation(SERVICE, path, 0, NULL);
1305 static void dir_operation(int type, const char * dir_name, int var, unsigned long *event_mask)
1306 /* [SUMMARY] Scan a directory tree and generate register events on leaf nodes.
1307 <flag> To choose which function to perform
1308 <dp> The directory pointer. This is closed upon completion.
1309 <dir_name> The name of the directory.
1310 <rootlen> string length parameter.
1314 struct stat statbuf;
1317 char path[STRING_LENGTH];
1319 debug_msg_logger(LOG_INFO, __FUNCTION__);
1321 if ((dp = opendir(dir_name))==NULL) {
1322 debug_msg_logger(LOG_ERR, "opendir: %s: %m", dir_name);
1326 while ((de = readdir(dp)) != NULL) {
1328 if (de->d_name && DOT_OR_DOTDOT(de->d_name))
1330 snprintf(path, sizeof(path), "%s/%s", dir_name, de->d_name);
1331 debug_msg_logger(LOG_ERR, "%s: %s", __FUNCTION__, path);
1333 if (lstat(path, &statbuf) != 0) {
1334 debug_msg_logger(LOG_ERR, "%s: %s: %m", __FUNCTION__, path);
1339 service(statbuf, path);
1342 restore(path, statbuf, var);
1345 read_config_file(path, var, event_mask);
1350 } /* End Function do_scan_and_service */
1352 static int mksymlink(const char *oldpath, const char *newpath)
1353 /* [SUMMARY] Create a symlink, creating intervening directories as required.
1354 <oldpath> The string contained in the symlink.
1355 <newpath> The name of the new symlink.
1356 [RETURNS] 0 on success, else -1.
1359 debug_msg_logger(LOG_INFO, __FUNCTION__);
1361 if (!make_dir_tree(newpath))
1364 if (symlink(oldpath, newpath) != 0) {
1365 if (errno != EEXIST) {
1366 debug_msg_logger(LOG_ERR, "%s: %s to %s: %m", __FUNCTION__, oldpath, newpath);
1371 } /* End Function mksymlink */
1374 static int make_dir_tree(const char *path)
1375 /* [SUMMARY] Creating intervening directories for a path as required.
1376 <path> The full pathname(including the leaf node).
1377 [RETURNS] TRUE on success, else FALSE.
1380 debug_msg_logger(LOG_INFO, __FUNCTION__);
1382 if (bb_make_directory(dirname((char *)path), -1, FILEUTILS_RECUR) == -1) {
1383 debug_msg_logger(LOG_ERR, "%s: %s: %m",__FUNCTION__, path);
1387 } /* End Function make_dir_tree */
1389 static int expand_expression(char *output, unsigned int outsize,
1391 const char *(*get_variable_func)(const char *variable, void *info),
1393 const char *devname,
1394 const regmatch_t *ex, unsigned int numexp)
1395 /* [SUMMARY] Expand environment variables and regular subexpressions in string.
1396 <output> The output expanded expression is written here.
1397 <length> The size of the output buffer.
1398 <input> The input expression. This may equal <<output>>.
1399 <get_variable> A function which will be used to get variable values. If
1400 this returns NULL, the environment is searched instead. If this is NULL,
1401 only the environment is searched.
1402 <info> An arbitrary pointer passed to <<get_variable>>.
1403 <devname> Device name; specifically, this is the string that contains all
1404 of the regular subexpressions.
1405 <ex> Array of start / end offsets into info->devname for each subexpression
1406 <numexp> Number of regular subexpressions found in <<devname>>.
1407 [RETURNS] TRUE on success, else FALSE.
1410 char temp[STRING_LENGTH];
1412 debug_msg_logger(LOG_INFO, __FUNCTION__);
1414 if (!st_expr_expand(temp, STRING_LENGTH, input, get_variable_func, info))
1416 expand_regexp(output, outsize, temp, devname, ex, numexp);
1418 } /* End Function expand_expression */
1420 static void expand_regexp(char *output, size_t outsize, const char *input,
1421 const char *devname,
1422 const regmatch_t *ex, unsigned int numex)
1423 /* [SUMMARY] Expand all occurrences of the regular subexpressions \0 to \9.
1424 <output> The output expanded expression is written here.
1425 <outsize> The size of the output buffer.
1426 <input> The input expression. This may NOT equal <<output>>, because
1427 supporting that would require yet another string-copy. However, it's not
1428 hard to write a simple wrapper function to add this functionality for those
1429 few cases that need it.
1430 <devname> Device name; specifically, this is the string that contains all
1431 of the regular subexpressions.
1432 <ex> An array of start and end offsets into <<devname>>, one for each
1434 <numex> Number of subexpressions in the offset-array <<ex>>.
1438 const char last_exp = '0' - 1 + numex;
1441 debug_msg_logger(LOG_INFO, __FUNCTION__);
1443 /* Guarantee NULL termination by writing an explicit '\0' character into
1444 the very last byte */
1446 output[--outsize] = '\0';
1447 /* Copy the input string into the output buffer, replacing '\\' with '\'
1448 and '\0' .. '\9' with subexpressions 0 .. 9, if they exist. Other \x
1449 codes are deleted */
1450 while ((c != '\0') && (outsize != 0)) {
1457 if ((c >= '0') && (c <= last_exp)) {
1458 const regmatch_t *subexp = ex + (c - '0');
1459 unsigned int sublen = subexp->rm_eo - subexp->rm_so;
1461 /* Range checking */
1462 if (sublen > outsize)
1464 strncpy(output, devname + subexp->rm_so, sublen);
1475 } /* End Function expand_regexp */
1478 /* from compat_name.c */
1480 struct translate_struct
1482 const char *match; /* The string to match to(up to length) */
1483 const char *format; /* Format of output, "%s" takes data past match string,
1484 NULL is effectively "%s"(just more efficient) */
1487 static struct translate_struct translate_table[] =
1490 {"printers/", "lp%s"},
1492 {"parports/", "parport%s"},
1495 {"loop/", "loop%s"},
1496 {"floppy/", "fd%s"},
1498 {"md/", "md%s"}, /* Meta-devices */
1502 {"pg/", "pg%s"}, /* Parallel port generic ATAPI interface*/
1504 {"staliomem/", "staliomem%s"}, /* Stallion serial driver control */
1505 {"tts/E", "ttyE%s"}, /* Stallion serial driver */
1506 {"cua/E", "cue%s"}, /* Stallion serial driver callout */
1507 {"tts/R", "ttyR%s"}, /* Rocketport serial driver */
1508 {"cua/R", "cur%s"}, /* Rocketport serial driver callout */
1509 {"ip2/", "ip2%s"}, /* Computone serial driver control */
1510 {"tts/F", "ttyF%s"}, /* Computone serial driver */
1511 {"cua/F", "cuf%s"}, /* Computone serial driver callout */
1512 {"tts/C", "ttyC%s"}, /* Cyclades serial driver */
1513 {"cua/C", "cub%s"}, /* Cyclades serial driver callout */
1514 {"tts/", "ttyS%s"}, /* Generic serial: must be after others */
1515 {"cua/", "cua%s"}, /* Generic serial: must be after others */
1516 {"input/js", "js%s"}, /* Joystick driver */
1520 const char *get_old_name(const char *devname, unsigned int namelen,
1521 char *buffer, unsigned int major, unsigned int minor)
1522 /* [SUMMARY] Translate a kernel-supplied name into an old name.
1523 <devname> The device name provided by the kernel.
1524 <namelen> The length of the name.
1525 <buffer> A buffer that may be used. This should be at least 128 bytes long.
1526 <major> The major number for the device.
1527 <minor> The minor number for the device.
1528 [RETURNS] A pointer to the old name if known, else NULL.
1531 const char *compat_name = NULL;
1533 struct translate_struct *trans;
1540 /* 1 to 5 "scsi/" , 6 to 9 "ide/host", 10 sbp/, 11 vcc/, 12 pty/ */
1541 static const char *const fmt[] = {
1543 "sg%u", /* scsi/generic */
1544 NULL, /* scsi/disc */
1545 "sr%u", /* scsi/cd */
1546 NULL, /* scsi/part */
1547 "nst%u%c", /* scsi/mt */
1548 "hd%c" , /* ide/host/disc */
1549 "hd%c" , /* ide/host/cd */
1550 "hd%c%s", /* ide/host/part */
1551 "%sht%d", /* ide/host/mt */
1552 "sbpcd%u", /* sbp/ */
1554 "%cty%c%c", /* pty/ */
1558 debug_msg_logger(LOG_INFO, __FUNCTION__);
1560 for (trans = translate_table; trans->match != NULL; ++trans) {
1561 len = strlen(trans->match);
1563 if (strncmp(devname, trans->match, len) == 0) {
1564 if (trans->format == NULL)
1565 return devname + len;
1566 sprintf(buffer, trans->format, devname + len);
1571 ptr = (strrchr(devname, '/') + 1);
1572 i = scan_dev_name(devname, namelen, ptr);
1574 if (i > 0 && i < 13)
1575 compat_name = buffer;
1579 debug_msg_logger(LOG_INFO, "%s: scan_dev_name = %d", __FUNCTION__, i);
1581 /* 1 == scsi/generic, 3 == scsi/cd, 10 == sbp/ */
1582 if (i == 1 || i == 3 || i == 10)
1583 sprintf(buffer, fmt[i], minor);
1585 /* 2 ==scsi/disc, 4 == scsi/part */
1586 if (i == 2 || i == 4)
1587 compat_name = write_old_sd_name(buffer, major, minor,((i == 2)?"":(ptr + 4)));
1594 sprintf(buffer, fmt[i], minor & 0x1f, mode);
1595 if (devname[namelen - 1] != 'n')
1598 /* 6 == ide/host/disc, 7 == ide/host/cd, 8 == ide/host/part */
1599 if (i == 6 || i == 7 || i == 8)
1600 /* last arg should be ignored for i == 6 or i== 7 */
1601 sprintf(buffer, fmt[i] , get_old_ide_name(major, minor), ptr + 4);
1603 /* 9 == ide/host/mt */
1605 sprintf(buffer, fmt[i], ptr + 2, minor & 0x7f);
1609 sprintf(buffer, fmt[i], devname + 4);
1610 if (buffer[3] == '0')
1615 pty1 = "pqrstuvwxyzabcde";
1616 pty2 = "0123456789abcdef";
1617 indexx = atoi(devname + 5);
1618 sprintf(buffer, fmt[i], (devname[4] == 'm') ? 'p' : 't', pty1[indexx >> 4], pty2[indexx & 0x0f]);
1621 if (ENABLE_DEBUG && compat_name != NULL)
1622 msg_logger(LOG_INFO, "%s: compat_name %s", __FUNCTION__, compat_name);
1625 } /* End Function get_old_name */
1627 static char get_old_ide_name(unsigned int major, unsigned int minor)
1628 /* [SUMMARY] Get the old IDE name for a device.
1629 <major> The major number for the device.
1630 <minor> The minor number for the device.
1631 [RETURNS] The drive letter.
1634 char letter = 'y'; /* 121 */
1635 char c = 'a'; /* 97 */
1638 debug_msg_logger(LOG_INFO, __FUNCTION__);
1640 /* I hope it works like the previous code as it saves a few bytes. Tito ;P */
1642 if (i == IDE0_MAJOR || i == IDE1_MAJOR || i == IDE2_MAJOR
1643 || i == IDE3_MAJOR || i == IDE4_MAJOR || i == IDE5_MAJOR
1644 || i == IDE6_MAJOR || i == IDE7_MAJOR || i == IDE8_MAJOR
1647 if ((unsigned int)i == major) {
1654 } while (i <= IDE9_MAJOR);
1659 } /* End Function get_old_ide_name */
1661 static char *write_old_sd_name(char *buffer,
1662 unsigned int major, unsigned int minor,
1664 /* [SUMMARY] Write the old SCSI disc name to a buffer.
1665 <buffer> The buffer to write to.
1666 <major> The major number for the device.
1667 <minor> The minor number for the device.
1668 <part> The partition string. Must be "" for a whole-disc entry.
1669 [RETURNS] A pointer to the buffer on success, else NULL.
1672 unsigned int disc_index;
1674 debug_msg_logger(LOG_INFO, __FUNCTION__);
1677 sprintf(buffer, "sd%c%s", 'a' + (minor >> 4), part);
1680 if ((major > 64) && (major < 72)) {
1681 disc_index = ((major - 64) << 4) +(minor >> 4);
1682 if (disc_index < 26)
1683 sprintf(buffer, "sd%c%s", 'a' + disc_index, part);
1685 sprintf(buffer, "sd%c%c%s", 'a' +(disc_index / 26) - 1, 'a' + disc_index % 26, part);
1689 } /* End Function write_old_sd_name */
1694 /*EXPERIMENTAL_FUNCTION*/
1696 int st_expr_expand(char *output, unsigned int length, const char *input,
1697 const char *(*get_variable_func)(const char *variable,
1700 /* [SUMMARY] Expand an expression using Borne Shell-like unquoted rules.
1701 <output> The output expanded expression is written here.
1702 <length> The size of the output buffer.
1703 <input> The input expression. This may equal <<output>>.
1704 <get_variable> A function which will be used to get variable values. If
1705 this returns NULL, the environment is searched instead. If this is NULL,
1706 only the environment is searched.
1707 <info> An arbitrary pointer passed to <<get_variable>>.
1708 [RETURNS] TRUE on success, else FALSE.
1713 unsigned int out_pos = 0;
1716 struct passwd *pwent;
1717 char buffer[BUFFER_SIZE], tmp[STRING_LENGTH];
1719 debug_msg_logger(LOG_INFO, __FUNCTION__);
1721 if (length > BUFFER_SIZE)
1722 length = BUFFER_SIZE;
1723 for (; TRUE; ++input) {
1724 switch (ch = *input) {
1726 /* Variable expansion */
1727 input = expand_variable(buffer, length, &out_pos, ++input, get_variable_func, info);
1732 /* Home directory expansion */
1734 if (isspace(ch) ||(ch == '/') ||(ch == '\0')) {
1735 /* User's own home directory: leave separator for next time */
1736 if ((env = getenv("HOME")) == NULL) {
1737 msg_logger(LOG_INFO, bb_msg_variable_not_found, "HOME");
1741 if (len + out_pos >= length)
1742 goto st_expr_expand_out;
1743 memcpy(buffer + out_pos, env, len + 1);
1747 /* Someone else's home directory */
1748 for (ptr = ++input; !isspace(ch) && (ch != '/') && (ch != '\0'); ch = *++ptr)
1751 if (len >= sizeof tmp)
1752 goto st_expr_expand_out;
1753 safe_memcpy(tmp, input, len);
1755 if ((pwent = getpwnam(tmp)) == NULL) {
1756 msg_logger(LOG_INFO, "no pwent for: %s", tmp);
1759 len = strlen(pwent->pw_dir);
1760 if (len + out_pos >= length)
1761 goto st_expr_expand_out;
1762 memcpy(buffer + out_pos, pwent->pw_dir, len + 1);
1768 if (out_pos >= length)
1769 goto st_expr_expand_out;
1770 buffer[out_pos++] = ch;
1772 memcpy(output, buffer, out_pos);
1781 msg_logger(LOG_INFO, bb_msg_small_buffer);
1783 } /* End Function st_expr_expand */
1786 /* Private functions follow */
1788 static const char *expand_variable(char *buffer, unsigned int length,
1789 unsigned int *out_pos, const char *input,
1790 const char *(*func)(const char *variable,
1793 /* [SUMMARY] Expand a variable.
1794 <buffer> The buffer to write to.
1795 <length> The length of the output buffer.
1796 <out_pos> The current output position. This is updated.
1797 <input> A pointer to the input character pointer.
1798 <func> A function which will be used to get variable values. If this
1799 returns NULL, the environment is searched instead. If this is NULL, only
1800 the environment is searched.
1801 <info> An arbitrary pointer passed to <<func>>.
1802 <errfp> Diagnostic messages are written here.
1803 [RETURNS] A pointer to the end of this subexpression on success, else NULL.
1808 unsigned int open_braces;
1809 const char *env, *ptr;
1810 char tmp[STRING_LENGTH];
1812 debug_msg_logger(LOG_INFO, __FUNCTION__);
1816 /* Special case for "$$": PID */
1817 sprintf(tmp, "%d",(int) getpid());
1819 if (len + *out_pos >= length)
1820 goto expand_variable_out;
1822 memcpy(buffer + *out_pos, tmp, len + 1);
1826 /* Ordinary variable expansion, possibly in braces */
1828 /* Simple variable expansion */
1829 for (ptr = input; isalnum(ch) || (ch == '_') || (ch == ':'); ch = *++ptr)
1832 if ((size_t)len >= sizeof tmp)
1833 goto expand_variable_out;
1835 safe_memcpy(tmp, input, len);
1837 if ((env = get_variable_v2(tmp, func, info)) == NULL) {
1838 msg_logger(LOG_INFO, bb_msg_variable_not_found, tmp);
1842 if (len + *out_pos >= length)
1843 goto expand_variable_out;
1845 memcpy(buffer + *out_pos, env, len + 1);
1849 /* Variable in braces: check for ':' tricks */
1851 for (ptr = input; isalnum(ch) || (ch == '_'); ch = *++ptr)
1854 /* Must be simple variable expansion with "${var}" */
1856 if ((size_t)len >= sizeof tmp)
1857 goto expand_variable_out;
1859 safe_memcpy(tmp, input, len);
1860 ptr = expand_variable(buffer, length, out_pos, tmp, func, info);
1865 if (ch != ':' || ptr[1] != '-') {
1866 msg_logger(LOG_INFO, "illegal char in var name");
1869 /* It's that handy "${var:-word}" expression. Check if var is defined */
1871 if ((size_t)len >= sizeof tmp)
1872 goto expand_variable_out;
1874 safe_memcpy(tmp, input, len);
1875 /* Move input pointer to ':' */
1877 /* First skip to closing brace, taking note of nested expressions */
1880 for (open_braces = 1; open_braces > 0; ch = *++ptr) {
1889 msg_logger(LOG_INFO,"\"}\" not found in: %s", input);
1896 /* At this point ptr should point to closing brace of "${var:-word}" */
1897 if ((env = get_variable_v2(tmp, func, info)) != NULL) {
1898 /* Found environment variable, so skip the input to the closing brace
1899 and return the variable */
1902 if (len + *out_pos >= length)
1903 goto expand_variable_out;
1905 memcpy(buffer + *out_pos, env, len + 1);
1909 /* Environment variable was not found, so process word. Advance input
1910 pointer to start of word in "${var:-word}" */
1913 if ((size_t)len >= sizeof tmp)
1914 goto expand_variable_out;
1916 safe_memcpy(tmp, input, len);
1918 if (!st_expr_expand(tmp, STRING_LENGTH, tmp, func, info))
1921 if (len + *out_pos >= length)
1922 goto expand_variable_out;
1924 memcpy(buffer + *out_pos, tmp, len + 1);
1927 expand_variable_out:
1928 msg_logger(LOG_INFO, bb_msg_small_buffer);
1930 } /* End Function expand_variable */
1933 static const char *get_variable_v2(const char *variable,
1934 const char *(*func)(const char *variable, void *info),
1936 /* [SUMMARY] Get a variable from the environment or .
1937 <variable> The variable name.
1938 <func> A function which will be used to get the variable. If this returns
1939 NULL, the environment is searched instead. If this is NULL, only the
1940 environment is searched.
1941 [RETURNS] The value of the variable on success, else NULL.
1946 debug_msg_logger(LOG_INFO, __FUNCTION__);
1949 value = (*func)(variable, info);
1953 return getenv(variable);
1954 } /* End Function get_variable */