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 int get_uid_gid(int flag, const char *string);
238 static void safe_memcpy(char * dest, const char * src, int len);
239 static unsigned int scan_dev_name_common(const char *d, unsigned int n, int addendum, const char *ptr);
240 static unsigned int scan_dev_name(const char *d, unsigned int n, const char *ptr);
242 /* Structs and vars */
243 static struct config_entry_struct *first_config = NULL;
244 static struct config_entry_struct *last_config = NULL;
245 static char *mount_point = NULL;
246 static volatile int caught_signal = FALSE;
247 static volatile int caught_sighup = FALSE;
248 static struct initial_symlink_struct {
251 } initial_symlinks[] = {
252 {"/proc/self/fd", "fd"},
259 static struct event_type {
260 unsigned int type; /* The DEVFSD_NOTIFY_* value */
261 const char *config_name; /* The name used in the config file */
263 {DEVFSD_NOTIFY_REGISTERED, "REGISTER"},
264 {DEVFSD_NOTIFY_UNREGISTERED, "UNREGISTER"},
265 {DEVFSD_NOTIFY_ASYNC_OPEN, "ASYNC_OPEN"},
266 {DEVFSD_NOTIFY_CLOSE, "CLOSE"},
267 {DEVFSD_NOTIFY_LOOKUP, "LOOKUP"},
268 {DEVFSD_NOTIFY_CHANGE, "CHANGE"},
269 {DEVFSD_NOTIFY_CREATE, "CREATE"},
270 {DEVFSD_NOTIFY_DELETE, "DELETE"},
274 /* Busybox messages */
276 static const char bb_msg_proto_rev[] ALIGN1 = "protocol revision";
277 static const char bb_msg_bad_config[] ALIGN1 = "bad %s config file: %s";
278 static const char bb_msg_small_buffer[] ALIGN1 = "buffer too small";
279 static const char bb_msg_variable_not_found[] ALIGN1 = "variable: %s not found";
282 #if ENABLE_DEVFSD_VERBOSE || ENABLE_DEBUG
283 #define info_logger(p, fmt, args...) bb_info_msg(fmt, ## args)
284 #define msg_logger(p, fmt, args...) bb_error_msg(fmt, ## args)
285 #define msg_logger_and_die(p, fmt, args...) bb_error_msg_and_die(fmt, ## args)
286 #define error_logger(p, fmt, args...) bb_perror_msg(fmt, ## args)
287 #define error_logger_and_die(p, fmt, args...) bb_perror_msg_and_die(fmt, ## args)
289 #define info_logger(p, fmt, args...)
290 #define msg_logger(p, fmt, args...)
291 #define msg_logger_and_die(p, fmt, args...) exit(1)
292 #define error_logger(p, fmt, args...)
293 #define error_logger_and_die(p, fmt, args...) exit(1)
296 static void safe_memcpy(char *dest, const char *src, int len)
298 memcpy(dest , src, len);
302 static unsigned int scan_dev_name_common(const char *d, unsigned int n, int addendum, const char *ptr)
304 if (d[n - 4] == 'd' && d[n - 3] == 'i' && d[n - 2] == 's' && d[n - 1] == 'c')
306 if (d[n - 2] == 'c' && d[n - 1] == 'd')
308 if (ptr[0] == 'p' && ptr[1] == 'a' && ptr[2] == 'r' && ptr[3] == 't')
310 if (ptr[n - 2] == 'm' && ptr[n - 1] == 't')
315 static unsigned int scan_dev_name(const char *d, unsigned int n, const char *ptr)
317 if (d[0] == 's' && d[1] == 'c' && d[2] == 's' && d[3] == 'i' && d[4] == '/') {
318 if (d[n - 7] == 'g' && d[n - 6] == 'e' && d[n - 5] == 'n'
319 && d[n - 4] == 'e' && d[n - 3] == 'r' && d[n - 2] == 'i' && d[n - 1] == 'c'
322 return scan_dev_name_common(d, n, 0, ptr);
324 if (d[0] == 'i' && d[1] == 'd' && d[2] == 'e' && d[3] == '/'
325 && d[4] == 'h' && d[5] == 'o' && d[6] == 's' && d[7] == 't'
327 return scan_dev_name_common(d, n, 4, ptr);
328 if (d[0] == 's' && d[1] == 'b' && d[2] == 'p' && d[3] == '/')
330 if (d[0] == 'v' && d[1] == 'c' && d[2] == 'c' && d[3] == '/')
332 if (d[0] == 'p' && d[1] == 't' && d[2] == 'y' && d[3] == '/')
337 /* Public functions follow */
339 int devfsd_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
340 int devfsd_main(int argc, char **argv)
342 int print_version = FALSE;
343 int do_daemon = TRUE;
344 int no_polling = FALSE;
346 int fd, proto_rev, count;
347 unsigned long event_mask = 0;
348 struct sigaction new_action;
349 struct initial_symlink_struct *curr;
354 for (count = 2; count < argc; ++count) {
355 if (argv[count][0] == '-') {
356 if (argv[count][1] == 'v' && !argv[count][2]) /* -v */
357 print_version = TRUE;
358 else if (ENABLE_DEVFSD_FG_NP && argv[count][1] == 'f'
359 && argv[count][2] == 'g' && !argv[count][3]) /* -fg */
361 else if (ENABLE_DEVFSD_FG_NP && argv[count][1] == 'n'
362 && argv[count][2] == 'p' && !argv[count][3]) /* -np */
369 mount_point = bb_simplify_path(argv[1]);
373 fd = xopen(".devfsd", O_RDONLY);
374 close_on_exec_on(fd);
375 xioctl(fd, DEVFSDIOC_GET_PROTO_REV, &proto_rev);
377 /*setup initial entries */
378 for (curr = initial_symlinks; curr->dest != NULL; ++curr)
379 symlink(curr->dest, curr->name);
381 /* NB: The check for CONFIG_FILE is done in read_config_file() */
383 if (print_version || (DEVFSD_PROTOCOL_REVISION_DAEMON != proto_rev)) {
384 printf("%s v%s\nDaemon %s:\t%d\nKernel-side %s:\t%d\n",
385 applet_name, DEVFSD_VERSION, bb_msg_proto_rev,
386 DEVFSD_PROTOCOL_REVISION_DAEMON, bb_msg_proto_rev, proto_rev);
387 if (DEVFSD_PROTOCOL_REVISION_DAEMON != proto_rev)
388 bb_error_msg_and_die("%s mismatch!", bb_msg_proto_rev);
389 exit(EXIT_SUCCESS); /* -v */
391 /* Tell kernel we are special(i.e. we get to see hidden entries) */
392 xioctl(fd, DEVFSDIOC_SET_EVENT_MASK, 0);
394 sigemptyset(&new_action.sa_mask);
395 new_action.sa_flags = 0;
397 /* Set up SIGHUP and SIGUSR1 handlers */
398 new_action.sa_handler = signal_handler;
399 if (sigaction(SIGHUP, &new_action, NULL) != 0 || sigaction(SIGUSR1, &new_action, NULL) != 0)
400 bb_error_msg_and_die("sigaction");
402 printf("%s v%s started for %s\n",applet_name, DEVFSD_VERSION, mount_point);
404 /* Set umask so that mknod(2), open(2) and mkdir(2) have complete control over permissions */
406 read_config_file((char*)CONFIG_FILE, FALSE, &event_mask);
407 /* Do the scan before forking, so that boot scripts see the finished product */
408 dir_operation(SERVICE, mount_point, 0, NULL);
410 if (ENABLE_DEVFSD_FG_NP && no_polling)
413 if (ENABLE_DEVFSD_VERBOSE || ENABLE_DEBUG)
414 logmode = LOGMODE_BOTH;
415 else if (do_daemon == TRUE)
416 logmode = LOGMODE_SYSLOG;
417 /* This is the default */
419 logmode = LOGMODE_STDIO; */
422 /* Release so that the child can grab it */
423 xioctl(fd, DEVFSDIOC_RELEASE_EVENT_QUEUE, 0);
424 bb_daemonize_or_rexec(0, argv);
425 } else if (ENABLE_DEVFSD_FG_NP) {
426 setpgid(0, 0); /* Become process group leader */
430 do_scan = do_servicing(fd, event_mask);
433 read_config_file((char*)CONFIG_FILE, FALSE, &event_mask);
435 dir_operation(SERVICE, mount_point, 0, NULL);
437 if (ENABLE_FEATURE_CLEAN_UP) free(mount_point);
438 } /* End Function main */
441 /* Private functions follow */
443 static void read_config_file(char *path, int optional, unsigned long *event_mask)
444 /* [SUMMARY] Read a configuration database.
445 <path> The path to read the database from. If this is a directory, all
446 entries in that directory will be read(except hidden entries).
447 <optional> If TRUE, the routine will silently ignore a missing config file.
448 <event_mask> The event mask is written here. This is not initialised.
454 char buf[STRING_LENGTH];
458 if (stat(path, &statbuf) == 0) {
459 /* Don't read 0 length files: ignored */
460 /*if (statbuf.st_size == 0)
462 if (S_ISDIR(statbuf.st_mode)) {
463 p = bb_simplify_path(path);
464 dir_operation(READ_CONFIG, p, 0, event_mask);
468 fp = fopen(path, "r");
470 while (fgets(buf, STRING_LENGTH, fp) != NULL) {
471 /* Skip whitespace */
473 line = skip_whitespace(line);
474 if (line[0] == '\0' || line[0] == '#')
476 process_config_line(line, event_mask);
480 goto read_config_file_err;
483 read_config_file_err:
484 if (optional == 0 && errno == ENOENT)
485 error_logger_and_die(LOG_ERR, "read config file: %s", path);
487 } /* End Function read_config_file */
489 static void process_config_line(const char *line, unsigned long *event_mask)
490 /* [SUMMARY] Process a line from a configuration file.
491 <line> The configuration line.
492 <event_mask> The event mask is written here. This is not initialised.
497 struct config_entry_struct *new;
498 char p[MAX_ARGS][STRING_LENGTH];
499 char when[STRING_LENGTH], what[STRING_LENGTH];
500 char name[STRING_LENGTH];
501 const char *msg = "";
505 /* !!!! Only Uppercase Keywords in devsfd.conf */
506 static const char options[] ALIGN1 =
507 "CLEAR_CONFIG\0""INCLUDE\0""OPTIONAL_INCLUDE\0"
508 "RESTORE\0""PERMISSIONS\0""MODLOAD\0""EXECUTE\0"
509 "COPY\0""IGNORE\0""MKOLDCOMPAT\0""MKNEWCOMPAT\0"
510 "RMOLDCOMPAT\0""RMNEWCOMPAT\0";
512 for (count = 0; count < MAX_ARGS; ++count)
514 num_args = sscanf(line, "%s %s %s %s %s %s %s %s %s %s",
516 p[0], p[1], p[2], p[3], p[4], p[5], p[6]);
518 i = index_in_strings(options, when);
528 goto process_config_line_err;
530 /* "INCLUDE" & "OPTIONAL_INCLUDE" */
531 if (i == 1 || i == 2) {
532 st_expr_expand(name, STRING_LENGTH, name, get_variable, NULL);
533 info_logger(LOG_INFO, "%sinclude: %s", (toupper(when[0]) == 'I') ? "": "optional_", name);
534 read_config_file(name, (toupper(when[0]) == 'I') ? FALSE : TRUE, event_mask);
539 dir_operation(RESTORE, name, strlen(name),NULL);
543 goto process_config_line_err;
545 new = xzalloc(sizeof *new);
547 for (count = 0; event_types[count].config_name != NULL; ++count) {
548 if (strcasecmp(when, event_types[count].config_name) != 0)
550 new->action.when = event_types[count].type;
553 if (event_types[count].config_name == NULL) {
555 goto process_config_line_err;
558 i = index_in_strings(options, what);
561 case 4: /* "PERMISSIONS" */
562 new->action.what = AC_PERMISSIONS;
563 /* Get user and group */
564 ptr = strchr(p[0], '.');
567 goto process_config_line_err; /*"missing '.' in UID.GID"*/
571 new->u.permissions.uid = get_uid_gid(UID, p[0]);
572 new->u.permissions.gid = get_uid_gid(GID, ptr);
574 new->u.permissions.mode = get_mode(p[1]);
576 case 5: /* MODLOAD */
577 /*This action will pass "/dev/$devname"(i.e. "/dev/" prefixed to
578 the device name) to the module loading facility. In addition,
579 the /etc/modules.devfs configuration file is used.*/
580 if (ENABLE_DEVFSD_MODLOAD)
581 new->action.what = AC_MODLOAD;
583 case 6: /* EXECUTE */
584 new->action.what = AC_EXECUTE;
587 for (count = 0; count < num_args; ++count)
588 new->u.execute.argv[count] = xstrdup(p[count]);
590 new->u.execute.argv[num_args] = NULL;
593 new->action.what = AC_COPY;
596 goto process_config_line_err; /* missing path and function in line */
598 new->u.copy.source = xstrdup(p[0]);
599 new->u.copy.destination = xstrdup(p[1]);
603 case 9: /* MKOLDCOMPAT */
605 case 10: /* MKNEWCOMPAT */
607 case 11:/* RMOLDCOMPAT */
609 case 12: /* RMNEWCOMPAT */
615 new->action.what = i - 2;
619 goto process_config_line_err;
623 xregcomp(&new->preg, name, REG_EXTENDED);
625 *event_mask |= 1 << new->action.when;
627 if (first_config == NULL)
630 last_config->next = new;
634 process_config_line_err:
635 msg_logger_and_die(LOG_ERR, bb_msg_bad_config, msg , line);
636 } /* End Function process_config_line */
638 static int do_servicing(int fd, unsigned long event_mask)
639 /* [SUMMARY] Service devfs changes until a signal is received.
640 <fd> The open control file.
641 <event_mask> The event mask.
642 [RETURNS] TRUE if SIGHUP was caught, else FALSE.
646 struct devfsd_notify_struct info;
648 /* (void*) cast is only in order to match prototype */
649 xioctl(fd, DEVFSDIOC_SET_EVENT_MASK, (void*)event_mask);
650 while (!caught_signal) {
652 bytes = read(fd,(char *) &info, sizeof info);
654 break; /* Must test for this first */
656 continue; /* Yes, the order is important */
662 int c_sighup = caught_sighup;
664 caught_signal = FALSE;
665 caught_sighup = FALSE;
668 msg_logger_and_die(LOG_ERR, "read error on control file");
669 } /* End Function do_servicing */
671 static void service_name(const struct devfsd_notify_struct *info)
672 /* [SUMMARY] Service a single devfs change.
673 <info> The devfs change.
678 regmatch_t mbuf[MAX_SUBEXPR];
679 struct config_entry_struct *entry;
681 if (ENABLE_DEBUG && info->overrun_count > 0)
682 msg_logger(LOG_ERR, "lost %u events", info->overrun_count);
684 /* Discard lookups on "/dev/log" and "/dev/initctl" */
685 if (info->type == DEVFSD_NOTIFY_LOOKUP
686 && ((info->devname[0] == 'l' && info->devname[1] == 'o'
687 && info->devname[2] == 'g' && !info->devname[3])
688 || (info->devname[0] == 'i' && info->devname[1] == 'n'
689 && info->devname[2] == 'i' && info->devname[3] == 't'
690 && info->devname[4] == 'c' && info->devname[5] == 't'
691 && info->devname[6] == 'l' && !info->devname[7]))
695 for (entry = first_config; entry != NULL; entry = entry->next) {
696 /* First check if action matches the type, then check if name matches */
697 if (info->type != entry->action.when
698 || regexec(&entry->preg, info->devname, MAX_SUBEXPR, mbuf, 0) != 0)
700 for (n = 0;(n < MAX_SUBEXPR) && (mbuf[n].rm_so != -1); ++n)
703 switch (entry->action.what) {
705 action_permissions(info, entry);
708 if (ENABLE_DEVFSD_MODLOAD)
709 action_modload(info, entry);
712 action_execute(info, entry, mbuf, n);
715 action_copy(info, entry, mbuf, n);
724 action_compat(info, entry->action.what);
727 msg_logger_and_die(LOG_ERR, "Unknown action");
730 } /* End Function service_name */
732 static void action_permissions(const struct devfsd_notify_struct *info,
733 const struct config_entry_struct *entry)
734 /* [SUMMARY] Update permissions for a device entry.
735 <info> The devfs change.
736 <entry> The config file entry.
742 if (stat(info->devname, &statbuf) != 0
743 || chmod(info->devname, (statbuf.st_mode & S_IFMT) | (entry->u.permissions.mode & ~S_IFMT)) != 0
744 || chown(info->devname, entry->u.permissions.uid, entry->u.permissions.gid) != 0
746 error_logger(LOG_ERR, "Can't chmod or chown: %s", info->devname);
747 } /* End Function action_permissions */
749 static void action_modload(const struct devfsd_notify_struct *info,
750 const struct config_entry_struct *entry ATTRIBUTE_UNUSED)
751 /* [SUMMARY] Load a module.
752 <info> The devfs change.
753 <entry> The config file entry.
759 argv[0] = (char*)MODPROBE;
760 argv[1] = (char*)MODPROBE_SWITCH_1; /* "-k" */
761 argv[2] = (char*)MODPROBE_SWITCH_2; /* "-C" */
762 argv[3] = (char*)CONFIG_MODULES_DEVFS;
763 argv[4] = concat_path_file("/dev", info->devname); /* device */
766 wait4pid(xspawn(argv));
768 } /* End Function action_modload */
770 static void action_execute(const struct devfsd_notify_struct *info,
771 const struct config_entry_struct *entry,
772 const regmatch_t *regexpr, unsigned int numexpr)
773 /* [SUMMARY] Execute a programme.
774 <info> The devfs change.
775 <entry> The config file entry.
776 <regexpr> The number of subexpression(start, end) offsets within the
778 <numexpr> The number of elements within <<regexpr>>.
783 struct get_variable_info gv_info;
784 char *argv[MAX_ARGS + 1];
785 char largv[MAX_ARGS + 1][STRING_LENGTH];
788 gv_info.devname = info->devname;
789 snprintf(gv_info.devpath, sizeof(gv_info.devpath), "%s/%s", mount_point, info->devname);
790 for (count = 0; entry->u.execute.argv[count] != NULL; ++count) {
791 expand_expression(largv[count], STRING_LENGTH,
792 entry->u.execute.argv[count],
793 get_variable, &gv_info,
794 gv_info.devname, regexpr, numexpr);
795 argv[count] = largv[count];
798 wait4pid(spawn(argv));
799 } /* End Function action_execute */
802 static void action_copy(const struct devfsd_notify_struct *info,
803 const struct config_entry_struct *entry,
804 const regmatch_t *regexpr, unsigned int numexpr)
805 /* [SUMMARY] Copy permissions.
806 <info> The devfs change.
807 <entry> The config file entry.
808 <regexpr> This list of subexpression(start, end) offsets within the
810 <numexpr> The number of elements in <<regexpr>>.
815 struct get_variable_info gv_info;
816 struct stat source_stat, dest_stat;
817 char source[STRING_LENGTH], destination[STRING_LENGTH];
820 dest_stat.st_mode = 0;
822 if ((info->type == DEVFSD_NOTIFY_CHANGE) && S_ISLNK(info->mode))
825 gv_info.devname = info->devname;
827 snprintf(gv_info.devpath, sizeof(gv_info.devpath), "%s/%s", mount_point, info->devname);
828 expand_expression(source, STRING_LENGTH, entry->u.copy.source,
829 get_variable, &gv_info, gv_info.devname,
832 expand_expression(destination, STRING_LENGTH, entry->u.copy.destination,
833 get_variable, &gv_info, gv_info.devname,
836 if (!make_dir_tree(destination) || lstat(source, &source_stat) != 0)
838 lstat(destination, &dest_stat);
839 new_mode = source_stat.st_mode & ~S_ISVTX;
840 if (info->type == DEVFSD_NOTIFY_CREATE)
842 else if ((info->type == DEVFSD_NOTIFY_CHANGE) &&(dest_stat.st_mode & S_ISVTX))
844 ret = copy_inode(destination, &dest_stat, new_mode, source, &source_stat);
845 if (ENABLE_DEBUG && ret && (errno != EEXIST))
846 error_logger(LOG_ERR, "copy_inode: %s to %s", source, destination);
847 } /* End Function action_copy */
849 static void action_compat(const struct devfsd_notify_struct *info, unsigned int action)
850 /* [SUMMARY] Process a compatibility request.
851 <info> The devfs change.
852 <action> The action to take.
857 const char *compat_name = NULL;
858 const char *dest_name = info->devname;
860 char compat_buf[STRING_LENGTH], dest_buf[STRING_LENGTH];
861 int mode, host, bus, target, lun;
864 /* 1 to 5 "scsi/" , 6 to 9 "ide/host" */
865 static const char *const fmt[] = {
867 "sg/c%db%dt%du%d", /* scsi/generic */
868 "sd/c%db%dt%du%d", /* scsi/disc */
869 "sr/c%db%dt%du%d", /* scsi/cd */
870 "sd/c%db%dt%du%dp%d", /* scsi/part */
871 "st/c%db%dt%du%dm%d%c", /* scsi/mt */
872 "ide/hd/c%db%dt%du%d", /* ide/host/disc */
873 "ide/cd/c%db%dt%du%d", /* ide/host/cd */
874 "ide/hd/c%db%dt%du%dp%d", /* ide/host/part */
875 "ide/mt/c%db%dt%du%d%s", /* ide/host/mt */
879 /* First construct compatibility name */
883 compat_name = get_old_name(info->devname, info->namelen, compat_buf, info->major, info->minor);
887 ptr = bb_basename(info->devname);
888 i = scan_dev_name(info->devname, info->namelen, ptr);
894 sscanf(info->devname + ((i < 6) ? 5 : 4), "host%d/bus%d/target%d/lun%d/", &host, &bus, &target, &lun);
895 snprintf(dest_buf, sizeof(dest_buf), "../%s", info->devname + (( i > 5) ? 4 : 0));
896 dest_name = dest_buf;
897 compat_name = compat_buf;
900 /* 1 == scsi/generic 2 == scsi/disc 3 == scsi/cd 6 == ide/host/disc 7 == ide/host/cd */
901 if (i == 1 || i == 2 || i == 3 || i == 6 || i ==7)
902 sprintf(compat_buf, fmt[i], host, bus, target, lun);
904 /* 4 == scsi/part 8 == ide/host/part */
905 if (i == 4 || i == 8)
906 sprintf(compat_buf, fmt[i], host, bus, target, lun, atoi(ptr + 4));
910 rewind_ = info->devname[info->namelen - 1];
914 if (ptr[2] == 'l' /*108*/ || ptr[2] == 'm'/*109*/)
915 mode = ptr[2] - 107; /* 1 or 2 */
918 sprintf(compat_buf, fmt[i], host, bus, target, lun, mode, rewind_);
921 /* 9 == ide/host/mt */
923 snprintf(compat_buf, sizeof(compat_buf), fmt[i], host, bus, target, lun, ptr + 2);
925 } /* switch (action) */
927 if (compat_name == NULL)
930 /* Now decide what to do with it */
934 mksymlink(dest_name, compat_name);
938 ret = unlink(compat_name);
939 if (ENABLE_DEBUG && ret)
940 error_logger(LOG_ERR, "unlink: %s", compat_name);
943 } /* switch (action) */
944 } /* End Function action_compat */
946 static void restore(char *spath, struct stat source_stat, int rootlen)
949 struct stat dest_stat;
951 dest_stat.st_mode = 0;
952 dpath = concat_path_file(mount_point, spath + rootlen);
953 lstat(dpath, &dest_stat);
955 if (S_ISLNK(source_stat.st_mode) || (source_stat.st_mode & S_ISVTX))
956 copy_inode(dpath, &dest_stat,(source_stat.st_mode & ~S_ISVTX) , spath, &source_stat);
958 if (S_ISDIR(source_stat.st_mode))
959 dir_operation(RESTORE, spath, rootlen,NULL);
963 static int copy_inode(const char *destpath, const struct stat *dest_stat,
965 const char *sourcepath, const struct stat *source_stat)
966 /* [SUMMARY] Copy an inode.
967 <destpath> The destination path. An existing inode may be deleted.
968 <dest_stat> The destination stat(2) information.
969 <new_mode> The desired new mode for the destination.
970 <sourcepath> The source path.
971 <source_stat> The source stat(2) information.
972 [RETURNS] TRUE on success, else FALSE.
975 int source_len, dest_len;
976 char source_link[STRING_LENGTH], dest_link[STRING_LENGTH];
978 struct sockaddr_un un_addr;
979 char symlink_val[STRING_LENGTH];
981 if ((source_stat->st_mode & S_IFMT) ==(dest_stat->st_mode & S_IFMT)) {
983 if (S_ISLNK(source_stat->st_mode)) {
984 source_len = readlink(sourcepath, source_link, STRING_LENGTH - 1);
986 || (dest_len = readlink(destpath, dest_link, STRING_LENGTH - 1)) < 0
989 source_link[source_len] = '\0';
990 dest_link[dest_len] = '\0';
991 if ((source_len != dest_len) || (strcmp(source_link, dest_link) != 0)) {
993 symlink(source_link, destpath);
996 } /* Else not a symlink */
997 chmod(destpath, new_mode & ~S_IFMT);
998 chown(destpath, source_stat->st_uid, source_stat->st_gid);
1001 /* Different types: unlink and create */
1003 switch (source_stat->st_mode & S_IFMT) {
1005 fd = socket(AF_UNIX, SOCK_STREAM, 0);
1008 un_addr.sun_family = AF_UNIX;
1009 snprintf(un_addr.sun_path, sizeof(un_addr.sun_path), "%s", destpath);
1010 val = bind(fd,(struct sockaddr *) &un_addr,(int) sizeof un_addr);
1012 if (val != 0 || chmod(destpath, new_mode & ~S_IFMT) != 0)
1016 val = readlink(sourcepath, symlink_val, STRING_LENGTH - 1);
1019 symlink_val[val] = '\0';
1020 if (symlink(symlink_val, destpath) == 0)
1024 fd = open(destpath, O_RDONLY | O_CREAT, new_mode & ~S_IFMT);
1028 if (chmod(destpath, new_mode & ~S_IFMT) != 0)
1034 if (mknod(destpath, new_mode, source_stat->st_rdev) != 0)
1038 if (mkdir(destpath, new_mode & ~S_IFMT) != 0)
1041 if (chown(destpath, source_stat->st_uid, source_stat->st_gid) == 0)
1046 } /* End Function copy_inode */
1048 static void free_config(void)
1049 /* [SUMMARY] Free the configuration information.
1053 struct config_entry_struct *c_entry;
1056 for (c_entry = first_config; c_entry != NULL; c_entry = next) {
1059 next = c_entry->next;
1060 regfree(&c_entry->preg);
1061 if (c_entry->action.what == AC_EXECUTE) {
1062 for (count = 0; count < MAX_ARGS; ++count) {
1063 if (c_entry->u.execute.argv[count] == NULL)
1065 free(c_entry->u.execute.argv[count]);
1070 first_config = NULL;
1072 } /* End Function free_config */
1074 static int get_uid_gid(int flag, const char *string)
1075 /* [SUMMARY] Convert a string to a UID or GID value.
1076 <flag> "UID" or "GID".
1077 <string> The string.
1078 [RETURNS] The UID or GID value.
1081 struct passwd *pw_ent;
1082 struct group *grp_ent;
1083 static const char *msg;
1085 if (ENABLE_DEVFSD_VERBOSE)
1088 if (isdigit(string[0]) ||((string[0] == '-') && isdigit(string[1])))
1089 return atoi(string);
1091 if (flag == UID && (pw_ent = getpwnam(string)) != NULL)
1092 return pw_ent->pw_uid;
1094 if (flag == GID && (grp_ent = getgrnam(string)) != NULL)
1095 return grp_ent->gr_gid;
1096 else if (ENABLE_DEVFSD_VERBOSE)
1099 if (ENABLE_DEVFSD_VERBOSE)
1100 msg_logger(LOG_ERR,"unknown %s: %s, defaulting to %cid=0", msg, string, msg[0]);
1102 }/* End Function get_uid_gid */
1104 static mode_t get_mode(const char *string)
1105 /* [SUMMARY] Convert a string to a mode value.
1106 <string> The string.
1107 [RETURNS] The mode value.
1113 if (isdigit(string[0]))
1114 return strtoul(string, NULL, 8);
1115 if (strlen(string) != 9)
1116 msg_logger_and_die(LOG_ERR, "bad mode: %s", string);
1121 if (string[0] == 'r' || string[0] == 'w' || string[0] == 'x')
1127 } /* End Function get_mode */
1129 static void signal_handler(int sig)
1131 caught_signal = TRUE;
1133 caught_sighup = TRUE;
1135 info_logger(LOG_INFO, "Caught signal %d", sig);
1136 } /* End Function signal_handler */
1138 static const char *get_variable(const char *variable, void *info)
1140 static char sbuf[sizeof(int)*3 + 2]; /* sign and NUL */
1142 char hostname[STRING_LENGTH];
1143 struct get_variable_info *gv_info = info;
1144 const char *field_names[] = {
1145 "hostname", "mntpt", "devpath", "devname",
1146 "uid", "gid", "mode", hostname, mount_point,
1147 gv_info->devpath, gv_info->devname, NULL
1151 if (gethostname(hostname, STRING_LENGTH - 1) != 0)
1152 /* Here on error we should do exit(RV_SYS_ERROR), instead we do exit(EXIT_FAILURE) */
1153 error_logger_and_die(LOG_ERR, "gethostname");
1155 hostname[STRING_LENGTH - 1] = '\0';
1157 /* index_in_str_array returns i>=0 */
1158 i = index_in_str_array(field_names, variable);
1160 if (i > 6 || i < 0 || (i > 1 && gv_info == NULL))
1162 if (i >= 0 && i <= 3)
1163 return field_names[i + 7];
1166 sprintf(sbuf, "%u", gv_info->info->uid);
1168 sprintf(sbuf, "%u", gv_info->info->gid);
1170 sprintf(sbuf, "%o", gv_info->info->mode);
1172 } /* End Function get_variable */
1174 static void service(struct stat statbuf, char *path)
1176 struct devfsd_notify_struct info;
1178 memset(&info, 0, sizeof info);
1179 info.type = DEVFSD_NOTIFY_REGISTERED;
1180 info.mode = statbuf.st_mode;
1181 info.major = major(statbuf.st_rdev);
1182 info.minor = minor(statbuf.st_rdev);
1183 info.uid = statbuf.st_uid;
1184 info.gid = statbuf.st_gid;
1185 snprintf(info.devname, sizeof(info.devname), "%s", path + strlen(mount_point) + 1);
1186 info.namelen = strlen(info.devname);
1187 service_name(&info);
1188 if (S_ISDIR(statbuf.st_mode))
1189 dir_operation(SERVICE, path, 0, NULL);
1192 static void dir_operation(int type, const char * dir_name, int var, unsigned long *event_mask)
1193 /* [SUMMARY] Scan a directory tree and generate register events on leaf nodes.
1194 <flag> To choose which function to perform
1195 <dp> The directory pointer. This is closed upon completion.
1196 <dir_name> The name of the directory.
1197 <rootlen> string length parameter.
1201 struct stat statbuf;
1206 dp = warn_opendir(dir_name);
1210 while ((de = readdir(dp)) != NULL) {
1212 if (de->d_name && DOT_OR_DOTDOT(de->d_name))
1214 path = concat_path_file(dir_name, de->d_name);
1215 if (lstat(path, &statbuf) == 0) {
1218 service(statbuf, path);
1221 restore(path, statbuf, var);
1224 read_config_file(path, var, event_mask);
1231 } /* End Function do_scan_and_service */
1233 static int mksymlink(const char *oldpath, const char *newpath)
1234 /* [SUMMARY] Create a symlink, creating intervening directories as required.
1235 <oldpath> The string contained in the symlink.
1236 <newpath> The name of the new symlink.
1237 [RETURNS] 0 on success, else -1.
1240 if (!make_dir_tree(newpath))
1243 if (symlink(oldpath, newpath) != 0) {
1244 if (errno != EEXIST)
1248 } /* End Function mksymlink */
1251 static int make_dir_tree(const char *path)
1252 /* [SUMMARY] Creating intervening directories for a path as required.
1253 <path> The full pathname(including the leaf node).
1254 [RETURNS] TRUE on success, else FALSE.
1257 if (bb_make_directory(dirname((char *)path), -1, FILEUTILS_RECUR) == -1)
1260 } /* End Function make_dir_tree */
1262 static int expand_expression(char *output, unsigned int outsize,
1264 const char *(*get_variable_func)(const char *variable, void *info),
1266 const char *devname,
1267 const regmatch_t *ex, unsigned int numexp)
1268 /* [SUMMARY] Expand environment variables and regular subexpressions in string.
1269 <output> The output expanded expression is written here.
1270 <length> The size of the output buffer.
1271 <input> The input expression. This may equal <<output>>.
1272 <get_variable> A function which will be used to get variable values. If
1273 this returns NULL, the environment is searched instead. If this is NULL,
1274 only the environment is searched.
1275 <info> An arbitrary pointer passed to <<get_variable>>.
1276 <devname> Device name; specifically, this is the string that contains all
1277 of the regular subexpressions.
1278 <ex> Array of start / end offsets into info->devname for each subexpression
1279 <numexp> Number of regular subexpressions found in <<devname>>.
1280 [RETURNS] TRUE on success, else FALSE.
1283 char temp[STRING_LENGTH];
1285 if (!st_expr_expand(temp, STRING_LENGTH, input, get_variable_func, info))
1287 expand_regexp(output, outsize, temp, devname, ex, numexp);
1289 } /* End Function expand_expression */
1291 static void expand_regexp(char *output, size_t outsize, const char *input,
1292 const char *devname,
1293 const regmatch_t *ex, unsigned int numex)
1294 /* [SUMMARY] Expand all occurrences of the regular subexpressions \0 to \9.
1295 <output> The output expanded expression is written here.
1296 <outsize> The size of the output buffer.
1297 <input> The input expression. This may NOT equal <<output>>, because
1298 supporting that would require yet another string-copy. However, it's not
1299 hard to write a simple wrapper function to add this functionality for those
1300 few cases that need it.
1301 <devname> Device name; specifically, this is the string that contains all
1302 of the regular subexpressions.
1303 <ex> An array of start and end offsets into <<devname>>, one for each
1305 <numex> Number of subexpressions in the offset-array <<ex>>.
1309 const char last_exp = '0' - 1 + numex;
1312 /* Guarantee NULL termination by writing an explicit '\0' character into
1313 the very last byte */
1315 output[--outsize] = '\0';
1316 /* Copy the input string into the output buffer, replacing '\\' with '\'
1317 and '\0' .. '\9' with subexpressions 0 .. 9, if they exist. Other \x
1318 codes are deleted */
1319 while ((c != '\0') && (outsize != 0)) {
1326 if ((c >= '0') && (c <= last_exp)) {
1327 const regmatch_t *subexp = ex + (c - '0');
1328 unsigned int sublen = subexp->rm_eo - subexp->rm_so;
1330 /* Range checking */
1331 if (sublen > outsize)
1333 strncpy(output, devname + subexp->rm_so, sublen);
1344 } /* End Function expand_regexp */
1347 /* from compat_name.c */
1349 struct translate_struct
1351 const char *match; /* The string to match to(up to length) */
1352 const char *format; /* Format of output, "%s" takes data past match string,
1353 NULL is effectively "%s"(just more efficient) */
1356 static struct translate_struct translate_table[] =
1359 {"printers/", "lp%s"},
1361 {"parports/", "parport%s"},
1364 {"loop/", "loop%s"},
1365 {"floppy/", "fd%s"},
1367 {"md/", "md%s"}, /* Meta-devices */
1371 {"pg/", "pg%s"}, /* Parallel port generic ATAPI interface*/
1373 {"staliomem/", "staliomem%s"}, /* Stallion serial driver control */
1374 {"tts/E", "ttyE%s"}, /* Stallion serial driver */
1375 {"cua/E", "cue%s"}, /* Stallion serial driver callout */
1376 {"tts/R", "ttyR%s"}, /* Rocketport serial driver */
1377 {"cua/R", "cur%s"}, /* Rocketport serial driver callout */
1378 {"ip2/", "ip2%s"}, /* Computone serial driver control */
1379 {"tts/F", "ttyF%s"}, /* Computone serial driver */
1380 {"cua/F", "cuf%s"}, /* Computone serial driver callout */
1381 {"tts/C", "ttyC%s"}, /* Cyclades serial driver */
1382 {"cua/C", "cub%s"}, /* Cyclades serial driver callout */
1383 {"tts/", "ttyS%s"}, /* Generic serial: must be after others */
1384 {"cua/", "cua%s"}, /* Generic serial: must be after others */
1385 {"input/js", "js%s"}, /* Joystick driver */
1389 const char *get_old_name(const char *devname, unsigned int namelen,
1390 char *buffer, unsigned int major, unsigned int minor)
1391 /* [SUMMARY] Translate a kernel-supplied name into an old name.
1392 <devname> The device name provided by the kernel.
1393 <namelen> The length of the name.
1394 <buffer> A buffer that may be used. This should be at least 128 bytes long.
1395 <major> The major number for the device.
1396 <minor> The minor number for the device.
1397 [RETURNS] A pointer to the old name if known, else NULL.
1400 const char *compat_name = NULL;
1402 struct translate_struct *trans;
1409 /* 1 to 5 "scsi/" , 6 to 9 "ide/host", 10 sbp/, 11 vcc/, 12 pty/ */
1410 static const char *const fmt[] = {
1412 "sg%u", /* scsi/generic */
1413 NULL, /* scsi/disc */
1414 "sr%u", /* scsi/cd */
1415 NULL, /* scsi/part */
1416 "nst%u%c", /* scsi/mt */
1417 "hd%c" , /* ide/host/disc */
1418 "hd%c" , /* ide/host/cd */
1419 "hd%c%s", /* ide/host/part */
1420 "%sht%d", /* ide/host/mt */
1421 "sbpcd%u", /* sbp/ */
1423 "%cty%c%c", /* pty/ */
1427 for (trans = translate_table; trans->match != NULL; ++trans) {
1428 len = strlen(trans->match);
1430 if (strncmp(devname, trans->match, len) == 0) {
1431 if (trans->format == NULL)
1432 return devname + len;
1433 sprintf(buffer, trans->format, devname + len);
1438 ptr = bb_basename(devname);
1439 i = scan_dev_name(devname, namelen, ptr);
1441 if (i > 0 && i < 13)
1442 compat_name = buffer;
1446 /* 1 == scsi/generic, 3 == scsi/cd, 10 == sbp/ */
1447 if (i == 1 || i == 3 || i == 10)
1448 sprintf(buffer, fmt[i], minor);
1450 /* 2 ==scsi/disc, 4 == scsi/part */
1451 if (i == 2 || i == 4)
1452 compat_name = write_old_sd_name(buffer, major, minor,((i == 2) ? "" : (ptr + 4)));
1459 sprintf(buffer, fmt[i], minor & 0x1f, mode);
1460 if (devname[namelen - 1] != 'n')
1463 /* 6 == ide/host/disc, 7 == ide/host/cd, 8 == ide/host/part */
1464 if (i == 6 || i == 7 || i == 8)
1465 /* last arg should be ignored for i == 6 or i== 7 */
1466 sprintf(buffer, fmt[i] , get_old_ide_name(major, minor), ptr + 4);
1468 /* 9 == ide/host/mt */
1470 sprintf(buffer, fmt[i], ptr + 2, minor & 0x7f);
1474 sprintf(buffer, fmt[i], devname + 4);
1475 if (buffer[3] == '0')
1480 pty1 = "pqrstuvwxyzabcde";
1481 pty2 = "0123456789abcdef";
1482 indexx = atoi(devname + 5);
1483 sprintf(buffer, fmt[i], (devname[4] == 'm') ? 'p' : 't', pty1[indexx >> 4], pty2[indexx & 0x0f]);
1486 } /* End Function get_old_name */
1488 static char get_old_ide_name(unsigned int major, unsigned int minor)
1489 /* [SUMMARY] Get the old IDE name for a device.
1490 <major> The major number for the device.
1491 <minor> The minor number for the device.
1492 [RETURNS] The drive letter.
1495 char letter = 'y'; /* 121 */
1496 char c = 'a'; /* 97 */
1499 /* I hope it works like the previous code as it saves a few bytes. Tito ;P */
1501 if (i == IDE0_MAJOR || i == IDE1_MAJOR || i == IDE2_MAJOR
1502 || i == IDE3_MAJOR || i == IDE4_MAJOR || i == IDE5_MAJOR
1503 || i == IDE6_MAJOR || i == IDE7_MAJOR || i == IDE8_MAJOR
1506 if ((unsigned int)i == major) {
1513 } while (i <= IDE9_MAJOR);
1518 } /* End Function get_old_ide_name */
1520 static char *write_old_sd_name(char *buffer,
1521 unsigned int major, unsigned int minor,
1523 /* [SUMMARY] Write the old SCSI disc name to a buffer.
1524 <buffer> The buffer to write to.
1525 <major> The major number for the device.
1526 <minor> The minor number for the device.
1527 <part> The partition string. Must be "" for a whole-disc entry.
1528 [RETURNS] A pointer to the buffer on success, else NULL.
1531 unsigned int disc_index;
1534 sprintf(buffer, "sd%c%s", 'a' + (minor >> 4), part);
1537 if ((major > 64) && (major < 72)) {
1538 disc_index = ((major - 64) << 4) +(minor >> 4);
1539 if (disc_index < 26)
1540 sprintf(buffer, "sd%c%s", 'a' + disc_index, part);
1542 sprintf(buffer, "sd%c%c%s", 'a' +(disc_index / 26) - 1, 'a' + disc_index % 26, part);
1546 } /* End Function write_old_sd_name */
1551 /*EXPERIMENTAL_FUNCTION*/
1553 int st_expr_expand(char *output, unsigned int length, const char *input,
1554 const char *(*get_variable_func)(const char *variable,
1557 /* [SUMMARY] Expand an expression using Borne Shell-like unquoted rules.
1558 <output> The output expanded expression is written here.
1559 <length> The size of the output buffer.
1560 <input> The input expression. This may equal <<output>>.
1561 <get_variable> A function which will be used to get variable values. If
1562 this returns NULL, the environment is searched instead. If this is NULL,
1563 only the environment is searched.
1564 <info> An arbitrary pointer passed to <<get_variable>>.
1565 [RETURNS] TRUE on success, else FALSE.
1570 unsigned int out_pos = 0;
1573 struct passwd *pwent;
1574 char buffer[BUFFER_SIZE], tmp[STRING_LENGTH];
1576 if (length > BUFFER_SIZE)
1577 length = BUFFER_SIZE;
1578 for (; TRUE; ++input) {
1579 switch (ch = *input) {
1581 /* Variable expansion */
1582 input = expand_variable(buffer, length, &out_pos, ++input, get_variable_func, info);
1587 /* Home directory expansion */
1589 if (isspace(ch) ||(ch == '/') ||(ch == '\0')) {
1590 /* User's own home directory: leave separator for next time */
1591 env = getenv("HOME");
1593 info_logger(LOG_INFO, bb_msg_variable_not_found, "HOME");
1597 if (len + out_pos >= length)
1598 goto st_expr_expand_out;
1599 memcpy(buffer + out_pos, env, len + 1);
1603 /* Someone else's home directory */
1604 for (ptr = ++input; !isspace(ch) && (ch != '/') && (ch != '\0'); ch = *++ptr)
1607 if (len >= sizeof tmp)
1608 goto st_expr_expand_out;
1609 safe_memcpy(tmp, input, len);
1611 pwent = getpwnam(tmp);
1612 if (pwent == NULL) {
1613 info_logger(LOG_INFO, "no pwent for: %s", tmp);
1616 len = strlen(pwent->pw_dir);
1617 if (len + out_pos >= length)
1618 goto st_expr_expand_out;
1619 memcpy(buffer + out_pos, pwent->pw_dir, len + 1);
1625 if (out_pos >= length)
1626 goto st_expr_expand_out;
1627 buffer[out_pos++] = ch;
1629 memcpy(output, buffer, out_pos);
1638 info_logger(LOG_INFO, bb_msg_small_buffer);
1640 } /* End Function st_expr_expand */
1643 /* Private functions follow */
1645 static const char *expand_variable(char *buffer, unsigned int length,
1646 unsigned int *out_pos, const char *input,
1647 const char *(*func)(const char *variable,
1650 /* [SUMMARY] Expand a variable.
1651 <buffer> The buffer to write to.
1652 <length> The length of the output buffer.
1653 <out_pos> The current output position. This is updated.
1654 <input> A pointer to the input character pointer.
1655 <func> A function which will be used to get variable values. If this
1656 returns NULL, the environment is searched instead. If this is NULL, only
1657 the environment is searched.
1658 <info> An arbitrary pointer passed to <<func>>.
1659 <errfp> Diagnostic messages are written here.
1660 [RETURNS] A pointer to the end of this subexpression on success, else NULL.
1665 unsigned int open_braces;
1666 const char *env, *ptr;
1667 char tmp[STRING_LENGTH];
1671 /* Special case for "$$": PID */
1672 sprintf(tmp, "%d",(int) getpid());
1674 if (len + *out_pos >= length)
1675 goto expand_variable_out;
1677 memcpy(buffer + *out_pos, tmp, len + 1);
1681 /* Ordinary variable expansion, possibly in braces */
1683 /* Simple variable expansion */
1684 for (ptr = input; isalnum(ch) || (ch == '_') || (ch == ':'); ch = *++ptr)
1687 if ((size_t)len >= sizeof tmp)
1688 goto expand_variable_out;
1690 safe_memcpy(tmp, input, len);
1692 env = get_variable_v2(tmp, func, info);
1694 info_logger(LOG_INFO, bb_msg_variable_not_found, tmp);
1698 if (len + *out_pos >= length)
1699 goto expand_variable_out;
1701 memcpy(buffer + *out_pos, env, len + 1);
1705 /* Variable in braces: check for ':' tricks */
1707 for (ptr = input; isalnum(ch) || (ch == '_'); ch = *++ptr)
1710 /* Must be simple variable expansion with "${var}" */
1712 if ((size_t)len >= sizeof tmp)
1713 goto expand_variable_out;
1715 safe_memcpy(tmp, input, len);
1716 ptr = expand_variable(buffer, length, out_pos, tmp, func, info);
1721 if (ch != ':' || ptr[1] != '-') {
1722 info_logger(LOG_INFO, "illegal char in var name");
1725 /* It's that handy "${var:-word}" expression. Check if var is defined */
1727 if ((size_t)len >= sizeof tmp)
1728 goto expand_variable_out;
1730 safe_memcpy(tmp, input, len);
1731 /* Move input pointer to ':' */
1733 /* First skip to closing brace, taking note of nested expressions */
1736 for (open_braces = 1; open_braces > 0; ch = *++ptr) {
1745 info_logger(LOG_INFO,"\"}\" not found in: %s", input);
1752 /* At this point ptr should point to closing brace of "${var:-word}" */
1753 env = get_variable_v2(tmp, func, info);
1755 /* Found environment variable, so skip the input to the closing brace
1756 and return the variable */
1759 if (len + *out_pos >= length)
1760 goto expand_variable_out;
1762 memcpy(buffer + *out_pos, env, len + 1);
1766 /* Environment variable was not found, so process word. Advance input
1767 pointer to start of word in "${var:-word}" */
1770 if ((size_t)len >= sizeof tmp)
1771 goto expand_variable_out;
1773 safe_memcpy(tmp, input, len);
1775 if (!st_expr_expand(tmp, STRING_LENGTH, tmp, func, info))
1778 if (len + *out_pos >= length)
1779 goto expand_variable_out;
1781 memcpy(buffer + *out_pos, tmp, len + 1);
1784 expand_variable_out:
1785 info_logger(LOG_INFO, bb_msg_small_buffer);
1787 } /* End Function expand_variable */
1790 static const char *get_variable_v2(const char *variable,
1791 const char *(*func)(const char *variable, void *info),
1793 /* [SUMMARY] Get a variable from the environment or .
1794 <variable> The variable name.
1795 <func> A function which will be used to get the variable. If this returns
1796 NULL, the environment is searched instead. If this is NULL, only the
1797 environment is searched.
1798 [RETURNS] The value of the variable on success, else NULL.
1804 value = (*func)(variable, info);
1808 return getenv(variable);
1809 } /* End Function get_variable */