From 8c59a0bf0e9e2d87b0ff273ea3f0bf05bbbf6373 Mon Sep 17 00:00:00 2001 From: nobody Date: Wed, 13 Oct 2004 09:42:10 +0000 Subject: This commit was manufactured by cvs2svn to create tag 'busybox_1_00'. --- busybox/miscutils/Config.in | 201 +++ busybox/miscutils/Makefile | 32 + busybox/miscutils/Makefile.in | 55 + busybox/miscutils/adjtimex.c | 167 +++ busybox/miscutils/crond.c | 1055 +++++++++++++++ busybox/miscutils/crontab.c | 368 ++++++ busybox/miscutils/dc.c | 228 ++++ busybox/miscutils/devfsd.c | 2183 +++++++++++++++++++++++++++++++ busybox/miscutils/hdparm.c | 2872 +++++++++++++++++++++++++++++++++++++++++ busybox/miscutils/last.c | 107 ++ busybox/miscutils/makedevs.c | 93 ++ busybox/miscutils/mt.c | 121 ++ busybox/miscutils/rx.c | 344 +++++ busybox/miscutils/strings.c | 156 +++ busybox/miscutils/time.c | 502 +++++++ busybox/miscutils/watchdog.c | 81 ++ 16 files changed, 8565 insertions(+) create mode 100644 busybox/miscutils/Config.in create mode 100644 busybox/miscutils/Makefile create mode 100644 busybox/miscutils/Makefile.in create mode 100644 busybox/miscutils/adjtimex.c create mode 100644 busybox/miscutils/crond.c create mode 100644 busybox/miscutils/crontab.c create mode 100644 busybox/miscutils/dc.c create mode 100644 busybox/miscutils/devfsd.c create mode 100644 busybox/miscutils/hdparm.c create mode 100644 busybox/miscutils/last.c create mode 100644 busybox/miscutils/makedevs.c create mode 100644 busybox/miscutils/mt.c create mode 100644 busybox/miscutils/rx.c create mode 100644 busybox/miscutils/strings.c create mode 100644 busybox/miscutils/time.c create mode 100644 busybox/miscutils/watchdog.c (limited to 'busybox/miscutils') diff --git a/busybox/miscutils/Config.in b/busybox/miscutils/Config.in new file mode 100644 index 0000000..77e13e8 --- /dev/null +++ b/busybox/miscutils/Config.in @@ -0,0 +1,201 @@ +# +# For a description of the syntax of this configuration file, +# see scripts/kbuild/config-language.txt. +# + +menu "Miscellaneous Utilities" + +config CONFIG_ADJTIMEX + bool "adjtimex" + default n + help + Adjtimex reads and optionally sets adjustment parameters for + the Linux clock adjustment algorithm. + +config CONFIG_CROND + bool "crond" + default n + select CONFIG_FEATURE_SUID + help + Crond is a background daemon that parses individual crontab + files and executes commands on behalf of the users in question. + This is a port of dcron from slackware. It uses files of the + format /var/spool/cron/crontabs/ files, for example: + $ cat /var/spool/cron/crontabs/root + # Run daily cron jobs at 4:40 every day: + 40 4 * * * /etc/cron/daily > /dev/null 2>&1 + Note that Busybox binary must be setuid root for this applet to + work properly. + +config CONFIG_FEATURE_CROND_CALL_SENDMAIL + bool " Using /usr/sbin/sendmail?" + default n + depends on CONFIG_CROND + help + Support calling /usr/sbin/sendmail for send cmd outputs. + +config CONFIG_CRONTAB + bool "crontab" + default n + help + Crontab manipulates the crontab for a particular user. Only + the superuser may specify a different user and/or crontab directory. + +config CONFIG_DC + bool "dc" + default n + help + Dc is a reverse-polish desk calculator which supports unlimited + precision arithmetic. + +config CONFIG_DEVFSD + bool "devfsd" + default n + help + Provides compatibility with old device names on a devfs systems. + You should set it to true if you have devfs enabled. + The following keywords in devsfd.conf are supported: + "CLEAR_CONFIG", "INCLUDE", "OPTIONAL_INCLUDE", "RESTORE", + "PERMISSIONS", "EXECUTE", "COPY", "IGNORE", + "MKOLDCOMPAT", "MKNEWCOMPAT","RMOLDCOMPAT", "RMNEWCOMPAT". + + But only if they are written UPPERCASE!!!!!!!! + +config CONFIG_DEVFSD_MODLOAD + bool "Adds support for MODLOAD keyword in devsfd.conf" + default n + depends on CONFIG_DEVFSD + help + This actually doesn't work with busybox modutils but needs the real modutils. + +config CONFIG_DEVFSD_FG_NP + bool "Enables the -fg and -np options" + default n + depends on CONFIG_DEVFSD + help + -fg Run the daemon in the foreground. + -np Exit after parsing the configuration file. Do not poll for events. + +config CONFIG_DEVFSD_VERBOSE + bool "Increases logging (and size)" + default n + depends on CONFIG_DEVFSD + help + Increases logging to stderr or syslog. + +config CONFIG_LAST + bool "last" + default n + select CONFIG_FEATURE_U_W_TMP + help + 'last' displays a list of the last users that logged into the system. + +config CONFIG_HDPARM + bool "hdparm" + default n + help + Get/Set hard drive parameters. Primarily intended for ATA + drives. Adds about 13k (or around 30k if you enable the + CONFIG_FEATURE_HDPARM_GET_IDENTITY option).... + +config CONFIG_FEATURE_HDPARM_GET_IDENTITY + bool " Support obtaining detailed information directly from drives" + default y + depends on CONFIG_HDPARM + help + Enables the -I and -Istdin options to obtain detailed information + directly from drives about their capabilities and supported ATA + feature set. Enabling this option will add about 16k... + +config CONFIG_FEATURE_HDPARM_HDIO_SCAN_HWIF + bool " Register an IDE interface (DANGEROUS)" + default n + depends on CONFIG_HDPARM + help + Enables the 'hdparm -R' option to register an IDE interface. + This is dangerous stuff, so you should probably say N. + +config CONFIG_FEATURE_HDPARM_HDIO_UNREGISTER_HWIF + bool " Un-register an IDE interface (DANGEROUS)" + default n + depends on CONFIG_HDPARM + help + Enables the 'hdparm -U' option to un-register an IDE interface. + This is dangerous stuff, so you should probably say N. + +config CONFIG_FEATURE_HDPARM_HDIO_DRIVE_RESET + bool " perform device reset (DANGEROUS)" + default n + depends on CONFIG_HDPARM + help + Enables the 'hdparm -w' option to perform a device reset. + This is dangerous stuff, so you should probably say N. + +config CONFIG_FEATURE_HDPARM_HDIO_TRISTATE_HWIF + bool " tristate device for hotswap (DANGEROUS)" + default n + depends on CONFIG_HDPARM + help + Enables the 'hdparm -x' option to tristate device for hotswap, + and the '-b' option to get/set bus state. This is dangerous + stuff, so you should probably say N. + +config CONFIG_FEATURE_HDPARM_HDIO_GETSET_DMA + bool " get/set using_dma flag (DANGEROUS)" + default n + depends on CONFIG_HDPARM + help + Enables the 'hdparm -d' option to get/set using_dma flag. + This is dangerous stuff, so you should probably say N. + +config CONFIG_MAKEDEVS + bool "makedevs" + default n + help + 'makedevs' is a utility used and created by the Linux Router Project. + It creates a large number of device special files (/dev devices) + rather quickly, and can be considerably faster then running mknod a + zillion times. + +config CONFIG_MT + bool "mt" + default n + help + mt is used to control tape devices. You can use the mt utility + to advance or rewind a tape past a specified number of archive + files on the tape. + +config CONFIG_RX + bool "rx" + default n + help + Receive files using the Xmodem protocol. + +config CONFIG_STRINGS + bool "strings" + default n + help + strings prints the printable character sequences for each file + specified. + +config CONFIG_TIME + bool "time" + default n + help + The time command runs the specified program with the given arguments. + When the command finishes, time writes a message to standard output + giving timing statistics about this program run. + +config CONFIG_WATCHDOG + bool "watchdog" + default n + help + The watchdog utility is used with hardware or software watchdog + device drivers. It opens the specified watchdog device special file + and periodically writes a magic character to the device. If the + watchdog applet ever fails to write the magic character within a + certain amount of time, the watchdog device assumes the system has + hung, and will cause the hardware to reboot. + +endmenu + diff --git a/busybox/miscutils/Makefile b/busybox/miscutils/Makefile new file mode 100644 index 0000000..ac427dc --- /dev/null +++ b/busybox/miscutils/Makefile @@ -0,0 +1,32 @@ +# Makefile for busybox +# +# Copyright (C) 1999-2004 by Erik Andersen +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +# + +top_srcdir=.. +top_builddir=.. +srcdir=$(top_srcdir)/miscutils +MISCUTILS_DIR:=./ +include $(top_builddir)/Rules.mak +include $(top_builddir)/.config +include Makefile.in +all: $(libraries-y) +-include $(top_builddir)/.depend + +clean: + rm -f *.o *.a $(AR_TARGET) + diff --git a/busybox/miscutils/Makefile.in b/busybox/miscutils/Makefile.in new file mode 100644 index 0000000..ddddf72 --- /dev/null +++ b/busybox/miscutils/Makefile.in @@ -0,0 +1,55 @@ +# Makefile for busybox +# +# Copyright (C) 1999-2004 by Erik Andersen +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +# + +MISCUTILS_AR:=miscutils.a +ifndef $(MISCUTILS_DIR) +MISCUTILS_DIR:=$(top_builddir)/miscutils/ +endif +srcdir=$(top_srcdir)/miscutils + +MISCUTILS-y:= +MISCUTILS-$(CONFIG_ADJTIMEX) += adjtimex.o +MISCUTILS-$(CONFIG_CROND) += crond.o +MISCUTILS-$(CONFIG_CRONTAB) += crontab.o +MISCUTILS-$(CONFIG_DC) += dc.o +MISCUTILS-$(CONFIG_DEVFSD) += devfsd.o +MISCUTILS-$(CONFIG_HDPARM) += hdparm.o +MISCUTILS-$(CONFIG_LAST) += last.o +MISCUTILS-$(CONFIG_MAKEDEVS) += makedevs.o +MISCUTILS-$(CONFIG_MT) += mt.o +MISCUTILS-$(CONFIG_RX) += rx.o +MISCUTILS-$(CONFIG_STRINGS) += strings.o +MISCUTILS-$(CONFIG_TIME) += time.o +MISCUTILS-$(CONFIG_WATCHDOG) += watchdog.o + +libraries-y+=$(MISCUTILS_DIR)$(MISCUTILS_AR) + +needlibm-y:= +needlibm-$(CONFIG_DC) := y + +ifeq ($(needlibm-y),y) + LIBRARIES += -lm +endif + +$(MISCUTILS_DIR)$(MISCUTILS_AR): $(patsubst %,$(MISCUTILS_DIR)%, $(MISCUTILS-y)) + $(AR) -ro $@ $(patsubst %,$(MISCUTILS_DIR)%, $(MISCUTILS-y)) + +$(MISCUTILS_DIR)%.o: $(srcdir)/%.c + $(CC) $(CFLAGS) $(EXTRA_CFLAGS) -c -o $@ $< + diff --git a/busybox/miscutils/adjtimex.c b/busybox/miscutils/adjtimex.c new file mode 100644 index 0000000..110c026 --- /dev/null +++ b/busybox/miscutils/adjtimex.c @@ -0,0 +1,167 @@ +/* + * adjtimex.c - read, and possibly modify, the Linux kernel `timex' variables. + * + * Originally written: October 1997 + * Last hack: March 2001 + * Copyright 1997, 2000, 2001 Larry Doolittle + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License (Version 2, + * June 1991) as published by the Free Software Foundation. At the + * time of writing, that license was published by the FSF with the URL + * http://www.gnu.org/copyleft/gpl.html, and is incorporated herein by + * reference. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * This adjtimex(1) is very similar in intent to adjtimex(8) by Steven + * Dick and Jim Van Zandt + * (see http://metalab.unc.edu/pub/Linux/system/admin/time/adjtimex*). + * That version predates this one, and is _much_ bigger and more + * featureful. My independently written version was very similar to + * Steven's from the start, because they both follow the kernel timex + * structure. I further tweaked this version to be equivalent to Steven's + * where possible, but I don't like getopt_long, so the actual usage + * syntax is incompatible. + * + * Amazingly enough, my Red Hat 5.2 sys/timex (and sub-includes) + * don't actually give a prototype for adjtimex(2), so building + * this code (with -Wall) gives a warning. Later versions of + * glibc fix this issue. + * + * This program is too simple for a Makefile, just build with: + * gcc -Wall -O adjtimex.c -o adjtimex + * + * busyboxed 20 March 2001, Larry Doolittle + * It will autosense if it is built in a busybox environment, based + * on the BB_VER preprocessor macro. + */ + +#include +#include +#include +#include +#include +#include "busybox.h" + +static struct {int bit; char *name;} statlist[] = { + { STA_PLL, "PLL" }, + { STA_PPSFREQ, "PPSFREQ" }, + { STA_PPSTIME, "PPSTIME" }, + { STA_FLL, "FFL" }, + { STA_INS, "INS" }, + { STA_DEL, "DEL" }, + { STA_UNSYNC, "UNSYNC" }, + { STA_FREQHOLD, "FREQHOLD" }, + { STA_PPSSIGNAL, "PPSSIGNAL" }, + { STA_PPSJITTER, "PPSJITTER" }, + { STA_PPSWANDER, "PPSWANDER" }, + { STA_PPSERROR, "PPSERROR" }, + { STA_CLOCKERR, "CLOCKERR" }, + { 0, NULL } }; + +static char *ret_code_descript[] = { + "clock synchronized", + "insert leap second", + "delete leap second", + "leap second in progress", + "leap second has occurred", + "clock not synchronized" }; + +#ifdef BB_VER +#define main adjtimex_main +#else +void usage(char *prog) +{ + fprintf(stderr, + "Usage: %s [ -q ] [ -o offset ] [ -f frequency ] [ -p timeconstant ] [ -t tick ]\n", + prog); +} +#define bb_show_usage() usage(argv[0]) +#endif + +int main(int argc, char ** argv) +{ + struct timex txc; + int quiet=0; + int c, i, ret, sep; + char *descript; + txc.modes=0; + for (;;) { + c = getopt( argc, argv, "qo:f:p:t:"); + if (c == EOF) break; + switch (c) { + case 'q': + quiet=1; + break; + case 'o': + txc.offset = atoi(optarg); + txc.modes |= ADJ_OFFSET_SINGLESHOT; + break; + case 'f': + txc.freq = atoi(optarg); + txc.modes |= ADJ_FREQUENCY; + break; + case 'p': + txc.constant = atoi(optarg); + txc.modes |= ADJ_TIMECONST; + break; + case 't': + txc.tick = atoi(optarg); + txc.modes |= ADJ_TICK; + break; + default: + bb_show_usage(); + exit(1); + } + } + if (argc != optind) { /* no valid non-option parameters */ + bb_show_usage(); + exit(1); + } + + ret = adjtimex(&txc); + + if (ret < 0) perror("adjtimex"); + + if (!quiet && ret>=0) { + printf( + " mode: %d\n" + "-o offset: %ld\n" + "-f frequency: %ld\n" + " maxerror: %ld\n" + " esterror: %ld\n" + " status: %d ( ", + txc.modes, txc.offset, txc.freq, txc.maxerror, + txc.esterror, txc.status); + + /* representative output of next code fragment: + "PLL | PPSTIME" */ + sep=0; + for (i=0; statlist[i].name; i++) { + if (txc.status & statlist[i].bit) { + if (sep) fputs(" | ",stdout); + fputs(statlist[i].name,stdout); + sep=1; + } + } + + descript = "error"; + if (ret >= 0 && ret <= 5) descript = ret_code_descript[ret]; + printf(" )\n" + "-p timeconstant: %ld\n" + " precision: %ld\n" + " tolerance: %ld\n" + "-t tick: %ld\n" + " time.tv_sec: %ld\n" + " time.tv_usec: %ld\n" + " return value: %d (%s)\n", + txc.constant, + txc.precision, txc.tolerance, txc.tick, + (long)txc.time.tv_sec, (long)txc.time.tv_usec, ret, descript); + } + return (ret<0); +} diff --git a/busybox/miscutils/crond.c b/busybox/miscutils/crond.c new file mode 100644 index 0000000..085cf6e --- /dev/null +++ b/busybox/miscutils/crond.c @@ -0,0 +1,1055 @@ +/* + * crond -d[#] -c -f -b + * + * run as root, but NOT setuid root + * + * Copyright 1994 Matthew Dillon (dillon@apollo.west.oic.com) + * May be distributed under the GNU General Public License + * + * Vladimir Oleynik (C) 2002 to be used in busybox + */ + +#define VERSION "2.3.2" + +#undef FEATURE_DEBUG_OPT + + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "busybox.h" + +#define arysize(ary) (sizeof(ary)/sizeof((ary)[0])) + +#ifndef CRONTABS +#define CRONTABS "/var/spool/cron/crontabs" +#endif +#ifndef TMPDIR +#define TMPDIR "/var/spool/cron" +#endif +#ifndef SENDMAIL +#define SENDMAIL "/usr/sbin/sendmail" +#endif +#ifndef SENDMAIL_ARGS +#define SENDMAIL_ARGS "-ti", "oem" +#endif +#ifndef CRONUPDATE +#define CRONUPDATE "cron.update" +#endif +#ifndef MAXLINES +#define MAXLINES 256 /* max lines in non-root crontabs */ +#endif + +typedef struct CronFile { + struct CronFile *cf_Next; + struct CronLine *cf_LineBase; + char *cf_User; /* username */ + int cf_Ready; /* bool: one or more jobs ready */ + int cf_Running; /* bool: one or more jobs running */ + int cf_Deleted; /* marked for deletion, ignore */ +} CronFile; + +typedef struct CronLine { + struct CronLine *cl_Next; + char *cl_Shell; /* shell command */ + pid_t cl_Pid; /* running pid, 0, or armed (-1) */ + int cl_MailFlag; /* running pid is for mail */ + int cl_MailPos; /* 'empty file' size */ + char cl_Mins[60]; /* 0-59 */ + char cl_Hrs[24]; /* 0-23 */ + char cl_Days[32]; /* 1-31 */ + char cl_Mons[12]; /* 0-11 */ + char cl_Dow[7]; /* 0-6, beginning sunday */ +} CronLine; + +#define RUN_RANOUT 1 +#define RUN_RUNNING 2 +#define RUN_FAILED 3 + +#define DaemonUid 0 + +#ifdef FEATURE_DEBUG_OPT +static short DebugOpt; +#endif + +static short LogLevel = 8; +static const char *LogFile; +static const char *CDir = CRONTABS; + +static void startlogger(void); + +static void CheckUpdates(void); +static void SynchronizeDir(void); +static int TestJobs(time_t t1, time_t t2); +static void RunJobs(void); +static int CheckJobs(void); + +static void RunJob(const char *user, CronLine * line); + +#ifdef CONFIG_FEATURE_CROND_CALL_SENDMAIL +static void EndJob(const char *user, CronLine * line); +#else +#define EndJob(user, line) line->cl_Pid = 0 +#endif + +static void DeleteFile(const char *userName); + +static CronFile *FileBase; + + +static void crondlog(const char *ctl, ...) +{ + va_list va; + const char *fmt; + int level = (int) (ctl[0] & 0xf); + int type = level == 20 ? + LOG_ERR : ((ctl[0] & 0100) ? LOG_WARNING : LOG_NOTICE); + + + va_start(va, ctl); + fmt = ctl + 1; + if (level >= LogLevel) { + +#ifdef FEATURE_DEBUG_OPT + if (DebugOpt) { + vfprintf(stderr, fmt, va); + } else +#endif + if (LogFile == 0) { + vsyslog(type, fmt, va); + } else { + int logfd = open(LogFile, O_WRONLY | O_CREAT | O_APPEND, 600); + if (logfd >= 0) { + vdprintf(logfd, fmt, va); + close(logfd); +#ifdef FEATURE_DEBUG_OPT + } else { + bb_perror_msg("Can't open log file"); +#endif + } + } + } + va_end(va); + if (ctl[0] & 0200) { + exit(20); + } +} + +int crond_main(int ac, char **av) +{ + unsigned long opt; + char *lopt, *Lopt, *copt; + +#ifdef FEATURE_DEBUG_OPT + char *dopt; + + bb_opt_complementaly = "f-b:b-f:S-L:L-S:d-l"; +#else + bb_opt_complementaly = "f-b:b-f:S-L:L-S"; +#endif + + opterr = 0; /* disable getopt 'errors' message. */ + opt = bb_getopt_ulflags(ac, av, "l:L:fbSc:" +#ifdef FEATURE_DEBUG_OPT + "d:" +#endif + , &lopt, &Lopt, &copt +#ifdef FEATURE_DEBUG_OPT + , &dopt +#endif + ); + if (opt & 1) { + LogLevel = atoi(lopt); + } + if (opt & 2) { + if (*Lopt != 0) { + LogFile = Lopt; + } + } + if (opt & 32) { + if (*copt != 0) { + CDir = copt; + } + } +#ifdef FEATURE_DEBUG_OPT + if (opt & 64) { + DebugOpt = atoi(dopt); + LogLevel = 0; + } +#endif + + /* + * change directory + */ + + if (chdir(CDir) != 0) { + bb_perror_msg_and_die("%s", CDir); + } + signal(SIGHUP, SIG_IGN); /* hmm.. but, if kill -HUP original + * version - his died. ;( + */ + /* + * close stdin and stdout, stderr. + * close unused descriptors - don't need. + * optional detach from controlling terminal + */ + + if (!(opt & 4)) { +#if defined(__uClinux__) + /* reexec for vfork() do continue parent */ + vfork_daemon_rexec(1, 0, ac, av, "-f"); +#else /* uClinux */ + if (daemon(1, 0) < 0) { + bb_perror_msg_and_die("daemon"); + } +#endif /* uClinux */ + } + + (void) startlogger(); /* need if syslog mode selected */ + + /* + * main loop - synchronize to 1 second after the minute, minimum sleep + * of 1 second. + */ + + crondlog("\011%s " VERSION " dillon, started, log level %d\n", + bb_applet_name, LogLevel); + + SynchronizeDir(); + + { + time_t t1 = time(NULL); + time_t t2; + long dt; + short rescan = 60; + short sleep_time = 60; + + for (;;) { + sleep((sleep_time + 1) - (short) (time(NULL) % sleep_time)); + + t2 = time(NULL); + dt = t2 - t1; + + /* + * The file 'cron.update' is checked to determine new cron + * jobs. The directory is rescanned once an hour to deal + * with any screwups. + * + * check for disparity. Disparities over an hour either way + * result in resynchronization. A reverse-indexed disparity + * less then an hour causes us to effectively sleep until we + * match the original time (i.e. no re-execution of jobs that + * have just been run). A forward-indexed disparity less then + * an hour causes intermediate jobs to be run, but only once + * in the worst case. + * + * when running jobs, the inequality used is greater but not + * equal to t1, and less then or equal to t2. + */ + + if (--rescan == 0) { + rescan = 60; + SynchronizeDir(); + } + CheckUpdates(); +#ifdef FEATURE_DEBUG_OPT + if (DebugOpt) + crondlog("\005Wakeup dt=%d\n", dt); +#endif + if (dt < -60 * 60 || dt > 60 * 60) { + t1 = t2; + crondlog("\111time disparity of %d minutes detected\n", dt / 60); + } else if (dt > 0) { + TestJobs(t1, t2); + RunJobs(); + sleep(5); + if (CheckJobs() > 0) { + sleep_time = 10; + } else { + sleep_time = 60; + } + t1 = t2; + } + } + } + /* not reached */ +} + +#if defined(FEATURE_DEBUG_OPT) || defined(CONFIG_FEATURE_CROND_CALL_SENDMAIL) +/* + write to temp file.. +*/ +static void fdprintf(int fd, const char *ctl, ...) +{ + va_list va; + + va_start(va, ctl); + vdprintf(fd, ctl, va); + va_end(va); +} +#endif + + +static int ChangeUser(const char *user) +{ + struct passwd *pas; + const char *err_msg; + + /* + * Obtain password entry and change privileges + */ + pas = getpwnam(user); + if (pas == 0) { + crondlog("\011failed to get uid for %s", user); + return (-1); + } + setenv("USER", pas->pw_name, 1); + setenv("HOME", pas->pw_dir, 1); + setenv("SHELL", DEFAULT_SHELL, 1); + + /* + * Change running state to the user in question + */ + err_msg = change_identity_e2str(pas); + if (err_msg) { + crondlog("\011%s for user %s", err_msg, user); + return (-1); + } + if (chdir(pas->pw_dir) < 0) { + crondlog("\011chdir failed: %s: %m", pas->pw_dir); + if (chdir(TMPDIR) < 0) { + crondlog("\011chdir failed: %s: %m", TMPDIR); + return (-1); + } + } + return (pas->pw_uid); +} + +static void startlogger(void) +{ + if (LogFile == 0) { + openlog(bb_applet_name, LOG_CONS | LOG_PID, LOG_CRON); + } +#ifdef FEATURE_DEBUG_OPT + else { /* test logfile */ + int logfd; + + if ((logfd = open(LogFile, O_WRONLY | O_CREAT | O_APPEND, 600)) >= 0) { + close(logfd); + } else { + bb_perror_msg("Failed to open log file '%s' reason", LogFile); + } + } +#endif +} + + +static const char *const DowAry[] = { + "sun", + "mon", + "tue", + "wed", + "thu", + "fri", + "sat", + + "Sun", + "Mon", + "Tue", + "Wed", + "Thu", + "Fri", + "Sat", + NULL +}; + +static const char *const MonAry[] = { + "jan", + "feb", + "mar", + "apr", + "may", + "jun", + "jul", + "aug", + "sep", + "oct", + "nov", + "dec", + + "Jan", + "Feb", + "Mar", + "Apr", + "May", + "Jun", + "Jul", + "Aug", + "Sep", + "Oct", + "Nov", + "Dec", + NULL +}; + +static char *ParseField(char *user, char *ary, int modvalue, int off, + const char *const *names, char *ptr) +{ + char *base = ptr; + int n1 = -1; + int n2 = -1; + + if (base == NULL) { + return (NULL); + } + + while (*ptr != ' ' && *ptr != '\t' && *ptr != '\n') { + int skip = 0; + + /* Handle numeric digit or symbol or '*' */ + + if (*ptr == '*') { + n1 = 0; /* everything will be filled */ + n2 = modvalue - 1; + skip = 1; + ++ptr; + } else if (*ptr >= '0' && *ptr <= '9') { + if (n1 < 0) { + n1 = strtol(ptr, &ptr, 10) + off; + } else { + n2 = strtol(ptr, &ptr, 10) + off; + } + skip = 1; + } else if (names) { + int i; + + for (i = 0; names[i]; ++i) { + if (strncmp(ptr, names[i], strlen(names[i])) == 0) { + break; + } + } + if (names[i]) { + ptr += strlen(names[i]); + if (n1 < 0) { + n1 = i; + } else { + n2 = i; + } + skip = 1; + } + } + + /* handle optional range '-' */ + + if (skip == 0) { + crondlog("\111failed user %s parsing %s\n", user, base); + return (NULL); + } + if (*ptr == '-' && n2 < 0) { + ++ptr; + continue; + } + + /* + * collapse single-value ranges, handle skipmark, and fill + * in the character array appropriately. + */ + + if (n2 < 0) { + n2 = n1; + } + if (*ptr == '/') { + skip = strtol(ptr + 1, &ptr, 10); + } + /* + * fill array, using a failsafe is the easiest way to prevent + * an endless loop + */ + + { + int s0 = 1; + int failsafe = 1024; + + --n1; + do { + n1 = (n1 + 1) % modvalue; + + if (--s0 == 0) { + ary[n1 % modvalue] = 1; + s0 = skip; + } + } + while (n1 != n2 && --failsafe); + + if (failsafe == 0) { + crondlog("\111failed user %s parsing %s\n", user, base); + return (NULL); + } + } + if (*ptr != ',') { + break; + } + ++ptr; + n1 = -1; + n2 = -1; + } + + if (*ptr != ' ' && *ptr != '\t' && *ptr != '\n') { + crondlog("\111failed user %s parsing %s\n", user, base); + return (NULL); + } + + while (*ptr == ' ' || *ptr == '\t' || *ptr == '\n') { + ++ptr; + } +#ifdef FEATURE_DEBUG_OPT + if (DebugOpt) { + int i; + + for (i = 0; i < modvalue; ++i) { + crondlog("\005%d", ary[i]); + } + crondlog("\005\n"); + } +#endif + + return (ptr); +} + +static void FixDayDow(CronLine * line) +{ + short i; + short weekUsed = 0; + short daysUsed = 0; + + for (i = 0; i < arysize(line->cl_Dow); ++i) { + if (line->cl_Dow[i] == 0) { + weekUsed = 1; + break; + } + } + for (i = 0; i < arysize(line->cl_Days); ++i) { + if (line->cl_Days[i] == 0) { + daysUsed = 1; + break; + } + } + if (weekUsed && !daysUsed) { + memset(line->cl_Days, 0, sizeof(line->cl_Days)); + } + if (daysUsed && !weekUsed) { + memset(line->cl_Dow, 0, sizeof(line->cl_Dow)); + } +} + + + +static void SynchronizeFile(const char *fileName) +{ + int maxEntries = MAXLINES; + int maxLines; + char buf[1024]; + + if (strcmp(fileName, "root") == 0) { + maxEntries = 65535; + } + maxLines = maxEntries * 10; + + if (fileName) { + FILE *fi; + + DeleteFile(fileName); + + fi = fopen(fileName, "r"); + if (fi != NULL) { + struct stat sbuf; + + if (fstat(fileno(fi), &sbuf) == 0 && sbuf.st_uid == DaemonUid) { + CronFile *file = calloc(1, sizeof(CronFile)); + CronLine **pline; + + file->cf_User = strdup(fileName); + pline = &file->cf_LineBase; + + while (fgets(buf, sizeof(buf), fi) != NULL && --maxLines) { + CronLine line; + char *ptr; + + if (buf[0]) { + buf[strlen(buf) - 1] = 0; + } + if (buf[0] == 0 || buf[0] == '#' || buf[0] == ' ' || buf[0] == '\t') { + continue; + } + if (--maxEntries == 0) { + break; + } + memset(&line, 0, sizeof(line)); + +#ifdef FEATURE_DEBUG_OPT + if (DebugOpt) { + crondlog("\111User %s Entry %s\n", fileName, buf); + } +#endif + + /* parse date ranges */ + ptr = ParseField(file->cf_User, line.cl_Mins, 60, 0, NULL, buf); + ptr = ParseField(file->cf_User, line.cl_Hrs, 24, 0, NULL, ptr); + ptr = ParseField(file->cf_User, line.cl_Days, 32, 0, NULL, ptr); + ptr = ParseField(file->cf_User, line.cl_Mons, 12, -1, MonAry, ptr); + ptr = ParseField(file->cf_User, line.cl_Dow, 7, 0, DowAry, ptr); + + /* check failure */ + if (ptr == NULL) { + continue; + } + + /* + * fix days and dow - if one is not * and the other + * is *, the other is set to 0, and vise-versa + */ + + FixDayDow(&line); + + *pline = calloc(1, sizeof(CronLine)); + **pline = line; + + /* copy command */ + (*pline)->cl_Shell = strdup(ptr); + +#ifdef FEATURE_DEBUG_OPT + if (DebugOpt) { + crondlog("\111 Command %s\n", ptr); + } +#endif + + pline = &((*pline)->cl_Next); + } + *pline = NULL; + + file->cf_Next = FileBase; + FileBase = file; + + if (maxLines == 0 || maxEntries == 0) { + crondlog("\111Maximum number of lines reached for user %s\n", fileName); + } + } + fclose(fi); + } + } +} + +static void CheckUpdates(void) +{ + FILE *fi; + char buf[256]; + + fi = fopen(CRONUPDATE, "r"); + if (fi != NULL) { + remove(CRONUPDATE); + while (fgets(buf, sizeof(buf), fi) != NULL) { + SynchronizeFile(strtok(buf, " \t\r\n")); + } + fclose(fi); + } +} + +static void SynchronizeDir(void) +{ + /* Attempt to delete the database. */ + + for (;;) { + CronFile *file; + + for (file = FileBase; file && file->cf_Deleted; file = file->cf_Next); + if (file == NULL) { + break; + } + DeleteFile(file->cf_User); + } + + /* + * Remove cron update file + * + * Re-chdir, in case directory was renamed & deleted, or otherwise + * screwed up. + * + * scan directory and add associated users + */ + + remove(CRONUPDATE); + if (chdir(CDir) < 0) { + crondlog("\311unable to find %s\n", CDir); + } + { + DIR *dir = opendir("."); + struct dirent *den; + + if (dir) { + while ((den = readdir(dir))) { + if (strchr(den->d_name, '.') != NULL) { + continue; + } + if (getpwnam(den->d_name)) { + SynchronizeFile(den->d_name); + } else { + crondlog("\007ignoring %s\n", den->d_name); + } + } + closedir(dir); + } else { + crondlog("\311Unable to open current dir!\n"); + } + } +} + + +/* + * DeleteFile() - delete user database + * + * Note: multiple entries for same user may exist if we were unable to + * completely delete a database due to running processes. + */ + +static void DeleteFile(const char *userName) +{ + CronFile **pfile = &FileBase; + CronFile *file; + + while ((file = *pfile) != NULL) { + if (strcmp(userName, file->cf_User) == 0) { + CronLine **pline = &file->cf_LineBase; + CronLine *line; + + file->cf_Running = 0; + file->cf_Deleted = 1; + + while ((line = *pline) != NULL) { + if (line->cl_Pid > 0) { + file->cf_Running = 1; + pline = &line->cl_Next; + } else { + *pline = line->cl_Next; + free(line->cl_Shell); + free(line); + } + } + if (file->cf_Running == 0) { + *pfile = file->cf_Next; + free(file->cf_User); + free(file); + } else { + pfile = &file->cf_Next; + } + } else { + pfile = &file->cf_Next; + } + } +} + +/* + * TestJobs() + * + * determine which jobs need to be run. Under normal conditions, the + * period is about a minute (one scan). Worst case it will be one + * hour (60 scans). + */ + +static int TestJobs(time_t t1, time_t t2) +{ + short nJobs = 0; + time_t t; + + /* Find jobs > t1 and <= t2 */ + + for (t = t1 - t1 % 60; t <= t2; t += 60) { + if (t > t1) { + struct tm *tp = localtime(&t); + CronFile *file; + CronLine *line; + + for (file = FileBase; file; file = file->cf_Next) { +#ifdef FEATURE_DEBUG_OPT + if (DebugOpt) + crondlog("\005FILE %s:\n", file->cf_User); +#endif + if (file->cf_Deleted) + continue; + for (line = file->cf_LineBase; line; line = line->cl_Next) { +#ifdef FEATURE_DEBUG_OPT + if (DebugOpt) + crondlog("\005 LINE %s\n", line->cl_Shell); +#endif + if (line->cl_Mins[tp->tm_min] && line->cl_Hrs[tp->tm_hour] && + (line->cl_Days[tp->tm_mday] || line->cl_Dow[tp->tm_wday]) + && line->cl_Mons[tp->tm_mon]) { +#ifdef FEATURE_DEBUG_OPT + if (DebugOpt) { + crondlog("\005 JobToDo: %d %s\n", + line->cl_Pid, line->cl_Shell); + } +#endif + if (line->cl_Pid > 0) { + crondlog("\010 process already running: %s %s\n", + file->cf_User, line->cl_Shell); + } else if (line->cl_Pid == 0) { + line->cl_Pid = -1; + file->cf_Ready = 1; + ++nJobs; + } + } + } + } + } + } + return (nJobs); +} + +static void RunJobs(void) +{ + CronFile *file; + CronLine *line; + + for (file = FileBase; file; file = file->cf_Next) { + if (file->cf_Ready) { + file->cf_Ready = 0; + + for (line = file->cf_LineBase; line; line = line->cl_Next) { + if (line->cl_Pid < 0) { + + RunJob(file->cf_User, line); + + crondlog("\010USER %s pid %3d cmd %s\n", + file->cf_User, line->cl_Pid, line->cl_Shell); + if (line->cl_Pid < 0) { + file->cf_Ready = 1; + } + else if (line->cl_Pid > 0) { + file->cf_Running = 1; + } + } + } + } + } +} + +/* + * CheckJobs() - check for job completion + * + * Check for job completion, return number of jobs still running after + * all done. + */ + +static int CheckJobs(void) +{ + CronFile *file; + CronLine *line; + int nStillRunning = 0; + + for (file = FileBase; file; file = file->cf_Next) { + if (file->cf_Running) { + file->cf_Running = 0; + + for (line = file->cf_LineBase; line; line = line->cl_Next) { + if (line->cl_Pid > 0) { + int status; + int r = wait4(line->cl_Pid, &status, WNOHANG, NULL); + + if (r < 0 || r == line->cl_Pid) { + EndJob(file->cf_User, line); + if (line->cl_Pid) { + file->cf_Running = 1; + } + } else if (r == 0) { + file->cf_Running = 1; + } + } + } + } + nStillRunning += file->cf_Running; + } + return (nStillRunning); +} + + +#ifdef CONFIG_FEATURE_CROND_CALL_SENDMAIL +static void +ForkJob(const char *user, CronLine * line, int mailFd, + const char *prog, const char *cmd, const char *arg, const char *mailf) +{ + /* Fork as the user in question and run program */ + pid_t pid = fork(); + + line->cl_Pid = pid; + if (pid == 0) { + /* CHILD */ + + /* Change running state to the user in question */ + + if (ChangeUser(user) < 0) { + exit(0); + } +#ifdef FEATURE_DEBUG_OPT + if (DebugOpt) { + crondlog("\005Child Running %s\n", prog); + } +#endif + + if (mailFd >= 0) { + dup2(mailFd, mailf != NULL); + dup2((mailf ? mailFd : 1), 2); + close(mailFd); + } + execl(prog, prog, cmd, arg, NULL); + crondlog("\024unable to exec, user %s cmd %s %s %s\n", user, prog, cmd, arg); + if (mailf) { + fdprintf(1, "Exec failed: %s -c %s\n", prog, arg); + } + exit(0); + } else if (pid < 0) { + /* FORK FAILED */ + crondlog("\024couldn't fork, user %s\n", user); + line->cl_Pid = 0; + if (mailf) { + remove(mailf); + } + } else if (mailf) { + /* PARENT, FORK SUCCESS + * rename mail-file based on pid of process + */ + char mailFile2[128]; + + snprintf(mailFile2, sizeof(mailFile2), TMPDIR "/cron.%s.%d", user, pid); + rename(mailf, mailFile2); + } + /* + * Close the mail file descriptor.. we can't just leave it open in + * a structure, closing it later, because we might run out of descriptors + */ + + if (mailFd >= 0) { + close(mailFd); + } +} + +static void RunJob(const char *user, CronLine * line) +{ + char mailFile[128]; + int mailFd; + + line->cl_Pid = 0; + line->cl_MailFlag = 0; + + /* open mail file - owner root so nobody can screw with it. */ + + snprintf(mailFile, sizeof(mailFile), TMPDIR "/cron.%s.%d", user, getpid()); + mailFd = open(mailFile, O_CREAT | O_TRUNC | O_WRONLY | O_EXCL | O_APPEND, 0600); + + if (mailFd >= 0) { + line->cl_MailFlag = 1; + fdprintf(mailFd, "To: %s\nSubject: cron: %s\n\n", user, + line->cl_Shell); + line->cl_MailPos = lseek(mailFd, 0, 1); + } else { + crondlog("\024unable to create mail file user %s file %s, output to /dev/null\n", user, mailFile); + } + + ForkJob(user, line, mailFd, DEFAULT_SHELL, "-c", line->cl_Shell, mailFile); +} + +/* + * EndJob - called when job terminates and when mail terminates + */ + +static void EndJob(const char *user, CronLine * line) +{ + int mailFd; + char mailFile[128]; + struct stat sbuf; + + /* No job */ + + if (line->cl_Pid <= 0) { + line->cl_Pid = 0; + return; + } + + /* + * End of job and no mail file + * End of sendmail job + */ + + snprintf(mailFile, sizeof(mailFile), TMPDIR "/cron.%s.%d", user, line->cl_Pid); + line->cl_Pid = 0; + + if (line->cl_MailFlag != 1) { + return; + } + line->cl_MailFlag = 0; + + /* + * End of primary job - check for mail file. If size has increased and + * the file is still valid, we sendmail it. + */ + + mailFd = open(mailFile, O_RDONLY); + remove(mailFile); + if (mailFd < 0) { + return; + } + + if (fstat(mailFd, &sbuf) < 0 || sbuf.st_uid != DaemonUid || sbuf.st_nlink != 0 || + sbuf.st_size == line->cl_MailPos || !S_ISREG(sbuf.st_mode)) { + close(mailFd); + return; + } + ForkJob(user, line, mailFd, SENDMAIL, SENDMAIL_ARGS, NULL); +} +#else +/* crond without sendmail */ + +static void RunJob(const char *user, CronLine * line) +{ + /* Fork as the user in question and run program */ + pid_t pid = fork(); + + if (pid == 0) { + /* CHILD */ + + /* Change running state to the user in question */ + + if (ChangeUser(user) < 0) { + exit(0); + } +#ifdef FEATURE_DEBUG_OPT + if (DebugOpt) { + crondlog("\005Child Running %s\n", DEFAULT_SHELL); + } +#endif + + execl(DEFAULT_SHELL, DEFAULT_SHELL, "-c", line->cl_Shell, NULL); + crondlog("\024unable to exec, user %s cmd %s -c %s\n", user, + DEFAULT_SHELL, line->cl_Shell); + exit(0); + } else if (pid < 0) { + /* FORK FAILED */ + crondlog("\024couldn't fork, user %s\n", user); + pid = 0; + } + line->cl_Pid = pid; +} +#endif /* CONFIG_FEATURE_CROND_CALL_SENDMAIL */ diff --git a/busybox/miscutils/crontab.c b/busybox/miscutils/crontab.c new file mode 100644 index 0000000..89e1377 --- /dev/null +++ b/busybox/miscutils/crontab.c @@ -0,0 +1,368 @@ +/* + * CRONTAB + * + * usually setuid root, -c option only works if getuid() == geteuid() + * + * Copyright 1994 Matthew Dillon (dillon@apollo.west.oic.com) + * May be distributed under the GNU General Public License + * + * Vladimir Oleynik (C) 2002 to be used in busybox + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifndef CRONTABS +#define CRONTABS "/var/spool/cron/crontabs" +#endif +#ifndef TMPDIR +#define TMPDIR "/var/spool/cron" +#endif +#ifndef CRONUPDATE +#define CRONUPDATE "cron.update" +#endif +#ifndef PATH_VI +#define PATH_VI "/bin/vi" /* location of vi */ +#endif + +#include "busybox.h" + +static const char *CDir = CRONTABS; + +static void EditFile(const char *user, const char *file); +static int GetReplaceStream(const char *user, const char *file); +static int ChangeUser(const char *user, short dochdir); + +int +crontab_main(int ac, char **av) +{ + enum { NONE, EDIT, LIST, REPLACE, DELETE } option = NONE; + const struct passwd *pas; + const char *repFile = NULL; + int repFd = 0; + int i; + char caller[256]; /* user that ran program */ + int UserId; + + UserId = getuid(); + if ((pas = getpwuid(UserId)) == NULL) + bb_perror_msg_and_die("getpwuid"); + + strncpy(caller, pas->pw_name, sizeof(caller)); + + i = 1; + if (ac > 1) { + if (av[1][0] == '-' && av[1][1] == 0) { + option = REPLACE; + ++i; + } else if (av[1][0] != '-') { + option = REPLACE; + ++i; + repFile = av[1]; + } + } + + for (; i < ac; ++i) { + char *ptr = av[i]; + + if (*ptr != '-') + break; + ptr += 2; + + switch(ptr[-1]) { + case 'l': + if (ptr[-1] == 'l') + option = LIST; + /* fall through */ + case 'e': + if (ptr[-1] == 'e') + option = EDIT; + /* fall through */ + case 'd': + if (ptr[-1] == 'd') + option = DELETE; + /* fall through */ + case 'u': + if (i + 1 < ac && av[i+1][0] != '-') { + ++i; + if (getuid() == geteuid()) { + pas = getpwnam(av[i]); + if (pas) { + UserId = pas->pw_uid; + } else { + bb_error_msg_and_die("user %s unknown", av[i]); + } + } else { + bb_error_msg_and_die("only the superuser may specify a user"); + } + } + break; + case 'c': + if (getuid() == geteuid()) { + CDir = (*ptr) ? ptr : av[++i]; + } else { + bb_error_msg_and_die("-c option: superuser only"); + } + break; + default: + i = ac; + break; + } + } + if (i != ac || option == NONE) + bb_show_usage(); + + /* + * Get password entry + */ + + if ((pas = getpwuid(UserId)) == NULL) + bb_perror_msg_and_die("getpwuid"); + + /* + * If there is a replacement file, obtain a secure descriptor to it. + */ + + if (repFile) { + repFd = GetReplaceStream(caller, repFile); + if (repFd < 0) + bb_error_msg_and_die("unable to read replacement file"); + } + + /* + * Change directory to our crontab directory + */ + + if (chdir(CDir) < 0) + bb_perror_msg_and_die("cannot change dir to %s", CDir); + + /* + * Handle options as appropriate + */ + + switch(option) { + case LIST: + { + FILE *fi; + char buf[1024]; + + if ((fi = fopen(pas->pw_name, "r"))) { + while (fgets(buf, sizeof(buf), fi) != NULL) + fputs(buf, stdout); + fclose(fi); + } else { + bb_error_msg("no crontab for %s", pas->pw_name); + } + } + break; + case EDIT: + { + FILE *fi; + int fd; + int n; + char tmp[128]; + char buf[1024]; + + snprintf(tmp, sizeof(tmp), TMPDIR "/crontab.%d", getpid()); + if ((fd = open(tmp, O_RDWR|O_CREAT|O_TRUNC|O_EXCL, 0600)) >= 0) { + chown(tmp, getuid(), getgid()); + if ((fi = fopen(pas->pw_name, "r"))) { + while ((n = fread(buf, 1, sizeof(buf), fi)) > 0) + write(fd, buf, n); + } + EditFile(caller, tmp); + remove(tmp); + lseek(fd, 0L, 0); + repFd = fd; + } else { + bb_error_msg_and_die("unable to create %s", tmp); + } + + } + option = REPLACE; + /* fall through */ + case REPLACE: + { + char buf[1024]; + char path[1024]; + int fd; + int n; + + snprintf(path, sizeof(path), "%s.new", pas->pw_name); + if ((fd = open(path, O_CREAT|O_TRUNC|O_APPEND|O_WRONLY, 0600)) >= 0) { + while ((n = read(repFd, buf, sizeof(buf))) > 0) { + write(fd, buf, n); + } + close(fd); + rename(path, pas->pw_name); + } else { + bb_error_msg("unable to create %s/%s", CDir, path); + } + close(repFd); + } + break; + case DELETE: + remove(pas->pw_name); + break; + case NONE: + default: + break; + } + + /* + * Bump notification file. Handle window where crond picks file up + * before we can write our entry out. + */ + + if (option == REPLACE || option == DELETE) { + FILE *fo; + struct stat st; + + while ((fo = fopen(CRONUPDATE, "a"))) { + fprintf(fo, "%s\n", pas->pw_name); + fflush(fo); + if (fstat(fileno(fo), &st) != 0 || st.st_nlink != 0) { + fclose(fo); + break; + } + fclose(fo); + /* loop */ + } + if (fo == NULL) { + bb_error_msg("unable to append to %s/%s", CDir, CRONUPDATE); + } + } + return 0; +} + +static int +GetReplaceStream(const char *user, const char *file) +{ + int filedes[2]; + int pid; + int fd; + int n; + char buf[1024]; + + if (pipe(filedes) < 0) { + perror("pipe"); + return(-1); + } + if ((pid = fork()) < 0) { + perror("fork"); + return(-1); + } + if (pid > 0) { + /* + * PARENT + */ + + close(filedes[1]); + if (read(filedes[0], buf, 1) != 1) { + close(filedes[0]); + filedes[0] = -1; + } + return(filedes[0]); + } + + /* + * CHILD + */ + + close(filedes[0]); + + if (ChangeUser(user, 0) < 0) + exit(0); + + fd = open(file, O_RDONLY); + if (fd < 0) { + bb_error_msg("unable to open %s", file); + exit(0); + } + buf[0] = 0; + write(filedes[1], buf, 1); + while ((n = read(fd, buf, sizeof(buf))) > 0) { + write(filedes[1], buf, n); + } + exit(0); +} + +static void +EditFile(const char *user, const char *file) +{ + int pid; + + if ((pid = fork()) == 0) { + /* + * CHILD - change user and run editor + */ + char *ptr; + char visual[1024]; + + if (ChangeUser(user, 1) < 0) + exit(0); + if ((ptr = getenv("VISUAL")) == NULL || strlen(ptr) > 256) + ptr = PATH_VI; + + snprintf(visual, sizeof(visual), "%s %s", ptr, file); + execl(DEFAULT_SHELL, DEFAULT_SHELL, "-c", visual, NULL); + perror("exec"); + exit(0); + } + if (pid < 0) { + /* + * PARENT - failure + */ + bb_perror_msg_and_die("fork"); + } + wait4(pid, NULL, 0, NULL); +} + +static int +ChangeUser(const char *user, short dochdir) +{ + struct passwd *pas; + + /* + * Obtain password entry and change privileges + */ + + if ((pas = getpwnam(user)) == 0) { + bb_perror_msg_and_die("failed to get uid for %s", user); + return(-1); + } + setenv("USER", pas->pw_name, 1); + setenv("HOME", pas->pw_dir, 1); + setenv("SHELL", DEFAULT_SHELL, 1); + + /* + * Change running state to the user in question + */ + change_identity(pas); + + if (dochdir) { + if (chdir(pas->pw_dir) < 0) { + bb_perror_msg_and_die("chdir failed: %s %s", user, pas->pw_dir); + if (chdir(TMPDIR) < 0) { + bb_perror_msg_and_die("chdir failed: %s %s", user, TMPDIR); + return(-1); + } + } + } + return(pas->pw_uid); +} diff --git a/busybox/miscutils/dc.c b/busybox/miscutils/dc.c new file mode 100644 index 0000000..112f6df --- /dev/null +++ b/busybox/miscutils/dc.c @@ -0,0 +1,228 @@ +/* vi: set sw=4 ts=4: */ +#include +#include +#include +#include +#include +#include +#include "busybox.h" + +/* Tiny RPN calculator, because "expr" didn't give me bitwise operations. */ + +static double stack[100]; +static unsigned int pointer; +static unsigned char base; + +static void push(double a) +{ + if (pointer >= (sizeof(stack) / sizeof(*stack))) + bb_error_msg_and_die("stack overflow"); + stack[pointer++] = a; +} + +static double pop(void) +{ + if (pointer == 0) + bb_error_msg_and_die("stack underflow"); + return stack[--pointer]; +} + +static void add(void) +{ + push(pop() + pop()); +} + +static void sub(void) +{ + double subtrahend = pop(); + + push(pop() - subtrahend); +} + +static void mul(void) +{ + push(pop() * pop()); +} + +static void power(void) +{ + double topower = pop(); + + push(pow(pop(), topower)); +} + +static void divide(void) +{ + double divisor = pop(); + + push(pop() / divisor); +} + +static void mod(void) +{ + unsigned int d = pop(); + + push((unsigned int) pop() % d); +} + +static void and(void) +{ + push((unsigned int) pop() & (unsigned int) pop()); +} + +static void or(void) +{ + push((unsigned int) pop() | (unsigned int) pop()); +} + +static void eor(void) +{ + push((unsigned int) pop() ^ (unsigned int) pop()); +} + +static void not(void) +{ + push(~(unsigned int) pop()); +} + +static void set_output_base(void) +{ + base=(unsigned char)pop(); + if ((base != 10) && (base != 16)) { + fprintf(stderr, "Error: base = %d is not supported.\n", base); + base=10; + } +} + +static void print_base(double print) +{ + if (base == 16) + printf("%x\n", (unsigned int)print); + else + printf("%g\n", print); +} + +static void print_stack_no_pop(void) +{ + unsigned int i=pointer; + while (i) + print_base(stack[--i]); +} + +static void print_no_pop(void) +{ + print_base(stack[pointer-1]); +} + +struct op { + const char *name; + void (*function) (void); +}; + +static const struct op operators[] = { + {"+", add}, + {"add", add}, + {"-", sub}, + {"sub", sub}, + {"*", mul}, + {"mul", mul}, + {"/", divide}, + {"div", divide}, + {"**", power}, + {"exp", power}, + {"pow", power}, + {"%", mod}, + {"mod", mod}, + {"and", and}, + {"or", or}, + {"not", not}, + {"eor", eor}, + {"xor", eor}, + {"p", print_no_pop}, + {"f", print_stack_no_pop}, + {"o", set_output_base}, + {0, 0} +}; + +static void stack_machine(const char *argument) +{ + char *endPointer = 0; + double d; + const struct op *o = operators; + + if (argument == 0) + return; + + d = strtod(argument, &endPointer); + + if (endPointer != argument) { + push(d); + return; + } + + while (o->name != 0) { + if (strcmp(o->name, argument) == 0) { + (*(o->function)) (); + return; + } + o++; + } + bb_error_msg_and_die("%s: syntax error.", argument); +} + +/* return pointer to next token in buffer and set *buffer to one char + * past the end of the above mentioned token + */ +static char *get_token(char **buffer) +{ + char *start = NULL; + char *current = *buffer; + + while (isspace(*current)) { current++; } + if (*current != 0) { + start = current; + while (!isspace(*current) && *current != 0) { current++; } + *buffer = current; + } + return start; +} + +/* In Perl one might say, scalar m|\s*(\S+)\s*|g */ +static int number_of_tokens(char *buffer) +{ + int i = 0; + char *b = buffer; + while (get_token(&b)) { i++; } + return i; +} + +int dc_main(int argc, char **argv) +{ + /* take stuff from stdin if no args are given */ + if (argc <= 1) { + int i, len; + char *line = NULL; + char *cursor = NULL; + char *token = NULL; + while ((line = bb_get_chomped_line_from_file(stdin))) { + cursor = line; + len = number_of_tokens(line); + for (i = 0; i < len; i++) { + token = get_token(&cursor); + *cursor++ = 0; + stack_machine(token); + } + free(line); + } + } else { + if (*argv[1]=='-') + bb_show_usage(); + while (argc >= 2) { + stack_machine(argv[1]); + argv++; + argc--; + } + } + stack_machine(0); + return EXIT_SUCCESS; +} diff --git a/busybox/miscutils/devfsd.c b/busybox/miscutils/devfsd.c new file mode 100644 index 0000000..5e183e6 --- /dev/null +++ b/busybox/miscutils/devfsd.c @@ -0,0 +1,2183 @@ +/* + devfsd implementation for busybox + + Copyright (C) 2003 by Tito Ragusa + + Busybox version is based on some previous work and ideas + Copyright (C) [2003] by [Matteo Croce] <3297627799@wind.it> + + devfsd.c + + Main file for devfsd (devfs daemon for Linux). + + Copyright (C) 1998-2002 Richard Gooch + + devfsd.h + + Header file for devfsd (devfs daemon for Linux). + + Copyright (C) 1998-2000 Richard Gooch + + compat_name.c + + Compatibility name file for devfsd (build compatibility names). + + Copyright (C) 1998-2002 Richard Gooch + + expression.c + + This code provides Borne Shell-like expression expansion. + + Copyright (C) 1997-1999 Richard Gooch + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + + Richard Gooch may be reached by email at rgooch@atnf.csiro.au + The postal address is: + Richard Gooch, c/o ATNF, P. O. Box 76, Epping, N.S.W., 2121, Australia. +*/ + +#include "libbb.h" +#include "busybox.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +/* Various defines taken from linux/major.h */ +#define IDE0_MAJOR 3 +#define IDE1_MAJOR 22 +#define IDE2_MAJOR 33 +#define IDE3_MAJOR 34 +#define IDE4_MAJOR 56 +#define IDE5_MAJOR 57 +#define IDE6_MAJOR 88 +#define IDE7_MAJOR 89 +#define IDE8_MAJOR 90 +#define IDE9_MAJOR 91 + + +/* Various defines taken from linux/devfs_fs.h */ +#define DEVFSD_PROTOCOL_REVISION_KERNEL 5 +#define DEVFSD_IOCTL_BASE 'd' +/* These are the various ioctls */ +#define DEVFSDIOC_GET_PROTO_REV _IOR(DEVFSD_IOCTL_BASE, 0, int) +#define DEVFSDIOC_SET_EVENT_MASK _IOW(DEVFSD_IOCTL_BASE, 2, int) +#define DEVFSDIOC_RELEASE_EVENT_QUEUE _IOW(DEVFSD_IOCTL_BASE, 3, int) +#define DEVFSDIOC_SET_CONFIG_DEBUG_MASK _IOW(DEVFSD_IOCTL_BASE, 4, int) +#define DEVFSD_NOTIFY_REGISTERED 0 +#define DEVFSD_NOTIFY_UNREGISTERED 1 +#define DEVFSD_NOTIFY_ASYNC_OPEN 2 +#define DEVFSD_NOTIFY_CLOSE 3 +#define DEVFSD_NOTIFY_LOOKUP 4 +#define DEVFSD_NOTIFY_CHANGE 5 +#define DEVFSD_NOTIFY_CREATE 6 +#define DEVFSD_NOTIFY_DELETE 7 +#define DEVFS_PATHLEN 1024 +/* Never change this otherwise the binary interface will change */ + +struct devfsd_notify_struct +{ /* Use native C types to ensure same types in kernel and user space */ + unsigned int type; /* DEVFSD_NOTIFY_* value */ + unsigned int mode; /* Mode of the inode or device entry */ + unsigned int major; /* Major number of device entry */ + unsigned int minor; /* Minor number of device entry */ + unsigned int uid; /* Uid of process, inode or device entry */ + unsigned int gid; /* Gid of process, inode or device entry */ + unsigned int overrun_count; /* Number of lost events */ + unsigned int namelen; /* Number of characters not including '\0' */ + /* The device name MUST come last */ + char devname[DEVFS_PATHLEN]; /* This will be '\0' terminated */ +}; + +#define BUFFER_SIZE 16384 +#define DEVFSD_VERSION "1.3.25" +#define CONFIG_FILE "/etc/devfsd.conf" +#define MODPROBE "/sbin/modprobe" +#define MODPROBE_SWITCH_1 "-k" +#define MODPROBE_SWITCH_2 "-C" +#define CONFIG_MODULES_DEVFS "/etc/modules.devfs" +#define MAX_ARGS (6 + 1) +#define MAX_SUBEXPR 10 +#define STRING_LENGTH 255 + +/* for get_uid_gid() */ +#define UID 0 +#define GID 1 + +/* for msg_logger(), do_ioctl(), + fork_and_execute() */ +# define DIE 1 +# define NO_DIE 0 + +/* for dir_operation() */ +#define RESTORE 0 +#define SERVICE 1 +#define READ_CONFIG 2 + +/* Update only after changing code to reflect new protocol */ +#define DEVFSD_PROTOCOL_REVISION_DAEMON 5 + +/* Compile-time check */ +#if DEVFSD_PROTOCOL_REVISION_KERNEL != DEVFSD_PROTOCOL_REVISION_DAEMON +#error protocol version mismatch. Update your kernel headers +#endif + +#define AC_PERMISSIONS 0 +#define AC_MODLOAD 1 +#define AC_EXECUTE 2 +#define AC_MFUNCTION 3 /* not supported by busybox */ +#define AC_CFUNCTION 4 /* not supported by busybox */ +#define AC_COPY 5 +#define AC_IGNORE 6 +#define AC_MKOLDCOMPAT 7 +#define AC_MKNEWCOMPAT 8 +#define AC_RMOLDCOMPAT 9 +#define AC_RMNEWCOMPAT 10 +#define AC_RESTORE 11 + + +struct permissions_type +{ + mode_t mode; + uid_t uid; + gid_t gid; +}; + +struct execute_type +{ + char *argv[MAX_ARGS + 1]; /* argv[0] must always be the programme */ +}; + +struct copy_type +{ + const char *source; + const char *destination; +}; + +struct action_type +{ + unsigned int what; + unsigned int when; +}; + +struct config_entry_struct +{ + struct action_type action; + regex_t preg; + union + { + struct permissions_type permissions; + struct execute_type execute; + struct copy_type copy; + } + u; + struct config_entry_struct *next; +}; + +struct get_variable_info +{ + const struct devfsd_notify_struct *info; + const char *devname; + char devpath[STRING_LENGTH]; +}; + +static void dir_operation(int , const char * , int, unsigned long* ); +static void service(struct stat statbuf, char *path); +static int st_expr_expand(char *, unsigned, const char *, const char *(*) (const char *, void *), void *); +static const char *get_old_name(const char *, unsigned, char *, unsigned, unsigned); +static int mksymlink (const char *oldpath, const char *newpath); +static void read_config_file (char *path, int optional, unsigned long *event_mask); +static void process_config_line (const char *, unsigned long *); +static int do_servicing (int, unsigned long); +static void service_name (const struct devfsd_notify_struct *); +static void action_permissions (const struct devfsd_notify_struct *, const struct config_entry_struct *); +static void action_execute (const struct devfsd_notify_struct *, const struct config_entry_struct *, + const regmatch_t *, unsigned); +#ifdef CONFIG_DEVFSD_MODLOAD +static void action_modload (const struct devfsd_notify_struct *info, const struct config_entry_struct *entry); +#endif +static void action_copy (const struct devfsd_notify_struct *, const struct config_entry_struct *, + const regmatch_t *, unsigned); +static void action_compat (const struct devfsd_notify_struct *, unsigned); +static void free_config (void); +static void restore(char *spath, struct stat source_stat, int rootlen); +static int copy_inode (const char *, const struct stat *, mode_t, const char *, const struct stat *); +static mode_t get_mode (const char *); +static void signal_handler (int); +static const char *get_variable (const char *, void *); +static int make_dir_tree (const char *); +static int expand_expression(char *, unsigned, const char *, const char *(*)(const char *, void *), void *, + const char *, const regmatch_t *, unsigned ); +static void expand_regexp (char *, size_t, const char *, const char *, const regmatch_t *, unsigned ); +static const char *expand_variable( char *, unsigned, unsigned *, const char *, + const char *(*) (const char *, void *), void * ); +static const char *get_variable_v2(const char *, const char *(*) (const char *, void *), void *); +static char get_old_ide_name (unsigned , unsigned); +static char *write_old_sd_name (char *, unsigned, unsigned, char *); + +/* busybox functions */ +#if defined(CONFIG_DEVFSD_VERBOSE) || defined(CONFIG_DEBUG) +static void msg_logger(int die, int pri, const char * fmt, ... ); +#endif +static void do_ioctl(int die, int fd, int request, unsigned long event_mask_flag); +static void fork_and_execute(int die, char *arg0, char **arg ); +static int get_uid_gid ( int, const char *); +static void safe_memcpy( char * dest, const char * src, int len); +static unsigned int scan_dev_name_common(const char *d, unsigned int n, int addendum, char *ptr); +static unsigned int scan_dev_name(const char *d, unsigned int n, char *ptr); + +/* Structs and vars */ +static struct config_entry_struct *first_config = NULL; +static struct config_entry_struct *last_config = NULL; +static const char *mount_point = NULL; +static volatile int caught_signal = FALSE; +static volatile int caught_sighup = FALSE; +static struct initial_symlink_struct +{ + char *dest; + char *name; +} initial_symlinks[] = +{ + {"/proc/self/fd", "fd"}, + {"fd/0", "stdin"}, + {"fd/1", "stdout"}, + {"fd/2", "stderr"}, + {NULL, NULL}, +}; + +static struct event_type +{ + unsigned int type; /* The DEVFSD_NOTIFY_* value */ + const char *config_name; /* The name used in the config file */ +} event_types[] = +{ + {DEVFSD_NOTIFY_REGISTERED, "REGISTER"}, + {DEVFSD_NOTIFY_UNREGISTERED, "UNREGISTER"}, + {DEVFSD_NOTIFY_ASYNC_OPEN, "ASYNC_OPEN"}, + {DEVFSD_NOTIFY_CLOSE, "CLOSE"}, + {DEVFSD_NOTIFY_LOOKUP, "LOOKUP"}, + {DEVFSD_NOTIFY_CHANGE, "CHANGE"}, + {DEVFSD_NOTIFY_CREATE, "CREATE"}, + {DEVFSD_NOTIFY_DELETE, "DELETE"}, + {0xffffffff, NULL} +}; + +/* busybox functions and messages */ + +extern void xregcomp(regex_t * preg, const char *regex, int cflags); + +const char * const bb_msg_proto_rev = "protocol revision"; +#ifdef CONFIG_DEVFSD_VERBOSE +const char * const bb_msg_bad_config = "bad %s config file: %s\n"; +const char * const bb_msg_small_buffer = "buffer too small\n"; +const char * const bb_msg_variable_not_found = "variable: %s not found\n"; +#endif + +#if defined(CONFIG_DEVFSD_VERBOSE) || defined(CONFIG_DEBUG) +static void msg_logger(int die, int pri, const char * fmt, ... ) +{ + va_list ap; + + va_start(ap, fmt); + if (access ("/dev/log", F_OK) == 0) + { + openlog(bb_applet_name, 0, LOG_DAEMON); + vsyslog( pri , fmt , ap); + closelog(); + } +#ifndef CONFIG_DEBUG + else +#endif + bb_verror_msg(fmt, ap); + va_end(ap); + if(die==DIE) + exit(EXIT_FAILURE); +} +#endif + +static void do_ioctl(int die, int fd, int request, unsigned long event_mask_flag) +{ +#ifdef CONFIG_DEVFSD_VERBOSE + if (ioctl (fd, request, event_mask_flag) == -1) + msg_logger(die, LOG_ERR, "ioctl(): %m\n"); +#else + if (ioctl (fd, request, event_mask_flag) == -1) + exit(EXIT_FAILURE); +#endif +} + +static void fork_and_execute(int die, char *arg0, char **arg ) +{ + switch ( fork () ) + { + case 0: + /* Child */ + break; + case -1: + /* Parent: Error : die or return */ +#ifdef CONFIG_DEVFSD_VERBOSE + msg_logger(die, LOG_ERR,(char *) bb_msg_memory_exhausted); +#else + if(die == DIE) + exit(EXIT_FAILURE); +#endif + return; + default: + /* Parent : ok : return or exit */ + if(arg0 != NULL) + { + wait (NULL); + return; + } + exit (EXIT_SUCCESS); + } + /* Child : if arg0 != NULL do execvp */ + if(arg0 != NULL ) + { + execvp (arg0, arg); +#ifdef CONFIG_DEVFSD_VERBOSE + msg_logger(DIE, LOG_ERR, "execvp(): %s: %m\n", arg0); +#else + exit(EXIT_FAILURE); +#endif + } +} + +static void safe_memcpy( char *dest, const char *src, int len) +{ + memcpy (dest , src , len ); + dest[len] = '\0'; +} + +static unsigned int scan_dev_name_common(const char *d, unsigned int n, int addendum, char *ptr) +{ + if( d[n - 4]=='d' && d[n - 3]=='i' && d[n - 2]=='s' && d[n - 1]=='c') + return (2 + addendum); + else if( d[n - 2]=='c' && d[n - 1]=='d') + return (3 + addendum); + else if(ptr[0]=='p' && ptr[1]=='a' && ptr[2]=='r' && ptr[3]=='t') + return (4 + addendum); + else if( ptr[n - 2]=='m' && ptr[n - 1]=='t') + return (5 + addendum); + else + return 0; +} + +static unsigned int scan_dev_name(const char *d, unsigned int n, char *ptr) +{ + if(d[0]=='s' && d[1]=='c' && d[2]=='s' && d[3]=='i' && d[4]=='/') + { + if( d[n - 7]=='g' && d[n - 6]=='e' && d[n - 5]=='n' && + d[n - 4]=='e' && d[n - 3]=='r' && d[n - 2]=='i' && + d[n - 1]=='c' ) + return 1; + return scan_dev_name_common(d, n, 0, ptr); + } + else if(d[0]=='i' && d[1]=='d' && d[2]=='e' && d[3]=='/' && + d[4]=='h' && d[5]=='o' && d[6]=='s' && d[7]=='t') + { + return scan_dev_name_common(d, n, 4, ptr); + } + else if(d[0]=='s' && d[1]=='b' && d[2]=='p' && d[3]=='/') + { + return 10; + } + else if(d[0]=='v' && d[1]=='c' && d[2]=='c' && d[3]=='/') + { + return 11; + } + else if(d[0]=='p' && d[1]=='t' && d[2]=='y' && d[3]=='/') + { + return 12; + } + return 0; +} + +/* Public functions follow */ + +int devfsd_main (int argc, char **argv) +{ + int print_version = FALSE; +#ifdef CONFIG_DEVFSD_FG_NP + int do_daemon = TRUE; + int no_polling = FALSE; +#endif + int do_scan; + int fd, proto_rev, count; + unsigned long event_mask = 0; + struct sigaction new_action; + struct initial_symlink_struct *curr; + + if (argc < 2) + bb_show_usage(); + + for (count = 2; count < argc; ++count) + { + if(argv[count][0] == '-') + { + if(argv[count][1]=='v' && !argv[count][2]) /* -v */ + print_version = TRUE; +#ifdef CONFIG_DEVFSD_FG_NP + else if(argv[count][1]=='f' && argv[count][2]=='g' && !argv[count][3]) /* -fg */ + do_daemon = FALSE; + else if(argv[count][1]=='n' && argv[count][2]=='p' && !argv[count][3]) /* -np */ + no_polling = TRUE; +#endif + else + bb_show_usage(); + } + } + + /* strip last / from mount point, so we don't need to check for it later */ + while( argv[1][1]!='\0' && argv[1][strlen(argv[1])-1] == '/' ) + argv[1][strlen(argv[1]) -1] = '\0'; + + mount_point = argv[1]; + + if (chdir (mount_point) != 0) +#ifdef CONFIG_DEVFSD_VERBOSE + bb_error_msg_and_die( " %s: %m", mount_point); +#else + exit(EXIT_FAILURE); +#endif + + fd = bb_xopen (".devfsd", O_RDONLY); + + if (fcntl (fd, F_SETFD, FD_CLOEXEC) != 0) +#ifdef CONFIG_DEVFSD_VERBOSE + bb_error_msg( "FD_CLOEXEC"); +#else + exit(EXIT_FAILURE); +#endif + + do_ioctl(DIE, fd, DEVFSDIOC_GET_PROTO_REV,(int )&proto_rev); + + /*setup initial entries */ + for (curr = initial_symlinks; curr->dest != NULL; ++curr) + symlink (curr->dest, curr->name); + + /* NB: The check for CONFIG_FILE is done in read_config_file() */ + + if ( print_version || (DEVFSD_PROTOCOL_REVISION_DAEMON != proto_rev) ) + { + bb_printf( "%s v%s\nDaemon %s:\t%d\nKernel-side %s:\t%d\n", + bb_applet_name,DEVFSD_VERSION,bb_msg_proto_rev, + DEVFSD_PROTOCOL_REVISION_DAEMON,bb_msg_proto_rev, proto_rev); + if (DEVFSD_PROTOCOL_REVISION_DAEMON != proto_rev) + bb_error_msg_and_die( "%s mismatch!",bb_msg_proto_rev); + exit(EXIT_SUCCESS); /* -v */ + } + /* Tell kernel we are special (i.e. we get to see hidden entries) */ + do_ioctl(DIE, fd, DEVFSDIOC_SET_EVENT_MASK, 0); + + sigemptyset (&new_action.sa_mask); + new_action.sa_flags = 0; + + /* Set up SIGHUP and SIGUSR1 handlers */ + new_action.sa_handler = signal_handler; + if (sigaction (SIGHUP, &new_action, NULL) != 0 || sigaction (SIGUSR1, &new_action, NULL) != 0 ) +#ifdef CONFIG_DEVFSD_VERBOSE + bb_error_msg_and_die( "sigaction()"); +#else + exit(EXIT_FAILURE); +#endif + + bb_printf("%s v%s started for %s\n",bb_applet_name, DEVFSD_VERSION, mount_point); + + /* Set umask so that mknod(2), open(2) and mkdir(2) have complete control over permissions */ + umask (0); + read_config_file (CONFIG_FILE, FALSE, &event_mask); + /* Do the scan before forking, so that boot scripts see the finished product */ + dir_operation(SERVICE,mount_point,0,NULL); +#ifdef CONFIG_DEVFSD_FG_NP + if (no_polling) + exit (0); + if (do_daemon) + { +#endif + /* Release so that the child can grab it */ + do_ioctl(DIE, fd, DEVFSDIOC_RELEASE_EVENT_QUEUE, 0); + fork_and_execute(DIE, NULL, NULL); + setsid (); /* Prevent hangups and become pgrp leader */ +#ifdef CONFIG_DEVFSD_FG_NP + } + else + setpgid (0, 0); /* Become process group leader */ +#endif + + while (TRUE) + { + do_scan = do_servicing (fd, event_mask); + + free_config (); + read_config_file (CONFIG_FILE, FALSE, &event_mask); + if (do_scan) + dir_operation(SERVICE,mount_point,0,NULL); + } +} /* End Function main */ + + +/* Private functions follow */ + +static void read_config_file (char *path, int optional, unsigned long *event_mask) +/* [SUMMARY] Read a configuration database. + The path to read the database from. If this is a directory, all + entries in that directory will be read (except hidden entries). + If TRUE, the routine will silently ignore a missing config file. + The event mask is written here. This is not initialised. + [RETURNS] Nothing. +*/ +{ + struct stat statbuf; + FILE *fp; + char buf[STRING_LENGTH]; + char *line=NULL; + +#ifdef CONFIG_DEBUG + msg_logger( NO_DIE, LOG_INFO, "read_config_file(): %s\n", path); +#endif + if (stat (path, &statbuf) != 0 || statbuf.st_size == 0 ) + goto read_config_file_err; + + if ( S_ISDIR (statbuf.st_mode) ) + { + /* strip last / from dirname so we don't need to check for it later */ + while( path && path[1]!='\0' && path[strlen(path)-1] == '/') + path[strlen(path) -1] = '\0'; + + dir_operation(READ_CONFIG, path, 0, event_mask); + return; + } + + if ( ( fp = fopen (path, "r") ) != NULL ) + { + while (fgets (buf, STRING_LENGTH, fp) != NULL) + { + /* GETS(3) Linux Programmer's Manual + fgets() reads in at most one less than size characters from stream and + stores them into the buffer pointed to by s. Reading stops after an + EOF or a newline. If a newline is read, it is stored into the buffer. + A '\0' is stored after the last character in the buffer. + */ + /*buf[strlen (buf) - 1] = '\0';*/ + /* Skip whitespace */ + for (line = buf; isspace (*line); ++line) + /*VOID*/; + if (line[0] == '\0' || line[0] == '#' ) + continue; + process_config_line (line, event_mask); + } + fclose (fp); + errno=0; + } +read_config_file_err: +#ifdef CONFIG_DEVFSD_VERBOSE + msg_logger(((optional == 0 ) && (errno == ENOENT))? DIE : NO_DIE, LOG_ERR, "read config file: %s: %m\n", path); +#else + if(optional == 0 && errno == ENOENT) + exit(EXIT_FAILURE); +#endif + return; +} /* End Function read_config_file */ + +static void process_config_line (const char *line, unsigned long *event_mask) +/* [SUMMARY] Process a line from a configuration file. + The configuration line. + The event mask is written here. This is not initialised. + [RETURNS] Nothing. +*/ +{ + int num_args, count; + struct config_entry_struct *new; + char p[MAX_ARGS][STRING_LENGTH]; + char when[STRING_LENGTH], what[STRING_LENGTH]; + char name[STRING_LENGTH]; + char * msg=""; + char *ptr; + + /* !!!! Only Uppercase Keywords in devsfd.conf */ + const char *options[] = { "CLEAR_CONFIG", "INCLUDE", "OPTIONAL_INCLUDE", "RESTORE", + "PERMISSIONS", "MODLOAD", "EXECUTE", "COPY", "IGNORE", + "MKOLDCOMPAT", "MKNEWCOMPAT","RMOLDCOMPAT", "RMNEWCOMPAT", 0 }; + + short int i; + +#ifdef CONFIG_DEBUG + msg_logger( NO_DIE, LOG_INFO, "process_config_line()\n"); +#endif + + for (count = 0; count < MAX_ARGS; ++count) p[count][0] = '\0'; + num_args = sscanf (line, "%s %s %s %s %s %s %s %s %s %s", + when, name, what, + p[0], p[1], p[2], p[3], p[4], p[5], p[6]); + + i = compare_string_array(options, when ); + + /*"CLEAR_CONFIG"*/ + if( i == 0) + { + free_config (); + *event_mask = 0; + return; + } + + if ( num_args < 2) + goto process_config_line_err; + + /* "INCLUDE" & "OPTIONAL_INCLUDE" */ + if( i == 1 || i == 2 ) + { + st_expr_expand (name, STRING_LENGTH, name, get_variable, NULL ); +#ifdef CONFIG_DEBUG + msg_logger( NO_DIE, LOG_INFO, "%sinclude: %s\n",(toupper (when[0]) == 'I') ? "": "optional_", name); +#endif + read_config_file (name, (toupper (when[0]) == 'I') ? FALSE : TRUE, event_mask); + return; + } + /* "RESTORE" */ + if( i == 3) + { + dir_operation(RESTORE,name, strlen (name),NULL); + return; + } + if (num_args < 3) + goto process_config_line_err; + + new = xmalloc (sizeof *new); + memset (new, 0, sizeof *new); + + for (count = 0; event_types[count].config_name != NULL; ++count) + { + if (strcasecmp (when, event_types[count].config_name) != 0) + continue; + new->action.when = event_types[count].type; + break; + } + if (event_types[count].config_name == NULL) + { + msg="WHEN in"; + goto process_config_line_err; + } + + i = compare_string_array(options, what ); + + switch(i) + { + case 4: /* "PERMISSIONS" */ + new->action.what = AC_PERMISSIONS; + /* Get user and group */ + if ( ( ptr = strchr (p[0], '.') ) == NULL ) + { + msg="UID.GID"; + goto process_config_line_err; /*"missing '.' in UID.GID */ + } + + *ptr++ = '\0'; + new->u.permissions.uid = get_uid_gid (UID, p[0]); + new->u.permissions.gid = get_uid_gid (GID, ptr); + /* Get mode */ + new->u.permissions.mode = get_mode (p[1]); + break; +#ifdef CONFIG_DEVFSD_MODLOAD + case 5: /* MODLOAD */ + /*This action will pass "/dev/$devname" (i.e. "/dev/" prefixed to + the device name) to the module loading facility. In addition, + the /etc/modules.devfs configuration file is used.*/ + new->action.what = AC_MODLOAD; + break; +#endif + case 6: /* EXECUTE */ + new->action.what = AC_EXECUTE; + num_args -= 3; + + for (count = 0; count < num_args; ++count) + new->u.execute.argv[count] = bb_xstrdup (p[count]); + + new->u.execute.argv[num_args] = NULL; + break; + case 7: /* COPY */ + new->action.what = AC_COPY; + num_args -= 3; + if (num_args != 2) + goto process_config_line_err; /* missing path and function in line */ + + new->u.copy.source = bb_xstrdup (p[0]); + new->u.copy.destination = bb_xstrdup (p[1]); + break; + case 8: /* IGNORE */ + /* FALLTROUGH */ + case 9: /* MKOLDCOMPAT */ + /* FALLTROUGH */ + case 10: /* MKNEWCOMPAT */ + /* FALLTROUGH */ + case 11:/* RMOLDCOMPAT */ + /* FALLTROUGH */ + case 12: /* RMNEWCOMPAT */ + /* AC_IGNORE 6 + AC_MKOLDCOMPAT 7 + AC_MKNEWCOMPAT 8 + AC_RMOLDCOMPAT 9 + AC_RMNEWCOMPAT 10*/ + new->action.what = i - 2; + break; + default: + msg ="WHAT in"; + goto process_config_line_err; + /*esac*/ + } /* switch (i) */ + + xregcomp( &new->preg, name, REG_EXTENDED); + + *event_mask |= 1 << new->action.when; + new->next = NULL; + if (first_config == NULL) + first_config = new; + else + last_config->next = new; + last_config = new; + return; +process_config_line_err: +#ifdef CONFIG_DEVFSD_VERBOSE + msg_logger( DIE, LOG_ERR, bb_msg_bad_config, msg , line); +#else + exit(EXIT_FAILURE); +#endif +} /* End Function process_config_line */ + +static int do_servicing (int fd, unsigned long event_mask) +/* [SUMMARY] Service devfs changes until a signal is received. + The open control file. + The event mask. + [RETURNS] TRUE if SIGHUP was caught, else FALSE. +*/ +{ + ssize_t bytes; + struct devfsd_notify_struct info; + unsigned long tmp_event_mask; + +#ifdef CONFIG_DEBUG + msg_logger( NO_DIE, LOG_INFO, "do_servicing()\n"); +#endif + /* Tell devfs what events we care about */ + tmp_event_mask = event_mask; + do_ioctl(DIE, fd, DEVFSDIOC_SET_EVENT_MASK, tmp_event_mask); + while (!caught_signal) + { + errno = 0; + bytes = read (fd, (char *) &info, sizeof info); + if (caught_signal) + break; /* Must test for this first */ + if (errno == EINTR) + continue; /* Yes, the order is important */ + if (bytes < 1) + break; + service_name (&info); + } + if (caught_signal) + { + int c_sighup = caught_sighup; + + caught_signal = FALSE; + caught_sighup = FALSE; + return (c_sighup); + } +#ifdef CONFIG_DEVFSD_VERBOSE + msg_logger( NO_DIE, LOG_ERR, "read error on control file: %m\n"); +#endif + /* This is to shut up a compiler warning */ + exit(EXIT_FAILURE); +} /* End Function do_servicing */ + +static void service_name (const struct devfsd_notify_struct *info) +/* [SUMMARY] Service a single devfs change. + The devfs change. + [RETURNS] Nothing. +*/ +{ + unsigned int n; + regmatch_t mbuf[MAX_SUBEXPR]; + struct config_entry_struct *entry; + +#ifdef CONFIG_DEBUG + msg_logger( NO_DIE, LOG_INFO, "service_name()\n"); + if (info->overrun_count > 0) + msg_logger( NO_DIE, LOG_ERR, "lost %u events\n", info->overrun_count); +#endif + + /* Discard lookups on "/dev/log" and "/dev/initctl" */ + if( info->type == DEVFSD_NOTIFY_LOOKUP && + ((info->devname[0]=='l' && info->devname[1]=='o' && + info->devname[2]=='g' && !info->devname[3]) || + ( info->devname[0]=='i' && info->devname[1]=='n' && + info->devname[2]=='i' && info->devname[3]=='t' && + info->devname[4]=='c' && info->devname[5]=='t' && + info->devname[6]=='l' && !info->devname[7]))) + return; + for (entry = first_config; entry != NULL; entry = entry->next) + { + /* First check if action matches the type, then check if name matches */ + if (info->type != entry->action.when || regexec (&entry->preg, info->devname, MAX_SUBEXPR, mbuf, 0) != 0 ) + continue; + for (n = 0; (n < MAX_SUBEXPR) && (mbuf[n].rm_so != -1); ++n) + /* VOID */; +#ifdef CONFIG_DEBUG + msg_logger( NO_DIE, LOG_INFO, "service_name(): action.what %d\n", entry->action.what); +#endif + switch (entry->action.what) + { + case AC_PERMISSIONS: + action_permissions (info, entry); + break; +#ifdef CONFIG_DEVFSD_MODLOAD + case AC_MODLOAD: + action_modload (info, entry); + break; +#endif + case AC_EXECUTE: + action_execute (info, entry, mbuf, n); + break; + case AC_COPY: + action_copy (info, entry, mbuf, n); + break; + case AC_IGNORE: + return; + /*break;*/ + case AC_MKOLDCOMPAT: + case AC_MKNEWCOMPAT: + case AC_RMOLDCOMPAT: + case AC_RMNEWCOMPAT: + action_compat (info, entry->action.what); + break; + default: +#ifdef CONFIG_DEVFSD_VERBOSE + msg_logger( DIE, LOG_ERR, "Unknown action\n"); +#else + exit(EXIT_FAILURE); +#endif + /*break;*/ + } + } +} /* End Function service_name */ + +static void action_permissions (const struct devfsd_notify_struct *info, + const struct config_entry_struct *entry) +/* [SUMMARY] Update permissions for a device entry. + The devfs change. + The config file entry. + [RETURNS] Nothing. +*/ +{ + struct stat statbuf; + +#ifdef CONFIG_DEBUG + msg_logger( NO_DIE, LOG_INFO, "action_permission()\n"); +#endif + + if ( stat (info->devname, &statbuf) != 0 || + chmod (info->devname,(statbuf.st_mode & S_IFMT) | (entry->u.permissions.mode & ~S_IFMT)) != 0 || + chown (info->devname, entry->u.permissions.uid, entry->u.permissions.gid) != 0) + { +#ifdef CONFIG_DEVFSD_VERBOSE + msg_logger( NO_DIE, LOG_ERR, "chmod() or chown(): %s: %m\n",info->devname); +#endif + return; + } + +} /* End Function action_permissions */ + +#ifdef CONFIG_DEVFSD_MODLOAD +static void action_modload (const struct devfsd_notify_struct *info, + const struct config_entry_struct *entry) +/* [SUMMARY] Load a module. + The devfs change. + The config file entry. + [RETURNS] Nothing. +*/ +{ + char *argv[6]; + char device[STRING_LENGTH]; + + argv[0] = MODPROBE; + argv[1] = MODPROBE_SWITCH_1; /* "-k" */ + argv[2] = MODPROBE_SWITCH_2; /* "-C" */ + argv[3] = CONFIG_MODULES_DEVFS; + argv[4] = device; + argv[5] = NULL; + + snprintf (device, sizeof (device), "/dev/%s", info->devname); + #ifdef CONFIG_DEBUG + msg_logger( NO_DIE, LOG_INFO, "action_modload():%s %s %s %s %s\n",argv[0],argv[1],argv[2],argv[3],argv[4]); + #endif + fork_and_execute(DIE, argv[0], argv); +} /* End Function action_modload */ +#endif + +static void action_execute (const struct devfsd_notify_struct *info, + const struct config_entry_struct *entry, + const regmatch_t *regexpr, unsigned int numexpr) +/* [SUMMARY] Execute a programme. + The devfs change. + The config file entry. + The number of subexpression (start, end) offsets within the + device name. + The number of elements within <>. + [RETURNS] Nothing. +*/ +{ + unsigned int count; + struct get_variable_info gv_info; + char *argv[MAX_ARGS + 1]; + char largv[MAX_ARGS + 1][STRING_LENGTH]; + +#ifdef CONFIG_DEBUG + int i; + char buff[512]; +#endif + + gv_info.info = info; + gv_info.devname = info->devname; + snprintf (gv_info.devpath, sizeof (gv_info.devpath), "%s/%s", mount_point, info->devname); + for (count = 0; entry->u.execute.argv[count] != NULL; ++count) + { + expand_expression (largv[count], STRING_LENGTH, + entry->u.execute.argv[count], + get_variable, &gv_info, + gv_info.devname, regexpr, numexpr ); + argv[count] = largv[count]; + } + argv[count] = NULL; + +#ifdef CONFIG_DEBUG + buff[0]='\0'; + for(i=0;argv[i]!=NULL;i++) /* argv[i] < MAX_ARGS + 1 */ + { + strcat(buff," "); + if( (strlen(buff)+ 1 + strlen(argv[i])) >= 512) + break; + strcat(buff,argv[i]); + } + strcat(buff,"\n"); + msg_logger( NO_DIE, LOG_INFO, "action_execute(): %s",buff); +#endif + + fork_and_execute(NO_DIE, argv[0], argv); +} /* End Function action_execute */ + + +static void action_copy (const struct devfsd_notify_struct *info, + const struct config_entry_struct *entry, + const regmatch_t *regexpr, unsigned int numexpr) +/* [SUMMARY] Copy permissions. + The devfs change. + The config file entry. + This list of subexpression (start, end) offsets within the + device name. + The number of elements in <>. + [RETURNS] Nothing. +*/ +{ + mode_t new_mode; + struct get_variable_info gv_info; + struct stat source_stat, dest_stat; + char source[STRING_LENGTH], destination[STRING_LENGTH]; + dest_stat.st_mode = 0; + +#ifdef CONFIG_DEBUG + msg_logger( NO_DIE, LOG_INFO, "action_copy()\n"); +#endif + + if ( (info->type == DEVFSD_NOTIFY_CHANGE) && S_ISLNK (info->mode) ) + return; + gv_info.info = info; + gv_info.devname = info->devname; + + snprintf (gv_info.devpath, sizeof (gv_info.devpath), "%s/%s", mount_point, info->devname); + expand_expression (source, STRING_LENGTH, entry->u.copy.source, + get_variable, &gv_info, gv_info.devname, + regexpr, numexpr); + + expand_expression (destination, STRING_LENGTH, entry->u.copy.destination, + get_variable, &gv_info, gv_info.devname, + regexpr, numexpr); + + if ( !make_dir_tree (destination) || lstat (source, &source_stat) != 0) + return; + lstat (destination, &dest_stat); + new_mode = source_stat.st_mode & ~S_ISVTX; + if (info->type == DEVFSD_NOTIFY_CREATE) + new_mode |= S_ISVTX; + else if ( (info->type == DEVFSD_NOTIFY_CHANGE) && (dest_stat.st_mode & S_ISVTX) ) + new_mode |= S_ISVTX; +#ifdef CONFIG_DEBUG + if ( !copy_inode (destination, &dest_stat, new_mode, source, &source_stat) && (errno != EEXIST)) + msg_logger( NO_DIE, LOG_ERR, "copy_inode(): %s to %s: %m\n", source, destination); +#else + copy_inode (destination, &dest_stat, new_mode, source, &source_stat); +#endif + return; +} /* End Function action_copy */ + +static void action_compat (const struct devfsd_notify_struct *info, unsigned int action) +/* [SUMMARY] Process a compatibility request. + The devfs change. + The action to take. + [RETURNS] Nothing. +*/ +{ + const char *compat_name = NULL; + const char *dest_name = info->devname; + char *ptr=NULL; + char compat_buf[STRING_LENGTH], dest_buf[STRING_LENGTH]; + int mode, host, bus, target, lun; + unsigned int i; + char rewind_; + /* 1 to 5 "scsi/" , 6 to 9 "ide/host" */ + const char *fmt[] = { NULL , + "sg/c%db%dt%du%d", /* scsi/generic */ + "sd/c%db%dt%du%d", /* scsi/disc */ + "sr/c%db%dt%du%d", /* scsi/cd */ + "sd/c%db%dt%du%dp%d", /* scsi/part */ + "st/c%db%dt%du%dm%d%c", /* scsi/mt */ + "ide/hd/c%db%dt%du%d", /* ide/host/disc */ + "ide/cd/c%db%dt%du%d", /* ide/host/cd */ + "ide/hd/c%db%dt%du%dp%d", /* ide/host/part */ + "ide/mt/c%db%dt%du%d%s", /* ide/host/mt */ + NULL }; + + /* First construct compatibility name */ + switch (action) + { + case AC_MKOLDCOMPAT: + case AC_RMOLDCOMPAT: + compat_name = get_old_name (info->devname, info->namelen, compat_buf, info->major, info->minor); + break; + case AC_MKNEWCOMPAT: + case AC_RMNEWCOMPAT: + ptr = strrchr (info->devname, '/') + 1; + i=scan_dev_name(info->devname, info->namelen, ptr); + +#ifdef CONFIG_DEBUG + msg_logger( NO_DIE, LOG_INFO, "action_compat(): scan_dev_name() returned %d\n", i); +#endif + + /* nothing found */ + if(i==0 || i > 9) + return; + + sscanf (info->devname +((i<6)?5:4), "host%d/bus%d/target%d/lun%d/", &host, &bus, &target, &lun); + snprintf (dest_buf, sizeof (dest_buf), "../%s", info->devname + ((i>5)?4:0)); + dest_name = dest_buf; + compat_name = compat_buf; + + + /* 1 == scsi/generic 2 == scsi/disc 3 == scsi/cd 6 == ide/host/disc 7 == ide/host/cd */ + if( i == 1 || i == 2 || i == 3 || i == 6 || i ==7 ) + sprintf ( compat_buf, fmt[i], host, bus, target, lun); + + /* 4 == scsi/part 8 == ide/host/part */ + if( i == 4 || i == 8) + sprintf ( compat_buf, fmt[i], host, bus, target, lun, atoi (ptr + 4) ); + + /* 5 == scsi/mt */ + if( i == 5) + { + rewind_ = info->devname[info->namelen - 1]; + if (rewind_ != 'n') + rewind_ = '\0'; + mode=0; + if(ptr[2] == 'l' /*108*/ || ptr[2] == 'm'/*109*/) + mode = ptr[2] - 107; /* 1 or 2 */ + if(ptr[2] == 'a') + mode = 3; + sprintf (compat_buf, fmt [i], host, bus, target, lun, mode, rewind_); + } + + /* 9 == ide/host/mt */ + if( i == 9 ) + snprintf (compat_buf, sizeof (compat_buf), fmt[i], host, bus, target, lun, ptr + 2); + /* esac */ + } /* switch(action) */ + + if(compat_name == NULL ) + return; + +#ifdef CONFIG_DEBUG + msg_logger( NO_DIE, LOG_INFO, "action_compat(): %s\n", compat_name); +#endif + + /* Now decide what to do with it */ + switch (action) + { + case AC_MKOLDCOMPAT: + case AC_MKNEWCOMPAT: + mksymlink (dest_name, compat_name); + break; + case AC_RMOLDCOMPAT: + case AC_RMNEWCOMPAT: +#ifdef CONFIG_DEBUG + if (unlink (compat_name) != 0) + msg_logger( NO_DIE, LOG_ERR, "unlink(): %s: %m\n", compat_name); +#else + unlink (compat_name); +#endif + break; + /*esac*/ + } /* switch(action) */ +} /* End Function action_compat */ + +static void restore(char *spath, struct stat source_stat, int rootlen) +{ + char dpath[STRING_LENGTH]; + struct stat dest_stat; + +#ifdef CONFIG_DEBUG + msg_logger( NO_DIE, LOG_INFO, "restore()\n"); +#endif + + dest_stat.st_mode = 0; + snprintf (dpath, sizeof dpath, "%s%s", mount_point, spath + rootlen); + lstat (dpath, &dest_stat); + + if ( S_ISLNK (source_stat.st_mode) || (source_stat.st_mode & S_ISVTX) ) + copy_inode (dpath, &dest_stat, (source_stat.st_mode & ~S_ISVTX) , spath, &source_stat); + + if ( S_ISDIR (source_stat.st_mode) ) + dir_operation(RESTORE, spath, rootlen,NULL); +} + + +static int copy_inode (const char *destpath, const struct stat *dest_stat, + mode_t new_mode, + const char *sourcepath, const struct stat *source_stat) +/* [SUMMARY] Copy an inode. + The destination path. An existing inode may be deleted. + The destination stat(2) information. + The desired new mode for the destination. + The source path. + The source stat(2) information. + [RETURNS] TRUE on success, else FALSE. +*/ +{ + int source_len, dest_len; + char source_link[STRING_LENGTH], dest_link[STRING_LENGTH]; + int fd, val; + struct sockaddr_un un_addr; + char symlink_val[STRING_LENGTH]; + +#ifdef CONFIG_DEBUG + msg_logger( NO_DIE, LOG_INFO, "copy_inode()\n"); +#endif + + if ( (source_stat->st_mode & S_IFMT) == (dest_stat->st_mode & S_IFMT) ) + { + /* Same type */ + if ( S_ISLNK (source_stat->st_mode) ) + { + if (( source_len = readlink (sourcepath, source_link, STRING_LENGTH - 1) ) < 0 || + ( dest_len = readlink (destpath , dest_link , STRING_LENGTH - 1) ) < 0 ) + return (FALSE); + source_link[source_len] = '\0'; + dest_link[dest_len] = '\0'; + if ( (source_len != dest_len) || (strcmp (source_link, dest_link) != 0) ) + { + unlink (destpath); + symlink (source_link, destpath); + } + return (TRUE); + } /* Else not a symlink */ + chmod (destpath, new_mode & ~S_IFMT); + chown (destpath, source_stat->st_uid, source_stat->st_gid); + return (TRUE); + } + /* Different types: unlink and create */ + unlink (destpath); + switch (source_stat->st_mode & S_IFMT) + { + case S_IFSOCK: + if ( ( fd = socket (AF_UNIX, SOCK_STREAM, 0) ) < 0 ) + break; + un_addr.sun_family = AF_UNIX; + snprintf (un_addr.sun_path, sizeof (un_addr.sun_path), "%s", destpath); + val = bind (fd, (struct sockaddr *) &un_addr, (int) sizeof un_addr); + close (fd); + if (val != 0 || chmod (destpath, new_mode & ~S_IFMT) != 0) + break; + goto do_chown; + case S_IFLNK: + if ( ( val = readlink (sourcepath, symlink_val, STRING_LENGTH - 1) ) < 0 ) + break; + symlink_val[val] = '\0'; + if (symlink (symlink_val, destpath) == 0) + return (TRUE); + break; + case S_IFREG: + if ( ( fd = open (destpath, O_RDONLY | O_CREAT, new_mode & ~S_IFMT) ) < 0 ) + break; + close (fd); + if (chmod (destpath, new_mode & ~S_IFMT) != 0) + break; + goto do_chown; + case S_IFBLK: + case S_IFCHR: + case S_IFIFO: + if (mknod (destpath, new_mode, source_stat->st_rdev) != 0) + break; + goto do_chown; + case S_IFDIR: + if (mkdir (destpath, new_mode & ~S_IFMT) != 0) + break; +do_chown: + if (chown (destpath, source_stat->st_uid, source_stat->st_gid) == 0) + return (TRUE); + /*break;*/ + } + return (FALSE); +} /* End Function copy_inode */ + +static void free_config () +/* [SUMMARY] Free the configuration information. + [RETURNS] Nothing. +*/ +{ + struct config_entry_struct *c_entry; + void *next; + +#ifdef CONFIG_DEBUG + msg_logger( NO_DIE, LOG_INFO, "free_config()\n"); +#endif + + for (c_entry = first_config; c_entry != NULL; c_entry = next) + { + unsigned int count; + + next = c_entry->next; + regfree (&c_entry->preg); + if (c_entry->action.what == AC_EXECUTE) + { + for (count = 0; count < MAX_ARGS; ++count) + { + if (c_entry->u.execute.argv[count] == NULL) + break; + free (c_entry->u.execute.argv[count]); + } + } + free (c_entry); + } + first_config = NULL; + last_config = NULL; +} /* End Function free_config */ + +static int get_uid_gid (int flag, const char *string) +/* [SUMMARY] Convert a string to a UID or GID value. + "UID" or "GID". + The string. + [RETURNS] The UID or GID value. +*/ +{ + struct passwd *pw_ent; + struct group *grp_ent; +#ifdef CONFIG_DEVFSD_VERBOSE + char * msg="user"; +#endif + +#ifdef CONFIG_DEBUG + msg_logger( NO_DIE, LOG_INFO, "get_uid_gid()\n"); + + + if(flag != UID && flag != GID ) + msg_logger( DIE, LOG_ERR,"get_uid_gid(): flag != UID && flag != GID\n"); +#endif + + if ( isdigit (string[0]) || ( (string[0] == '-') && isdigit (string[1]) ) ) + return atoi (string); + + if ( flag == UID && ( pw_ent = getpwnam (string) ) != NULL ) + return (pw_ent->pw_uid); + + if ( flag == GID && ( grp_ent = getgrnam (string) ) != NULL ) + return (grp_ent->gr_gid); +#ifdef CONFIG_DEVFSD_VERBOSE + else + msg="group"; + + msg_logger( NO_DIE, LOG_ERR,"unknown %s: %s, defaulting to %cID=0\n", msg, string, msg[0] - 32); +#endif + return (0); +}/* End Function get_uid_gid */ + +static mode_t get_mode (const char *string) +/* [SUMMARY] Convert a string to a mode value. + The string. + [RETURNS] The mode value. +*/ +{ + mode_t mode; + int i; +#ifdef CONFIG_DEBUG + msg_logger( NO_DIE, LOG_INFO, "get_mode()\n"); +#endif + + if ( isdigit (string[0]) ) + return strtoul (string, NULL, 8); + if (strlen (string) != 9) +#ifdef CONFIG_DEVFSD_VERBOSE + msg_logger( DIE, LOG_ERR, "bad mode: %s\n", string); +#else + exit(EXIT_FAILURE); +#endif + mode = 0; + i= S_IRUSR; + while(i>0) + { + if(string[0]=='r'||string[0]=='w'||string[0]=='x') + mode+=i; + i=i/2; + string++; + } + return (mode); +} /* End Function get_mode */ + +static void signal_handler (int sig) +{ +#ifdef CONFIG_DEBUG + msg_logger( NO_DIE, LOG_INFO, "signal_handler()\n"); +#endif + + caught_signal = TRUE; + if (sig == SIGHUP) + caught_sighup = TRUE; +#ifdef CONFIG_DEVFSD_VERBOSE + msg_logger( NO_DIE, LOG_INFO, "Caught %s\n",(sig == SIGHUP)?"SIGHUP" : "SIGUSR1"); +#endif +} /* End Function signal_handler */ + +static const char *get_variable (const char *variable, void *info) +{ + struct get_variable_info *gv_info = info; + static char hostname[STRING_LENGTH], sbuf[STRING_LENGTH]; + const char *field_names[] = { "hostname", "mntpt", "devpath", "devname", + "uid", "gid", "mode", hostname, mount_point, + gv_info->devpath, gv_info->devname, 0 }; + short int i; +#ifdef CONFIG_DEBUG + msg_logger( NO_DIE, LOG_INFO, "get_variable()\n"); +#endif + + if (gethostname (hostname, STRING_LENGTH - 1) != 0) +#ifdef CONFIG_DEVFSD_VERBOSE + msg_logger( DIE, LOG_ERR, "gethostname(): %m\n"); +#else + exit(EXIT_FAILURE); +#endif + /* Here on error we should do exit(RV_SYS_ERROR), instead we do exit(EXIT_FAILURE) */ + hostname[STRING_LENGTH - 1] = '\0'; + + /* compare_string_array returns i>=0 */ + i=compare_string_array(field_names, variable); + + if ( i > 6 && (i > 1 && gv_info == NULL)) + return (NULL); + if( i >= 0 || i <= 3) + { +#ifdef CONFIG_DEBUG + msg_logger( NO_DIE, LOG_INFO, "get_variable(): i=%d %s\n",i ,field_names[i+7]); +#endif + return(field_names[i+7]); + } + + if(i == 4 ) + sprintf (sbuf, "%u", gv_info->info->uid); + else if(i == 5) + sprintf (sbuf, "%u", gv_info->info->gid); + else if(i == 6) + sprintf (sbuf, "%o", gv_info->info->mode); +#ifdef CONFIG_DEBUG + msg_logger( NO_DIE, LOG_INFO, "get_variable(): %s\n", sbuf); +#endif + return (sbuf); +} /* End Function get_variable */ + +static void service(struct stat statbuf, char *path) +{ + struct devfsd_notify_struct info; + +#ifdef CONFIG_DEBUG + msg_logger( NO_DIE, LOG_INFO, "service()\n"); +#endif + + memset (&info, 0, sizeof info); + info.type = DEVFSD_NOTIFY_REGISTERED; + info.mode = statbuf.st_mode; + info.major = major (statbuf.st_rdev); + info.minor = minor (statbuf.st_rdev); + info.uid = statbuf.st_uid; + info.gid = statbuf.st_gid; + snprintf (info.devname, sizeof (info.devname), "%s", path + strlen (mount_point) + 1); + info.namelen = strlen (info.devname); + service_name (&info); + if ( S_ISDIR (statbuf.st_mode) ) + dir_operation(SERVICE,path,0,NULL); +} + +static void dir_operation(int type, const char * dir_name, int var, unsigned long *event_mask) +/* [SUMMARY] Scan a directory tree and generate register events on leaf nodes. + To choose which function to perform + The directory pointer. This is closed upon completion. + The name of the directory. + string length parameter. + [RETURNS] Nothing. +*/ +{ + struct stat statbuf; + DIR *dp; + struct dirent *de; + char path[STRING_LENGTH]; + + +#ifdef CONFIG_DEBUG + msg_logger( NO_DIE, LOG_INFO, "dir_operation()\n"); +#endif + + if((dp = opendir( dir_name))==NULL) + { +#ifdef CONFIG_DEBUG + msg_logger( NO_DIE, LOG_ERR, "opendir(): %s: %m\n", dir_name); +#endif + return; + } + + while ( (de = readdir (dp) ) != NULL ) + { + + if(de->d_name && *de->d_name == '.' && (!de->d_name[1] || (de->d_name[1] == '.' && !de->d_name[2]))) + continue; + snprintf (path, sizeof (path), "%s/%s", dir_name, de->d_name); +#ifdef CONFIG_DEBUG + msg_logger( NO_DIE, LOG_ERR, "dir_operation(): %s\n", path); +#endif + + if (lstat (path, &statbuf) != 0) + { +#ifdef CONFIG_DEBUG + msg_logger( NO_DIE, LOG_ERR, "%s: %m\n", path); +#endif + continue; + } + switch(type) + { + case SERVICE: + service(statbuf,path); + break; + case RESTORE: + restore(path, statbuf, var); + break; + case READ_CONFIG: + read_config_file (path, var, event_mask); + break; + } + } + closedir (dp); +} /* End Function do_scan_and_service */ + +static int mksymlink (const char *oldpath, const char *newpath) +/* [SUMMARY] Create a symlink, creating intervening directories as required. + The string contained in the symlink. + The name of the new symlink. + [RETURNS] 0 on success, else -1. +*/ +{ +#ifdef CONFIG_DEBUG + msg_logger( NO_DIE, LOG_INFO, "mksymlink()\n", newpath); +#endif + + + if ( !make_dir_tree (newpath) ) + return (-1); + + if (symlink (oldpath, newpath) != 0) + { + if (errno != EEXIST) + { +#ifdef CONFIG_DEBUG + msg_logger( NO_DIE, LOG_ERR, "mksymlink(): %s to %s: %m\n", oldpath, newpath); +#endif + return (-1); + } + } + return (0); +} /* End Function mksymlink */ + + +static int make_dir_tree (const char *path) +/* [SUMMARY] Creating intervening directories for a path as required. + The full pathname (including the leaf node). + [RETURNS] TRUE on success, else FALSE. +*/ +{ +#ifdef CONFIG_DEBUG + msg_logger( NO_DIE, LOG_INFO, "make_dir_tree()\n"); +#endif + if (bb_make_directory( dirname((char *)path), -1, FILEUTILS_RECUR )==-1) + { +#ifdef CONFIG_DEBUG + msg_logger( NO_DIE, LOG_ERR, "make_dir_tree(): %s: %m\n", path); +#endif + return (FALSE); + } + return(TRUE); +} /* End Function make_dir_tree */ + +static int expand_expression(char *output, unsigned int outsize, + const char *input, + const char *(*get_variable_func)(const char *variable, void *info), + void *info, + const char *devname, + const regmatch_t *ex, unsigned int numexp) +/* [SUMMARY] Expand environment variables and regular subexpressions in string. + The output expanded expression is written here. + The size of the output buffer. + The input expression. This may equal <>. + A function which will be used to get variable values. If + this returns NULL, the environment is searched instead. If this is NULL, + only the environment is searched. + An arbitrary pointer passed to <>. + Device name; specifically, this is the string that contains all + of the regular subexpressions. + Array of start / end offsets into info->devname for each subexpression + Number of regular subexpressions found in <>. + [RETURNS] TRUE on success, else FALSE. +*/ +{ + char temp[STRING_LENGTH]; + +#ifdef CONFIG_DEBUG + msg_logger( NO_DIE, LOG_INFO, "expand_expression()\n"); +#endif + + if ( !st_expr_expand (temp, STRING_LENGTH, input, get_variable_func, info) ) + return (FALSE); + expand_regexp (output, outsize, temp, devname, ex, numexp); + return (TRUE); +} /* End Function expand_expression */ + +static void expand_regexp (char *output, size_t outsize, const char *input, + const char *devname, + const regmatch_t *ex, unsigned int numex ) +/* [SUMMARY] Expand all occurrences of the regular subexpressions \0 to \9. + The output expanded expression is written here. + The size of the output buffer. + The input expression. This may NOT equal <>, because + supporting that would require yet another string-copy. However, it's not + hard to write a simple wrapper function to add this functionality for those + few cases that need it. + Device name; specifically, this is the string that contains all + of the regular subexpressions. + An array of start and end offsets into <>, one for each + subexpression + Number of subexpressions in the offset-array <>. + [RETURNS] Nothing. +*/ +{ + const char last_exp = '0' - 1 + numex; + int c = -1; + +#ifdef CONFIG_DEBUG + msg_logger( NO_DIE, LOG_INFO, "expand_regexp()\n"); +#endif + + /* Guarantee NULL termination by writing an explicit '\0' character into + the very last byte */ + if (outsize) + output[--outsize] = '\0'; + /* Copy the input string into the output buffer, replacing '\\' with '\' + and '\0' .. '\9' with subexpressions 0 .. 9, if they exist. Other \x + codes are deleted */ + while ( (c != '\0') && (outsize != 0) ) + { + c = *input; + ++input; + if (c == '\\') + { + c = *input; + ++input; + if (c != '\\') + { + if ((c >= '0') && (c <= last_exp)) + { + const regmatch_t *subexp = ex + (c - '0'); + unsigned int sublen = subexp->rm_eo - subexp->rm_so; + + /* Range checking */ + if (sublen > outsize) + sublen = outsize; + strncpy (output, devname + subexp->rm_so, sublen); + output += sublen; + outsize -= sublen; + } + continue; + } + } + *output = c; + ++output; + --outsize; + } /* while */ +} /* End Function expand_regexp */ + + +/* from compat_name.c */ + +struct translate_struct +{ + char *match; /* The string to match to (up to length) */ + char *format; /* Format of output, "%s" takes data past match string, + NULL is effectively "%s" (just more efficient) */ +}; + +static struct translate_struct translate_table[] = +{ + {"sound/", NULL}, + {"printers/", "lp%s"}, + {"v4l/", NULL}, + {"parports/", "parport%s"}, + {"fb/", "fb%s"}, + {"netlink/", NULL}, + {"loop/", "loop%s"}, + {"floppy/", "fd%s"}, + {"rd/", "ram%s"}, + {"md/", "md%s"}, /* Meta-devices */ + {"vc/", "tty%s"}, + {"misc/", NULL}, + {"isdn/", NULL}, + {"pg/", "pg%s"}, /* Parallel port generic ATAPI interface*/ + {"i2c/", "i2c-%s"}, + {"staliomem/", "staliomem%s"}, /* Stallion serial driver control */ + {"tts/E", "ttyE%s"}, /* Stallion serial driver */ + {"cua/E", "cue%s"}, /* Stallion serial driver callout */ + {"tts/R", "ttyR%s"}, /* Rocketport serial driver */ + {"cua/R", "cur%s"}, /* Rocketport serial driver callout */ + {"ip2/", "ip2%s"}, /* Computone serial driver control */ + {"tts/F", "ttyF%s"}, /* Computone serial driver */ + {"cua/F", "cuf%s"}, /* Computone serial driver callout */ + {"tts/C", "ttyC%s"}, /* Cyclades serial driver */ + {"cua/C", "cub%s"}, /* Cyclades serial driver callout */ + {"tts/", "ttyS%s"}, /* Generic serial: must be after others */ + {"cua/", "cua%s"}, /* Generic serial: must be after others */ + {"input/js", "js%s"}, /* Joystick driver */ + {NULL, NULL} +}; + +const char *get_old_name (const char *devname, unsigned int namelen, + char *buffer, unsigned int major, unsigned int minor) +/* [SUMMARY] Translate a kernel-supplied name into an old name. + The device name provided by the kernel. + The length of the name. + A buffer that may be used. This should be at least 128 bytes long. + The major number for the device. + The minor number for the device. + [RETURNS] A pointer to the old name if known, else NULL. +*/ +{ + const char *compat_name = NULL; + char *ptr; + struct translate_struct *trans; + unsigned int i; + char mode; + int indexx; + const char *pty1; + const char *pty2; + size_t len; + /* 1 to 5 "scsi/" , 6 to 9 "ide/host", 10 sbp/, 11 vcc/, 12 pty/ */ + const char *fmt[] = { NULL , + "sg%u", /* scsi/generic */ + NULL, /* scsi/disc */ + "sr%u", /* scsi/cd */ + NULL, /* scsi/part */ + "nst%u%c", /* scsi/mt */ + "hd%c" , /* ide/host/disc */ + "hd%c" , /* ide/host/cd */ + "hd%c%s", /* ide/host/part */ + "%sht%d", /* ide/host/mt */ + "sbpcd%u", /* sbp/ */ + "vcs%s", /* vcc/ */ + "%cty%c%c", /* pty/ */ + NULL }; + +#ifdef CONFIG_DEBUG + msg_logger( NO_DIE, LOG_INFO, "get_old_name()\n"); +#endif + + for (trans = translate_table; trans->match != NULL; ++trans) + { + len = strlen (trans->match); + + if (strncmp (devname, trans->match, len) == 0) + { + if (trans->format == NULL) + return (devname + len); + sprintf (buffer, trans->format, devname + len); + return (buffer); + } + } + + ptr = (strrchr (devname, '/') + 1); + i = scan_dev_name(devname, namelen, ptr); + + if( i > 0 && i < 13) + compat_name = buffer; + else + return NULL; + +#ifdef CONFIG_DEBUG + msg_logger( NO_DIE, LOG_INFO, "get_old_name(): scan_dev_name() returned %d\n", i); +#endif + + /* 1 == scsi/generic, 3 == scsi/cd, 10 == sbp/ */ + if( i == 1 || i == 3 || i == 10 ) + sprintf (buffer, fmt[i], minor); + + /* 2 ==scsi/disc, 4 == scsi/part */ + if( i == 2 || i == 4) + compat_name = write_old_sd_name (buffer, major, minor,((i == 2)?"":(ptr + 4))); + + /* 5 == scsi/mt */ + if( i == 5) + { + mode = ptr[2]; + if (mode == 'n') + mode = '\0'; + sprintf (buffer, fmt[i], minor & 0x1f, mode); + if (devname[namelen - 1] != 'n') + ++compat_name; + } + /* 6 == ide/host/disc, 7 == ide/host/cd, 8 == ide/host/part */ + if( i == 6 || i == 7 || i == 8 ) + sprintf (buffer, fmt[i] , get_old_ide_name (major, minor), ptr + 4); /* last arg should be ignored for i == 6 or i== 7 */ + + /* 9 == ide/host/mt */ + if( i == 9 ) + sprintf (buffer, fmt[i], ptr + 2, minor & 0x7f); + + /* 11 == vcc/ */ + if( i == 11 ) + { + sprintf (buffer, fmt[i], devname + 4); + if (buffer[3] == '0') + buffer[3] = '\0'; + } + /* 12 == pty/ */ + if( i == 12 ) + { + pty1 = "pqrstuvwxyzabcde"; + pty2 = "0123456789abcdef"; + indexx = atoi (devname + 5); + sprintf (buffer, fmt[i], (devname[4] == 'm') ? 'p' : 't', pty1[indexx >> 4], pty2[indexx & 0x0f]); + } +#ifdef CONFIG_DEBUG + if(compat_name!=NULL) + msg_logger( NO_DIE, LOG_INFO, "get_old_name(): compat_name %s\n", compat_name); +#endif + return (compat_name); +} /* End Function get_old_name */ + +static char get_old_ide_name (unsigned int major, unsigned int minor) +/* [SUMMARY] Get the old IDE name for a device. + The major number for the device. + The minor number for the device. + [RETURNS] The drive letter. +*/ +{ + char letter='y'; /* 121 */ + char c='a'; /* 97 */ + int i=IDE0_MAJOR; + +#ifdef CONFIG_DEBUG + msg_logger( NO_DIE, LOG_INFO, "get_old_ide_name()\n"); +#endif + + /* I hope it works like the previous code as it saves a few bytes. Tito ;P */ + do { + if( i==IDE0_MAJOR || i==IDE1_MAJOR || i==IDE2_MAJOR || + i==IDE3_MAJOR || i==IDE4_MAJOR || i==IDE5_MAJOR || + i==IDE6_MAJOR || i==IDE7_MAJOR || i==IDE8_MAJOR || + i==IDE9_MAJOR ) + { + if(i==major) + { + letter=c; + break; + } + c+=2; + } + i++; + } while(i<=IDE9_MAJOR); + + if (minor > 63) + ++letter; + return (letter); +} /* End Function get_old_ide_name */ + +static char *write_old_sd_name (char *buffer, + unsigned int major, unsigned int minor, + char *part) +/* [SUMMARY] Write the old SCSI disc name to a buffer. + The buffer to write to. + The major number for the device. + The minor number for the device. + The partition string. Must be "" for a whole-disc entry. + [RETURNS] A pointer to the buffer on success, else NULL. +*/ +{ + unsigned int disc_index; + +#ifdef CONFIG_DEBUG + msg_logger( NO_DIE, LOG_INFO, "write_old_sd_name()\n"); +#endif + + if (major == 8) + { + sprintf (buffer, "sd%c%s", 'a' + (minor >> 4), part); + return (buffer); + } + if ( (major > 64) && (major < 72) ) + { + disc_index = ( (major - 64) << 4 ) + (minor >> 4); + if (disc_index < 26) + sprintf (buffer, "sd%c%s", 'a' + disc_index, part); + else + sprintf (buffer, "sd%c%c%s", 'a' + (disc_index / 26) - 1, 'a' + disc_index % 26,part); + return (buffer); + } + return (NULL); +} /* End Function write_old_sd_name */ + + +/* expression.c */ + +/*EXPERIMENTAL_FUNCTION*/ + +int st_expr_expand (char *output, unsigned int length, const char *input, + const char *(*get_variable_func) (const char *variable, + void *info), + void *info) +/* [SUMMARY] Expand an expression using Borne Shell-like unquoted rules. + The output expanded expression is written here. + The size of the output buffer. + The input expression. This may equal <>. + A function which will be used to get variable values. If + this returns NULL, the environment is searched instead. If this is NULL, + only the environment is searched. + An arbitrary pointer passed to <>. + [RETURNS] TRUE on success, else FALSE. +*/ +{ + char ch; + unsigned int len; + unsigned int out_pos = 0; + const char *env; + const char *ptr; + struct passwd *pwent; + char buffer[BUFFER_SIZE], tmp[STRING_LENGTH]; + +#ifdef CONFIG_DEBUG + msg_logger( NO_DIE, LOG_INFO, "st_expr_expand()\n"); +#endif + + if (length > BUFFER_SIZE) + length = BUFFER_SIZE; + for (; TRUE; ++input) + { + switch (ch = *input) + { + case '$': + /* Variable expansion */ + input = expand_variable (buffer, length, &out_pos, ++input, get_variable_func, info); + if (input == NULL) + return (FALSE); + break; + case '~': + /* Home directory expansion */ + ch = input[1]; + if ( isspace (ch) || (ch == '/') || (ch == '\0') ) + { + /* User's own home directory: leave separator for next time */ + if ( ( env = getenv ("HOME") ) == NULL ) + { +#ifdef CONFIG_DEVFSD_VERBOSE + msg_logger( NO_DIE, LOG_INFO, bb_msg_variable_not_found, "HOME"); +#endif + return (FALSE); + } + len = strlen (env); + if (len + out_pos >= length) + goto st_expr_expand_out; + memcpy (buffer + out_pos, env, len + 1); + out_pos += len; + continue; + } + /* Someone else's home directory */ + for (ptr = ++input; !isspace (ch) && (ch != '/') && (ch != '\0'); ch = *++ptr) + /* VOID */ ; + len = ptr - input; + if (len >= sizeof tmp) + goto st_expr_expand_out; + safe_memcpy (tmp, input, len); + input = ptr - 1; + if ( ( pwent = getpwnam (tmp) ) == NULL ) + { +#ifdef CONFIG_DEVFSD_VERBOSE + msg_logger( NO_DIE, LOG_INFO, "no pwent for: %s\n", tmp); +#endif + return (FALSE); + } + len = strlen (pwent->pw_dir); + if (len + out_pos >= length) + goto st_expr_expand_out; + memcpy (buffer + out_pos, pwent->pw_dir, len + 1); + out_pos += len; + break; + case '\0': + /* Falltrough */ + default: + if (out_pos >= length) + goto st_expr_expand_out; + buffer[out_pos++] = ch; + if (ch == '\0') + { + memcpy (output, buffer, out_pos); + return (TRUE); + } + break; + /* esac */ + } + } + return (FALSE); +st_expr_expand_out: +#ifdef CONFIG_DEVFSD_VERBOSE + msg_logger( NO_DIE, LOG_INFO, bb_msg_small_buffer); +#endif + return (FALSE); +} /* End Function st_expr_expand */ + + +/* Private functions follow */ + +static const char *expand_variable (char *buffer, unsigned int length, + unsigned int *out_pos, const char *input, + const char *(*func) (const char *variable, + void *info), + void *info) +/* [SUMMARY] Expand a variable. + The buffer to write to. + The length of the output buffer. + The current output position. This is updated. + A pointer to the input character pointer. + A function which will be used to get variable values. If this + returns NULL, the environment is searched instead. If this is NULL, only + the environment is searched. + An arbitrary pointer passed to <>. + Diagnostic messages are written here. + [RETURNS] A pointer to the end of this subexpression on success, else NULL. +*/ +{ + char ch; + int len; + unsigned int open_braces; + const char *env, *ptr; + char tmp[STRING_LENGTH]; + +#ifdef CONFIG_DEBUG + msg_logger( NO_DIE, LOG_INFO, "expand_variable()\n"); +#endif + + ch = input[0]; + if (ch == '$') + { + /* Special case for "$$": PID */ + sprintf ( tmp, "%d", (int) getpid () ); + len = strlen (tmp); + if (len + *out_pos >= length) + goto expand_variable_out; + + memcpy (buffer + *out_pos, tmp, len + 1); + out_pos += len; + return (input); + } + /* Ordinary variable expansion, possibly in braces */ + if (ch != '{') + { + /* Simple variable expansion */ + for (ptr = input; isalnum (ch) || (ch == '_') || (ch == ':');ch = *++ptr) + /* VOID */ ; + len = ptr - input; + if (len >= sizeof tmp) + goto expand_variable_out; + + safe_memcpy (tmp, input, len); + input = ptr - 1; + if ( ( env = get_variable_v2 (tmp, func, info) ) == NULL ) + { +#ifdef CONFIG_DEVFSD_VERBOSE + msg_logger( NO_DIE, LOG_INFO, bb_msg_variable_not_found, tmp); +#endif + return (NULL); + } + len = strlen (env); + if (len + *out_pos >= length) + goto expand_variable_out; + + memcpy (buffer + *out_pos, env, len + 1); + *out_pos += len; + return (input); + } + /* Variable in braces: check for ':' tricks */ + ch = *++input; + for (ptr = input; isalnum (ch) || (ch == '_'); ch = *++ptr) + /* VOID */; + if (ch == '}') + { + /* Must be simple variable expansion with "${var}" */ + len = ptr - input; + if (len >= sizeof tmp) + goto expand_variable_out; + + safe_memcpy (tmp, input, len); + ptr = expand_variable (buffer, length, out_pos, tmp, func, info ); + if (ptr == NULL) + return (NULL); + return (input + len); + } + if (ch != ':' || ptr[1] != '-' ) + { +#ifdef CONFIG_DEVFSD_VERBOSE + msg_logger( NO_DIE, LOG_INFO,"illegal char in var name\n"); +#endif + return (NULL); + } + /* It's that handy "${var:-word}" expression. Check if var is defined */ + len = ptr - input; + if (len >= sizeof tmp) + goto expand_variable_out; + + safe_memcpy (tmp, input, len); + /* Move input pointer to ':' */ + input = ptr; + /* First skip to closing brace, taking note of nested expressions */ + ptr += 2; + ch = ptr[0]; + for (open_braces = 1; open_braces > 0; ch = *++ptr) + { + switch (ch) + { + case '{': + ++open_braces; + break; + case '}': + --open_braces; + break; + case '\0': +#ifdef CONFIG_DEVFSD_VERBOSE + msg_logger( NO_DIE, LOG_INFO,"\"}\" not found in: %s\n", input); +#endif + return (NULL); + default: + break; + } + } + --ptr; + /* At this point ptr should point to closing brace of "${var:-word}" */ + if ( ( env = get_variable_v2 (tmp, func, info) ) != NULL ) + { + /* Found environment variable, so skip the input to the closing brace + and return the variable */ + input = ptr; + len = strlen (env); + if (len + *out_pos >= length) + goto expand_variable_out; + + memcpy (buffer + *out_pos, env, len + 1); + *out_pos += len; + return (input); + } + /* Environment variable was not found, so process word. Advance input + pointer to start of word in "${var:-word}" */ + input += 2; + len = ptr - input; + if (len >= sizeof tmp) + goto expand_variable_out; + + safe_memcpy (tmp, input, len); + input = ptr; + if ( !st_expr_expand (tmp, STRING_LENGTH, tmp, func, info ) ) + return (NULL); + len = strlen (tmp); + if (len + *out_pos >= length) + goto expand_variable_out; + + memcpy (buffer + *out_pos, tmp, len + 1); + *out_pos += len; + return (input); +expand_variable_out: +#ifdef CONFIG_DEVFSD_VERBOSE + msg_logger( NO_DIE, LOG_INFO, bb_msg_small_buffer); +#endif + return (NULL); +} /* End Function expand_variable */ + + +static const char *get_variable_v2 (const char *variable, + const char *(*func) (const char *variable, void *info), + void *info) +/* [SUMMARY] Get a variable from the environment or . + The variable name. + A function which will be used to get the variable. If this returns + NULL, the environment is searched instead. If this is NULL, only the + environment is searched. + [RETURNS] The value of the variable on success, else NULL. +*/ +{ + const char *value; + +#ifdef CONFIG_DEBUG + msg_logger( NO_DIE, LOG_INFO, "get_variable_v2()\n"); +#endif + + if (func != NULL) + { + value = (*func) (variable, info); + if (value != NULL) + return (value); + } + return getenv (variable); +} /* End Function get_variable */ + +/* END OF CODE */ diff --git a/busybox/miscutils/hdparm.c b/busybox/miscutils/hdparm.c new file mode 100644 index 0000000..0d2c328 --- /dev/null +++ b/busybox/miscutils/hdparm.c @@ -0,0 +1,2872 @@ +/* vi: set sw=4 ts=4: */ +/* + * hdparm implementation for busybox + * + * + * Copyright (C) [2003] by [Matteo Croce] <3297627799@wind.it> + * + * Hacked by Tito for size optimization. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA + * 02111-1307 USA + * + * + * This program is based on the source code of hdparm: see below... + * hdparm.c - Command line interface to get/set hard disk parameters + * - by Mark Lord (C) 1994-2002 -- freely distributable + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "busybox.h" +#include +#include +#include +#include + + +#if (__BYTE_ORDER == __BIG_ENDIAN) && !defined(__USE_XOPEN) +#define __USE_XOPEN +#endif + +/* device types */ +/* ------------ */ +#define NO_DEV 0xffff +#define ATA_DEV 0x0000 +#define ATAPI_DEV 0x0001 + +/* word definitions */ +/* ---------------- */ +#define GEN_CONFIG 0 /* general configuration */ +#define LCYLS 1 /* number of logical cylinders */ +#define CONFIG 2 /* specific configuration */ +#define LHEADS 3 /* number of logical heads */ +#define TRACK_BYTES 4 /* number of bytes/track (ATA-1) */ +#define SECT_BYTES 5 /* number of bytes/sector (ATA-1) */ +#define LSECTS 6 /* number of logical sectors/track */ +#define START_SERIAL 10 /* ASCII serial number */ +#define LENGTH_SERIAL 10 /* 10 words (20 bytes or characters) */ +#define BUF_TYPE 20 /* buffer type (ATA-1) */ +#define BUFFER__SIZE 21 /* buffer size (ATA-1) */ +#define RW_LONG 22 /* extra bytes in R/W LONG cmd ( < ATA-4)*/ +#define START_FW_REV 23 /* ASCII firmware revision */ +#define LENGTH_FW_REV 4 /* 4 words (8 bytes or characters) */ +#define START_MODEL 27 /* ASCII model number */ +#define LENGTH_MODEL 20 /* 20 words (40 bytes or characters) */ +#define SECTOR_XFER_MAX 47 /* r/w multiple: max sectors xfered */ +#define DWORD_IO 48 /* can do double-word IO (ATA-1 only) */ +#define CAPAB_0 49 /* capabilities */ +#define CAPAB_1 50 +#define PIO_MODE 51 /* max PIO mode supported (obsolete)*/ +#define DMA_MODE 52 /* max Singleword DMA mode supported (obs)*/ +#define WHATS_VALID 53 /* what fields are valid */ +#define LCYLS_CUR 54 /* current logical cylinders */ +#define LHEADS_CUR 55 /* current logical heads */ +#define LSECTS_CUR 56 /* current logical sectors/track */ +#define CAPACITY_LSB 57 /* current capacity in sectors */ +#define CAPACITY_MSB 58 +#define SECTOR_XFER_CUR 59 /* r/w multiple: current sectors xfered */ +#define LBA_SECTS_LSB 60 /* LBA: total number of user */ +#define LBA_SECTS_MSB 61 /* addressable sectors */ +#define SINGLE_DMA 62 /* singleword DMA modes */ +#define MULTI_DMA 63 /* multiword DMA modes */ +#define ADV_PIO_MODES 64 /* advanced PIO modes supported */ + /* multiword DMA xfer cycle time: */ +#define DMA_TIME_MIN 65 /* - minimum */ +#define DMA_TIME_NORM 66 /* - manufacturer's recommended */ + /* minimum PIO xfer cycle time: */ +#define PIO_NO_FLOW 67 /* - without flow control */ +#define PIO_FLOW 68 /* - with IORDY flow control */ +#define PKT_REL 71 /* typical #ns from PKT cmd to bus rel */ +#define SVC_NBSY 72 /* typical #ns from SERVICE cmd to !BSY */ +#define CDR_MAJOR 73 /* CD ROM: major version number */ +#define CDR_MINOR 74 /* CD ROM: minor version number */ +#define QUEUE_DEPTH 75 /* queue depth */ +#define MAJOR 80 /* major version number */ +#define MINOR 81 /* minor version number */ +#define CMDS_SUPP_0 82 /* command/feature set(s) supported */ +#define CMDS_SUPP_1 83 +#define CMDS_SUPP_2 84 +#define CMDS_EN_0 85 /* command/feature set(s) enabled */ +#define CMDS_EN_1 86 +#define CMDS_EN_2 87 +#define ULTRA_DMA 88 /* ultra DMA modes */ + /* time to complete security erase */ +#define ERASE_TIME 89 /* - ordinary */ +#define ENH_ERASE_TIME 90 /* - enhanced */ +#define ADV_PWR 91 /* current advanced power management level + in low byte, 0x40 in high byte. */ +#define PSWD_CODE 92 /* master password revision code */ +#define HWRST_RSLT 93 /* hardware reset result */ +#define ACOUSTIC 94 /* acoustic mgmt values ( >= ATA-6) */ +#define LBA_LSB 100 /* LBA: maximum. Currently only 48 */ +#define LBA_MID 101 /* bits are used, but addr 103 */ +#define LBA_48_MSB 102 /* has been reserved for LBA in */ +#define LBA_64_MSB 103 /* the future. */ +#define RM_STAT 127 /* removable media status notification feature set support */ +#define SECU_STATUS 128 /* security status */ +#define CFA_PWR_MODE 160 /* CFA power mode 1 */ +#define START_MEDIA 176 /* media serial number */ +#define LENGTH_MEDIA 20 /* 20 words (40 bytes or characters)*/ +#define START_MANUF 196 /* media manufacturer I.D. */ +#define LENGTH_MANUF 10 /* 10 words (20 bytes or characters) */ +#define INTEGRITY 255 /* integrity word */ + +/* bit definitions within the words */ +/* -------------------------------- */ + +/* many words are considered valid if bit 15 is 0 and bit 14 is 1 */ +#define VALID 0xc000 +#define VALID_VAL 0x4000 +/* many words are considered invalid if they are either all-0 or all-1 */ +#define NOVAL_0 0x0000 +#define NOVAL_1 0xffff + +/* word 0: gen_config */ +#define NOT_ATA 0x8000 +#define NOT_ATAPI 0x4000 /* (check only if bit 15 == 1) */ +#define MEDIA_REMOVABLE 0x0080 +#define DRIVE_NOT_REMOVABLE 0x0040 /* bit obsoleted in ATA 6 */ +#define INCOMPLETE 0x0004 +#define CFA_SUPPORT_VAL 0x848a /* 848a=CFA feature set support */ +#define DRQ_RESPONSE_TIME 0x0060 +#define DRQ_3MS_VAL 0x0000 +#define DRQ_INTR_VAL 0x0020 +#define DRQ_50US_VAL 0x0040 +#define PKT_SIZE_SUPPORTED 0x0003 +#define PKT_SIZE_12_VAL 0x0000 +#define PKT_SIZE_16_VAL 0x0001 +#define EQPT_TYPE 0x1f00 +#define SHIFT_EQPT 8 + +#define CDROM 0x0005 + +#ifdef CONFIG_FEATURE_HDPARM_GET_IDENTITY +static const char *pkt_str[] = { + "Direct-access device", /* word 0, bits 12-8 = 00 */ + "Sequential-access device", /* word 0, bits 12-8 = 01 */ + "Printer", /* word 0, bits 12-8 = 02 */ + "Processor", /* word 0, bits 12-8 = 03 */ + "Write-once device", /* word 0, bits 12-8 = 04 */ + "CD-ROM", /* word 0, bits 12-8 = 05 */ + "Scanner", /* word 0, bits 12-8 = 06 */ + "Optical memory", /* word 0, bits 12-8 = 07 */ + "Medium changer", /* word 0, bits 12-8 = 08 */ + "Communications device", /* word 0, bits 12-8 = 09 */ + "ACS-IT8 device", /* word 0, bits 12-8 = 0a */ + "ACS-IT8 device", /* word 0, bits 12-8 = 0b */ + "Array controller", /* word 0, bits 12-8 = 0c */ + "Enclosure services", /* word 0, bits 12-8 = 0d */ + "Reduced block command device", /* word 0, bits 12-8 = 0e */ + "Optical card reader/writer", /* word 0, bits 12-8 = 0f */ + "", /* word 0, bits 12-8 = 10 */ + "", /* word 0, bits 12-8 = 11 */ + "", /* word 0, bits 12-8 = 12 */ + "", /* word 0, bits 12-8 = 13 */ + "", /* word 0, bits 12-8 = 14 */ + "", /* word 0, bits 12-8 = 15 */ + "", /* word 0, bits 12-8 = 16 */ + "", /* word 0, bits 12-8 = 17 */ + "", /* word 0, bits 12-8 = 18 */ + "", /* word 0, bits 12-8 = 19 */ + "", /* word 0, bits 12-8 = 1a */ + "", /* word 0, bits 12-8 = 1b */ + "", /* word 0, bits 12-8 = 1c */ + "", /* word 0, bits 12-8 = 1d */ + "", /* word 0, bits 12-8 = 1e */ + "Unknown", /* word 0, bits 12-8 = 1f */ +}; +static const char *ata1_cfg_str[] = { /* word 0 in ATA-1 mode */ + "reserved", /* bit 0 */ + "hard sectored", /* bit 1 */ + "soft sectored", /* bit 2 */ + "not MFM encoded ", /* bit 3 */ + "head switch time > 15us", /* bit 4 */ + "spindle motor control option", /* bit 5 */ + "fixed drive", /* bit 6 */ + "removable drive", /* bit 7 */ + "disk xfer rate <= 5Mbs", /* bit 8 */ + "disk xfer rate > 5Mbs, <= 10Mbs", /* bit 9 */ + "disk xfer rate > 5Mbs", /* bit 10 */ + "rotational speed tol.", /* bit 11 */ + "data strobe offset option", /* bit 12 */ + "track offset option", /* bit 13 */ + "format speed tolerance gap reqd", /* bit 14 */ + "ATAPI" /* bit 14 */ +}; +#endif + +/* word 1: number of logical cylinders */ +#define LCYLS_MAX 0x3fff /* maximum allowable value */ + +/* word 2: specific configuration + * (a) require SET FEATURES to spin-up + * (b) require spin-up to fully reply to IDENTIFY DEVICE + */ +#define STBY_NID_VAL 0x37c8 /* (a) and (b) */ +#define STBY_ID_VAL 0x738c /* (a) and not (b) */ +#define PWRD_NID_VAL 0x8c73 /* not (a) and (b) */ +#define PWRD_ID_VAL 0xc837 /* not (a) and not (b) */ + +/* words 47 & 59: sector_xfer_max & sector_xfer_cur */ +#define SECTOR_XFER 0x00ff /* sectors xfered on r/w multiple cmds*/ +#define MULTIPLE_SETTING_VALID 0x0100 /* 1=multiple sector setting is valid */ + +/* word 49: capabilities 0 */ +#define STD_STBY 0x2000 /* 1=standard values supported (ATA); + 0=vendor specific values */ +#define IORDY_SUP 0x0800 /* 1=support; 0=may be supported */ +#define IORDY_OFF 0x0400 /* 1=may be disabled */ +#define LBA_SUP 0x0200 /* 1=Logical Block Address support */ +#define DMA_SUP 0x0100 /* 1=Direct Memory Access support */ +#define DMA_IL_SUP 0x8000 /* 1=interleaved DMA support (ATAPI) */ +#define CMD_Q_SUP 0x4000 /* 1=command queuing support (ATAPI) */ +#define OVLP_SUP 0x2000 /* 1=overlap operation support (ATAPI) */ +#define SWRST_REQ 0x1000 /* 1=ATA SW reset required (ATAPI, obsolete */ + +/* word 50: capabilities 1 */ +#define MIN_STANDBY_TIMER 0x0001 /* 1=device specific standby timer value minimum */ + +/* words 51 & 52: PIO & DMA cycle times */ +#define MODE 0xff00 /* the mode is in the MSBs */ + +/* word 53: whats_valid */ +#define OK_W88 0x0004 /* the ultra_dma info is valid */ +#define OK_W64_70 0x0002 /* see above for word descriptions */ +#define OK_W54_58 0x0001 /* current cyl, head, sector, cap. info valid */ + +/*word 63,88: dma_mode, ultra_dma_mode*/ +#define MODE_MAX 7 /* bit definitions force udma <=7 (when + * udma >=8 comes out it'll have to be + * defined in a new dma_mode word!) */ + +/* word 64: PIO transfer modes */ +#define PIO_SUP 0x00ff /* only bits 0 & 1 are used so far, */ +#define PIO_MODE_MAX 8 /* but all 8 bits are defined */ + +/* word 75: queue_depth */ +#define DEPTH_BITS 0x001f /* bits used for queue depth */ + +/* words 80-81: version numbers */ +/* NOVAL_0 or NOVAL_1 means device does not report version */ + +/* word 81: minor version number */ +#define MINOR_MAX 0x1C +#ifdef CONFIG_FEATURE_HDPARM_GET_IDENTITY +static const char *minor_str[] = { /* word 81 value: */ + "device does not report version", /* 0x0000 */ + "ATA-1 X3T9.2 781D prior to revision 4", /* 0x0001 */ + "ATA-1 published, ANSI X3.221-1994", /* 0x0002 */ + "ATA-1 X3T9.2 781D revision 4", /* 0x0003 */ + "ATA-2 published, ANSI X3.279-1996", /* 0x0004 */ + "ATA-2 X3T10 948D prior to revision 2k", /* 0x0005 */ + "ATA-3 X3T10 2008D revision 1", /* 0x0006 */ + "ATA-2 X3T10 948D revision 2k", /* 0x0007 */ + "ATA-3 X3T10 2008D revision 0", /* 0x0008 */ + "ATA-2 X3T10 948D revision 3", /* 0x0009 */ + "ATA-3 published, ANSI X3.298-199x", /* 0x000a */ + "ATA-3 X3T10 2008D revision 6", /* 0x000b */ + "ATA-3 X3T13 2008D revision 7 and 7a", /* 0x000c */ + "ATA/ATAPI-4 X3T13 1153D revision 6", /* 0x000d */ + "ATA/ATAPI-4 T13 1153D revision 13", /* 0x000e */ + "ATA/ATAPI-4 X3T13 1153D revision 7", /* 0x000f */ + "ATA/ATAPI-4 T13 1153D revision 18", /* 0x0010 */ + "ATA/ATAPI-4 T13 1153D revision 15", /* 0x0011 */ + "ATA/ATAPI-4 published, ANSI NCITS 317-1998", /* 0x0012 */ + "ATA/ATAPI-5 T13 1321D revision 3", + "ATA/ATAPI-4 T13 1153D revision 14", /* 0x0014 */ + "ATA/ATAPI-5 T13 1321D revision 1", /* 0x0015 */ + "ATA/ATAPI-5 published, ANSI NCITS 340-2000", /* 0x0016 */ + "ATA/ATAPI-4 T13 1153D revision 17", /* 0x0017 */ + "ATA/ATAPI-6 T13 1410D revision 0", /* 0x0018 */ + "ATA/ATAPI-6 T13 1410D revision 3a", /* 0x0019 */ + "Reserved", /* 0x001a */ + "ATA/ATAPI-6 T13 1410D revision 2", /* 0x001b */ + "ATA/ATAPI-6 T13 1410D revision 1", /* 0x001c */ + "reserved" /* 0x001d */ + "reserved" /* 0x001e */ + "reserved" /* 0x001f-0xfffe*/ +}; +#endif +static const char actual_ver[] = { + /* word 81 value: */ + 0, /* 0x0000 WARNING: */ + 1, /* 0x0001 WARNING: */ + 1, /* 0x0002 WARNING: */ + 1, /* 0x0003 WARNING: */ + 2, /* 0x0004 WARNING: This array */ + 2, /* 0x0005 WARNING: corresponds */ + 3, /* 0x0006 WARNING: *exactly* */ + 2, /* 0x0007 WARNING: to the ATA/ */ + 3, /* 0x0008 WARNING: ATAPI version */ + 2, /* 0x0009 WARNING: listed in */ + 3, /* 0x000a WARNING: the */ + 3, /* 0x000b WARNING: minor_str */ + 3, /* 0x000c WARNING: array */ + 4, /* 0x000d WARNING: above. */ + 4, /* 0x000e WARNING: */ + 4, /* 0x000f WARNING: if you change */ + 4, /* 0x0010 WARNING: that one, */ + 4, /* 0x0011 WARNING: change this one */ + 4, /* 0x0012 WARNING: too!!! */ + 5, /* 0x0013 WARNING: */ + 4, /* 0x0014 WARNING: */ + 5, /* 0x0015 WARNING: */ + 5, /* 0x0016 WARNING: */ + 4, /* 0x0017 WARNING: */ + 6, /* 0x0018 WARNING: */ + 6, /* 0x0019 WARNING: */ + 0, /* 0x001a WARNING: */ + 6, /* 0x001b WARNING: */ + 6, /* 0x001c WARNING: */ + 0 /* 0x001d-0xfffe */ +}; + +/* words 82-84: cmds/feats supported */ +#define CMDS_W82 0x77ff /* word 82: defined command locations*/ +#define CMDS_W83 0x3fff /* word 83: defined command locations*/ +#define CMDS_W84 0x002f /* word 83: defined command locations*/ +#define SUPPORT_48_BIT 0x0400 +#define NUM_CMD_FEAT_STR 48 + +#ifdef CONFIG_FEATURE_HDPARM_GET_IDENTITY +static const char *cmd_feat_str[] = { + "", /* word 82 bit 15: obsolete */ + "NOP cmd", /* word 82 bit 14 */ + "READ BUFFER cmd", /* word 82 bit 13 */ + "WRITE BUFFER cmd", /* word 82 bit 12 */ + "", /* word 82 bit 11: obsolete */ + "Host Protected Area feature set", /* word 82 bit 10 */ + "DEVICE RESET cmd", /* word 82 bit 9 */ + "SERVICE interrupt", /* word 82 bit 8 */ + "Release interrupt", /* word 82 bit 7 */ + "Look-ahead", /* word 82 bit 6 */ + "Write cache", /* word 82 bit 5 */ + "PACKET command feature set", /* word 82 bit 4 */ + "Power Management feature set", /* word 82 bit 3 */ + "Removable Media feature set", /* word 82 bit 2 */ + "Security Mode feature set", /* word 82 bit 1 */ + "SMART feature set", /* word 82 bit 0 */ + /* --------------*/ + "", /* word 83 bit 15: !valid bit */ + "", /* word 83 bit 14: valid bit */ + "FLUSH CACHE EXT command", /* word 83 bit 13 */ + "Mandatory FLUSH CACHE command ", /* word 83 bit 12 */ + "Device Configuration Overlay feature set ", + "48-bit Address feature set ", /* word 83 bit 10 */ + "", + "SET MAX security extension", /* word 83 bit 8 */ + "Address Offset Reserved Area Boot", /* word 83 bit 7 */ + "SET FEATURES subcommand required to spinup after power up", + "Power-Up In Standby feature set", /* word 83 bit 5 */ + "Removable Media Status Notification feature set", + "Adv. Power Management feature set",/* word 83 bit 3 */ + "CFA feature set", /* word 83 bit 2 */ + "READ/WRITE DMA QUEUED", /* word 83 bit 1 */ + "DOWNLOAD MICROCODE cmd", /* word 83 bit 0 */ + /* --------------*/ + "", /* word 84 bit 15: !valid bit */ + "", /* word 84 bit 14: valid bit */ + "", /* word 84 bit 13: reserved */ + "", /* word 84 bit 12: reserved */ + "", /* word 84 bit 11: reserved */ + "", /* word 84 bit 10: reserved */ + "", /* word 84 bit 9: reserved */ + "", /* word 84 bit 8: reserved */ + "", /* word 84 bit 7: reserved */ + "", /* word 84 bit 6: reserved */ + "General Purpose Logging feature set", /* word 84 bit 5 */ + "", /* word 84 bit 4: reserved */ + "Media Card Pass Through Command feature set ", + "Media serial number ", /* word 84 bit 2 */ + "SMART self-test ", /* word 84 bit 1 */ + "SMART error logging " /* word 84 bit 0 */ +}; +#endif + + +/* words 85-87: cmds/feats enabled */ +/* use cmd_feat_str[] to display what commands and features have + * been enabled with words 85-87 + */ + +/* words 89, 90, SECU ERASE TIME */ +#define ERASE_BITS 0x00ff + +/* word 92: master password revision */ +/* NOVAL_0 or NOVAL_1 means no support for master password revision */ + +/* word 93: hw reset result */ +#define CBLID 0x2000 /* CBLID status */ +#define RST0 0x0001 /* 1=reset to device #0 */ +#define DEV_DET 0x0006 /* how device num determined */ +#define JUMPER_VAL 0x0002 /* device num determined by jumper */ +#define CSEL_VAL 0x0004 /* device num determined by CSEL_VAL */ + +/* word 127: removable media status notification feature set support */ +#define RM_STAT_BITS 0x0003 +#define RM_STAT_SUP 0x0001 + +/* word 128: security */ +#define SECU_ENABLED 0x0002 +#define SECU_LEVEL 0x0010 +#define NUM_SECU_STR 6 +#ifdef CONFIG_FEATURE_HDPARM_GET_IDENTITY +static const char *secu_str[] = { + "supported", /* word 128, bit 0 */ + "enabled", /* word 128, bit 1 */ + "locked", /* word 128, bit 2 */ + "frozen", /* word 128, bit 3 */ + "expired: security count", /* word 128, bit 4 */ + "supported: enhanced erase" /* word 128, bit 5 */ +}; +#endif + +/* word 160: CFA power mode */ +#define VALID_W160 0x8000 /* 1=word valid */ +#define PWR_MODE_REQ 0x2000 /* 1=CFA power mode req'd by some cmds*/ +#define PWR_MODE_OFF 0x1000 /* 1=CFA power moded disabled */ +#define MAX_AMPS 0x0fff /* value = max current in ma */ + +/* word 255: integrity */ +#define SIG 0x00ff /* signature location */ +#define SIG_VAL 0x00A5 /* signature value */ + +#define VERSION "v5.4" + +#define TIMING_MB 64 +#define TIMING_BUF_MB 1 +#define TIMING_BUF_BYTES (TIMING_BUF_MB * 1024 * 1024) +#define TIMING_BUF_COUNT (timing_MB / TIMING_BUF_MB) +#define BUFCACHE_FACTOR 2 + +#undef DO_FLUSHCACHE /* under construction: force cache flush on -W0 */ + +/* Busybox messages and functions */ + +const char * const bb_msg_shared_mem ="could not %s sharedmem buf"; +const char * const bb_msg_op_not_supp =" operation not supported on %s disks"; + +static void bb_ioctl(int fd, int request, void *argp, const char *string) +{ + if (ioctl (fd, request, argp) != 0) + bb_perror_msg(" %s", string); +} + +static void if_printf(unsigned long i, char *fmt, ... ) +{ + va_list ap; + va_start(ap, fmt); + if (i) + vprintf(fmt, ap); + va_end(ap); +} + +static void on_off (unsigned int value); + +static void if_printf_on_off(unsigned long get_arg,const char *fmt, unsigned long arg) +{ + if (get_arg) + { + printf(fmt, arg); + on_off(arg); + } +} + +static void bb_ioctl_on_off(int fd, int request, void *argp, const char *string, + const char * fmt) +{ + if (ioctl (fd, request, &argp) != 0) + bb_perror_msg(" %s", string); + else + { + printf(fmt, (unsigned long) argp); + on_off((unsigned long) argp); + } +} + +#ifdef CONFIG_FEATURE_HDPARM_GET_IDENTITY +static void if_else_printf(unsigned long i, char *fmt1, char *fmt2, ... ) +{ + va_list ap; + va_start(ap, fmt2); + if (i) + vprintf(fmt1, ap); + else + vprintf(fmt2, ap); + va_end(ap); +} + +static void print_ascii(uint16_t *p, uint8_t length); + +static void xprint_ascii(uint16_t *val ,int i, char * string, int n) +{ + if(val[i]) + { + printf("\t%-20s",string); + print_ascii(&val[i], n); + } +} + +static void if_strcat(unsigned long test, char *modes, char *string) +{ + if (test) + strcat(modes,string); +} +#endif + +static void sync_and_sleep(int i) +{ + sync(); + sleep(i); +} + +static uint16_t check_if_min_and_set_val(uint16_t a, uint16_t b) +{ + if( a < b) + a = b; + return a; +} + +static uint16_t check_if_maj_and_set_val(uint16_t a, uint16_t b) +{ + if( a > b) + a = b; + return a; +} + +static unsigned long int set_flag(char *p, char max) +{ + if (*p >= '0' && *p <= max ) + return 1; + return 0; +} + +/* end of busybox specific stuff */ + +#ifdef CONFIG_FEATURE_HDPARM_GET_IDENTITY +static uint8_t mode_loop(uint16_t mode_sup, uint16_t mode_sel, int cc, uint8_t *have_mode) +{ + uint16_t ii; + uint8_t err_dma = 0; + + for(ii = 0; ii <= MODE_MAX; ii++) + { + if(mode_sel & 0x0001) + { + printf("*%cdma%u ",cc,ii); + if(*have_mode) + err_dma = 1; + *have_mode = 1; + } + else if(mode_sup & 0x0001) + printf("%cdma%u ",cc,ii); + + mode_sup >>=1; + mode_sel >>=1; + } + return err_dma; +} + +static void print_ascii(uint16_t *p, uint8_t length) { + uint8_t ii; + char cl; + + /* find first non-space & print it */ + for(ii = 0; ii< length; ii++) + { + if(((char) 0x00ff&((*p)>>8)) != ' ') + break; + if((cl = (char) 0x00ff&(*p)) != ' ') + { + if_printf((cl != '\0'),"%c",cl); + p++; + ii++; + break; + } + p++; + } + /* print the rest */ + for(; ii< length; ii++) + { + if(!(*p)) + break; /* some older devices have NULLs */ + printf("%c%c",(char)0x00ff&((*p)>>8),(char)(*p)&0x00ff); + p++; + } + printf("\n"); +} + +/* identify() is the only extern function used across two source files. The + others, though, were declared in hdparm.c with global scope; since other + functions in that file have static (file) scope, I assume the difference is + intentional. */ +static void identify (uint16_t *id_supplied, const char *devname) +{ + + char *id_file = NULL; + FILE *fl; + uint16_t val[256], ii, jj, kk; + uint16_t like_std = 1, std = 0, min_std = 0xffff; + uint16_t dev = NO_DEV, eqpt = NO_DEV; + uint8_t have_mode = 0, err_dma = 0; + uint8_t chksum = 0; + uint32_t ll, mm, nn, oo; + __u64 bbbig; /* (:) */ + + if (id_supplied) + { +#if __BYTE_ORDER == __BIG_ENDIAN + swab(id_supplied, val, sizeof(val)); +#else + memcpy(val, id_supplied, sizeof(val)); +#endif + } + else + { + id_file = xcalloc(1, strlen(devname)+22); + sprintf(id_file, "/proc/ide/%s/identify", devname); + /* open the file, read in all the info and close it */ + if (id_file == NULL) + fl = stdin; + else + fl = bb_xfopen(id_file, "r"); + + /* calculate checksum over all bytes */ + for(ii = GEN_CONFIG; ii<=INTEGRITY; ii++) + { + unsigned int scratch; + if(1 != fscanf(fl,"%04x",&scratch)) + break; + val[ii] = (uint16_t)scratch; + chksum += val[ii] + (val[ii] >> 8); + } + fclose(fl); + /*bb_fclose_nonstdin(fl);*/ + if(ii < (INTEGRITY+1)) + bb_error_msg_and_die("Input file wrong format or length"); + } + chksum &= 0xff; + + /* check if we recognise the device type */ + printf("\n"); + if(!(val[GEN_CONFIG] & NOT_ATA)) + { + dev = ATA_DEV; + printf("ATA device, with "); + } + else if(val[GEN_CONFIG]==CFA_SUPPORT_VAL) + { + dev = ATA_DEV; + like_std = 4; + printf("CompactFlash ATA device, with "); + } + else if(!(val[GEN_CONFIG] & NOT_ATAPI)) + { + dev = ATAPI_DEV; + eqpt = (val[GEN_CONFIG] & EQPT_TYPE) >> SHIFT_EQPT; + printf("ATAPI %s, with ", pkt_str[eqpt]); + like_std = 3; + } + else + /*"Unknown device type:\n\tbits 15&14 of general configuration word 0 both set to 1.\n"*/ + bb_error_msg_and_die("Unknown device type"); + + if_printf(!(val[GEN_CONFIG] & MEDIA_REMOVABLE),"non-"); + printf("removable media\n"); + + /* Info from the specific configuration word says whether or not the + * ID command completed correctly. It is only defined, however in + * ATA/ATAPI-5 & 6; it is reserved (value theoretically 0) in prior + * standards. Since the values allowed for this word are extremely + * specific, it should be safe to check it now, even though we don't + * know yet what standard this device is using. + */ + if((val[CONFIG]==STBY_NID_VAL) || (val[CONFIG]==STBY_ID_VAL) || + (val[CONFIG]==PWRD_NID_VAL) || (val[CONFIG]==PWRD_ID_VAL) ) + { + like_std = 5; + if_printf(((val[CONFIG]==STBY_NID_VAL) || (val[CONFIG]==STBY_ID_VAL)), + "powers-up in standby; SET FEATURES subcmd spins-up.\n"); + if_printf((((val[CONFIG]==STBY_NID_VAL) || (val[CONFIG]==PWRD_NID_VAL)) && (val[GEN_CONFIG] & INCOMPLETE)), + "\n\tWARNING: ID response incomplete.\n\tFollowing data may be incorrect.\n\n"); + } + + /* output the model and serial numbers and the fw revision */ + xprint_ascii(val, START_MODEL, "Model Number:", LENGTH_MODEL); + xprint_ascii(val, START_SERIAL, "Serial Number:", LENGTH_SERIAL); + xprint_ascii(val, START_FW_REV, "Firmware Revision:", LENGTH_FW_REV); + xprint_ascii(val, START_MEDIA, "Media Serial Num:", LENGTH_MEDIA); + xprint_ascii(val, START_MANUF, "Media Manufacturer:", LENGTH_MANUF); + + /* major & minor standards version number (Note: these words were not + * defined until ATA-3 & the CDROM std uses different words.) */ + printf("Standards:"); + if(eqpt != CDROM) + { + if(val[MINOR] && (val[MINOR] <= MINOR_MAX)) + { + like_std=check_if_min_and_set_val(like_std, 3); + std = actual_ver[val[MINOR]]; + if_printf(std,"\n\tUsed: %s ",minor_str[val[MINOR]]); + + } + /* looks like when they up-issue the std, they obsolete one; + * thus, only the newest 4 issues need be supported. (That's + * what "kk" and "min_std" are all about.) */ + if(val[MAJOR] && (val[MAJOR] !=NOVAL_1)) + { + printf("\n\tSupported: "); + jj = val[MAJOR] << 1; + kk = like_std >4 ? like_std-4: 0; + for(ii = 14; (ii >0)&&(ii>kk); ii--) + { + if(jj & 0x8000) + { + printf("%u ", ii); + if(like_std < ii) + { + like_std = ii; + kk = like_std >4 ? like_std-4: 0; + } + min_std=check_if_maj_and_set_val(min_std, ii); + } + jj <<= 1; + } + like_std=check_if_min_and_set_val(like_std, 3); + } + /* Figure out what standard the device is using if it hasn't told + * us. If we know the std, check if the device is using any of + * the words from the next level up. It happens. + */ + like_std=check_if_min_and_set_val(like_std, std); + + if(((std == 5) || (!std && (like_std < 6))) && + ((((val[CMDS_SUPP_1] & VALID) == VALID_VAL) && + (( val[CMDS_SUPP_1] & CMDS_W83) > 0x00ff)) || + ((( val[CMDS_SUPP_2] & VALID) == VALID_VAL) && + ( val[CMDS_SUPP_2] & CMDS_W84) ) ) ) + { + like_std = 6; + } + else if(((std == 4) || (!std && (like_std < 5))) && + ((((val[INTEGRITY] & SIG) == SIG_VAL) && !chksum) || + (( val[HWRST_RSLT] & VALID) == VALID_VAL) || + ((( val[CMDS_SUPP_1] & VALID) == VALID_VAL) && + (( val[CMDS_SUPP_1] & CMDS_W83) > 0x001f)) ) ) + { + like_std = 5; + } + else if(((std == 3) || (!std && (like_std < 4))) && + ((((val[CMDS_SUPP_1] & VALID) == VALID_VAL) && + ((( val[CMDS_SUPP_1] & CMDS_W83) > 0x0000) || + (( val[CMDS_SUPP_0] & CMDS_W82) > 0x000f))) || + (( val[CAPAB_1] & VALID) == VALID_VAL) || + (( val[WHATS_VALID] & OK_W88) && val[ULTRA_DMA]) || + (( val[RM_STAT] & RM_STAT_BITS) == RM_STAT_SUP) ) ) + { + like_std = 4; + } + else if(((std == 2) || (!std && (like_std < 3))) && + ((val[CMDS_SUPP_1] & VALID) == VALID_VAL) ) + { + like_std = 3; + } + else if(((std == 1) || (!std && (like_std < 2))) && + ((val[CAPAB_0] & (IORDY_SUP | IORDY_OFF)) || + (val[WHATS_VALID] & OK_W64_70)) ) + { + like_std = 2; + } + if(!std) + printf("\n\tLikely used: %u\n",like_std); + else if(like_std > std) + printf("& some of %u\n",like_std); + else + printf("\n"); + } + else + { + /* TBD: do CDROM stuff more thoroughly. For now... */ + kk = 0; + if(val[CDR_MINOR] == 9) + { + kk = 1; + printf("\n\tUsed: ATAPI for CD-ROMs, SFF-8020i, r2.5"); + } + if(val[CDR_MAJOR] && (val[CDR_MAJOR] !=NOVAL_1)) + { + kk = 1; + printf("\n\tSupported: CD-ROM ATAPI"); + jj = val[CDR_MAJOR] >> 1; + for(ii = 1; ii <15; ii++) + { + if_printf((jj & 0x0001),"-%u ", ii); + jj >>= 1; + } + } + if_else_printf((!kk),"\n\tLikely used CD-ROM ATAPI-1\n","\n"); + /* the cdrom stuff is more like ATA-2 than anything else, so: */ + like_std = 2; + } + + if(min_std == 0xffff) + min_std = like_std > 4 ? like_std - 3 : 1; + + printf("Configuration:\n"); + /* more info from the general configuration word */ + if((eqpt != CDROM) && (like_std == 1)) + { + jj = val[GEN_CONFIG] >> 1; + for(ii = 1; ii < 15; ii++) + { + if_printf((jj & 0x0001),"\t%s\n",ata1_cfg_str[ii]); + jj >>=1; + } + } + if(dev == ATAPI_DEV) + { + printf("\tDRQ response: "); /* Data Request (DRQ) */ + switch(val[GEN_CONFIG] & DRQ_RESPONSE_TIME) + { + case DRQ_3MS_VAL : + printf("3ms.\n"); + break; + case DRQ_INTR_VAL : + printf("<=10ms with INTRQ\n"); + break; + case DRQ_50US_VAL : + printf("50us.\n"); + break; + default : + printf("unknown.\n"); + break; + } + printf("\tPacket size: "); + switch(val[GEN_CONFIG] & PKT_SIZE_SUPPORTED) + { + case PKT_SIZE_12_VAL : + printf("12 bytes\n"); + break; + case PKT_SIZE_16_VAL : + printf("16 bytes\n"); + break; + default : + printf("Unknown\n"); + break; + } + } + else + { + /* addressing...CHS? See section 6.2 of ATA specs 4 or 5 */ + ll = (uint32_t)val[LBA_SECTS_MSB] << 16 | val[LBA_SECTS_LSB]; + mm = 0; bbbig = 0; + if ( (ll > 0x00FBFC10) && (!val[LCYLS])) + printf("\tCHS addressing not supported\n"); + else + { + jj = val[WHATS_VALID] & OK_W54_58; + printf("\tLogical\t\tmax\tcurrent\n\tcylinders\t%u\t%u\n\theads\t\t%u\t%u\n\tsectors/track\t%u\t%u\n\t--\n", + val[LCYLS],jj?val[LCYLS_CUR]:0, val[LHEADS],jj?val[LHEADS_CUR]:0, val[LSECTS],jj?val[LSECTS_CUR]:0); + + if_printf(((min_std == 1) && (val[TRACK_BYTES] || val[SECT_BYTES])), + "\tbytes/track: %u\tbytes/sector: %u\n",val[TRACK_BYTES], val[SECT_BYTES]); + + if(jj) + { + mm = (uint32_t)val[CAPACITY_MSB] << 16 | val[CAPACITY_LSB]; + if(like_std < 3) + { + /* check Endian of capacity bytes */ + nn = val[LCYLS_CUR] * val[LHEADS_CUR] * val[LSECTS_CUR]; + oo = (uint32_t)val[CAPACITY_LSB] << 16 | val[CAPACITY_MSB]; + if(abs(mm - nn) > abs(oo - nn)) + mm = oo; + } + printf("\tCHS current addressable sectors:%11u\n",mm); + } + } + /* LBA addressing */ + printf("\tLBA user addressable sectors:%11u\n",ll); + if( ((val[CMDS_SUPP_1] & VALID) == VALID_VAL) && + (val[CMDS_SUPP_1] & SUPPORT_48_BIT) ) + { + bbbig = (__u64)val[LBA_64_MSB] << 48 | + (__u64)val[LBA_48_MSB] << 32 | + (__u64)val[LBA_MID] << 16 | + val[LBA_LSB] ; + printf("\tLBA48 user addressable sectors:%11llu\n",bbbig); + } + + if (!bbbig) + bbbig = (__u64)(ll>mm ? ll : mm); /* # 512 byte blocks */ + printf("\tdevice size with M = 1024*1024: %11llu MBytes\n",bbbig>>11); + bbbig = (bbbig<<9)/1000000; + printf("\tdevice size with M = 1000*1000: %11llu MBytes ",bbbig); + + if_else_printf((bbbig > 1000),"(%llu GB)\n","\n",bbbig/1000); + + } + + /* hw support of commands (capabilities) */ + printf("Capabilities:\n\t"); + + if(dev == ATAPI_DEV) + { + if(eqpt != CDROM) + if_printf((val[CAPAB_0] & CMD_Q_SUP),"Cmd queuing, "); + + if_printf((val[CAPAB_0] & OVLP_SUP),"Cmd overlap, "); + } + if_printf((val[CAPAB_0] & LBA_SUP),"LBA, "); + + if(like_std != 1) + { + printf("IORDY"); + if_printf((!(val[CAPAB_0] & IORDY_SUP)),"(may be)"); + if_else_printf((val[CAPAB_0] & IORDY_OFF),"(can","(cannot"); + printf(" be disabled)\n"); + } + else + printf("no IORDY\n"); + + if((like_std == 1) && val[BUF_TYPE]) + { + kk = val[BUF_TYPE]; + printf("\tBuffer type: %04x: ",kk); + if_else_printf((kk < 2),"single port, single-sector","dual port, multi-sector"); + if_printf((kk > 2)," with read caching ability"); + printf("\n"); + } + jj = 0; + if((min_std == 1) && (val[BUFFER__SIZE] && (val[BUFFER__SIZE] != NOVAL_1))) + { + printf("\tBuffer size: %.1fkB",(float)val[BUFFER__SIZE]/2); + jj = 1; + } + if((min_std < 4) && (val[RW_LONG])) + { + printf("\tbytes avail on r/w long: %u",val[RW_LONG]); + jj = 1; + } + if((eqpt != CDROM) && (like_std > 3)) + { + printf("\tQueue depth: %u",(val[QUEUE_DEPTH] & DEPTH_BITS)+1); + jj = 1; + } + if_printf(jj,"\n"); + + if(dev == ATA_DEV) + { + if(like_std == 1) + printf("\tCan%s perform double-word IO\n",(!val[DWORD_IO]) ?"not":""); + else + { + printf("\tStandby timer values: spec'd by "); + if_else_printf((val[CAPAB_0] & STD_STBY),"Standard","Vendor"); + if((like_std > 3) && ((val[CAPAB_1] & VALID) == VALID_VAL)) + printf(", %s device specific minimum\n",(val[CAPAB_1] & MIN_STANDBY_TIMER)?"with":"no"); + else + printf("\n"); + } + printf("\tR/W multiple sector transfer: "); + if((like_std < 3) && !(val[SECTOR_XFER_MAX] & SECTOR_XFER)) + printf("not supported\n"); + else + { + printf("Max = %u\tCurrent = ",val[SECTOR_XFER_MAX] & SECTOR_XFER); + if_else_printf((val[SECTOR_XFER_CUR] & MULTIPLE_SETTING_VALID), + "%u\n","?\n",val[SECTOR_XFER_CUR] & SECTOR_XFER); + } + if((like_std > 3) && (val[CMDS_SUPP_1] & 0x0008)) + { + /* We print out elsewhere whether the APM feature is enabled or + not. If it's not enabled, let's not repeat the info; just print + nothing here. */ + printf("\tAdvancedPM level: "); + if ( (val[ADV_PWR] & 0xFF00) == 0x4000 ) + { + uint8_t apm_level = val[ADV_PWR] & 0x00FF; + printf("%u (0x%x)\n", apm_level, apm_level); + } + else + printf("unknown setting (0x%04x)\n", val[ADV_PWR]); + } + if(like_std > 5) + { + if_printf(val[ACOUSTIC],"\tRecommended acoustic management value: %u, current value: %u\n", + (val[ACOUSTIC] >> 8) & 0x00ff, val[ACOUSTIC] & 0x00ff); + } + } + else + { + /* ATAPI */ + if(eqpt != CDROM) + if_printf((val[CAPAB_0] & SWRST_REQ),"\tATA sw reset required\n"); + + if(val[PKT_REL] || val[SVC_NBSY]) + { + printf("\tOverlap support:"); + if_printf(val[PKT_REL]," %uus to release bus.",val[PKT_REL]); + if_printf(val[SVC_NBSY]," %uus to clear BSY after SERVICE cmd.",val[SVC_NBSY]); + printf("\n"); + } + } + + /* DMA stuff. Check that only one DMA mode is selected. */ + printf("\tDMA: "); + if(!(val[CAPAB_0] & DMA_SUP)) + printf("not supported\n"); + else + { + if_printf((val[DMA_MODE] && !val[SINGLE_DMA] && !val[MULTI_DMA]), + " sdma%u\n",(val[DMA_MODE] & MODE) >> 8); + if(val[SINGLE_DMA]) + { + jj = val[SINGLE_DMA]; + kk = val[SINGLE_DMA] >> 8; + err_dma += mode_loop(jj,kk,'s',&have_mode); + } + if(val[MULTI_DMA]) + { + jj = val[MULTI_DMA]; + kk = val[MULTI_DMA] >> 8; + err_dma += mode_loop(jj,kk,'m',&have_mode); + } + if((val[WHATS_VALID] & OK_W88) && val[ULTRA_DMA]) + { + jj = val[ULTRA_DMA]; + kk = val[ULTRA_DMA] >> 8; + err_dma += mode_loop(jj,kk,'u',&have_mode); + } + if_printf((err_dma || !have_mode),"(?)"); + printf("\n"); + + if_printf(((dev == ATAPI_DEV) && (eqpt != CDROM) && (val[CAPAB_0] & DMA_IL_SUP)), + "\t Interleaved DMA support\n"); + + if((val[WHATS_VALID] & OK_W64_70) && + (val[DMA_TIME_MIN] || val[DMA_TIME_NORM])) + { + printf("\t Cycle time:"); + if_printf(val[DMA_TIME_MIN]," min=%uns",val[DMA_TIME_MIN]); + if_printf(val[DMA_TIME_NORM]," recommended=%uns",val[DMA_TIME_NORM]); + printf("\n"); + } + } + + /* Programmed IO stuff */ + printf("\tPIO: "); + /* If a drive supports mode n (e.g. 3), it also supports all modes less + * than n (e.g. 3, 2, 1 and 0). Print all the modes. */ + if((val[WHATS_VALID] & OK_W64_70) && (val[ADV_PIO_MODES] & PIO_SUP)) + { + jj = ((val[ADV_PIO_MODES] & PIO_SUP) << 3) | 0x0007; + for(ii = 0; ii <= PIO_MODE_MAX ; ii++) + { + if_printf((jj & 0x0001),"pio%d ",ii); + jj >>=1; + } + printf("\n"); + } + else if(((min_std < 5) || (eqpt == CDROM)) && (val[PIO_MODE] & MODE) ) + { + for(ii = 0; ii <= val[PIO_MODE]>>8; ii++) + printf("pio%d ",ii); + printf("\n"); + } + else + printf("unknown\n"); + + if(val[WHATS_VALID] & OK_W64_70) + { + if(val[PIO_NO_FLOW] || val[PIO_FLOW]) + { + printf("\t Cycle time:"); + if_printf(val[PIO_NO_FLOW]," no flow control=%uns", val[PIO_NO_FLOW]); + if_printf(val[PIO_FLOW]," IORDY flow control=%uns", val[PIO_FLOW]); + printf("\n"); + } + } + + if((val[CMDS_SUPP_1] & VALID) == VALID_VAL) + { + printf("Commands/features:\n\tEnabled\tSupported:\n"); + jj = val[CMDS_SUPP_0]; + kk = val[CMDS_EN_0]; + for(ii = 0; ii < NUM_CMD_FEAT_STR; ii++) + { + if((jj & 0x8000) && (*cmd_feat_str[ii] != '\0')) + { + if_else_printf((kk & 0x8000),"\t *","\t"); + printf("\t%s\n",cmd_feat_str[ii]); + } + jj <<=1; kk<<=1; + if(ii%16 == 15) + { + jj = val[CMDS_SUPP_0+1+(ii/16)]; + kk = val[CMDS_EN_0+1+(ii/16)]; + } + if(ii == 31) + { + if((val[CMDS_SUPP_2] & VALID) != VALID_VAL) + ii +=16; + } + } + } + if_printf(((val[RM_STAT] & RM_STAT_BITS) == RM_STAT_SUP), + "\tRemovable Media Status Notification feature set supported\n"); + + + /* security */ + if((eqpt != CDROM) && (like_std > 3) && + (val[SECU_STATUS] || val[ERASE_TIME] || val[ENH_ERASE_TIME])) + { + printf("Security: \n"); + if_printf((val[PSWD_CODE] && (val[PSWD_CODE] != NOVAL_1)), + "\tMaster password revision code = %u\n",val[PSWD_CODE]); + jj = val[SECU_STATUS]; + if(jj) + { + for(ii = 0; ii < NUM_SECU_STR; ii++) + { + if_else_printf((!(jj & 0x0001)),"\tnot\t%s\n", "\t\t%s\n", secu_str[ii]); + jj >>=1; + } + if(val[SECU_STATUS] & SECU_ENABLED) + { + printf("\tSecurity level "); + if_else_printf((val[SECU_STATUS] & SECU_LEVEL),"maximum\n","high\n"); + } + } + jj = val[ERASE_TIME] & ERASE_BITS; + kk = val[ENH_ERASE_TIME] & ERASE_BITS; + if(jj || kk) + { + printf("\t"); + if_printf(jj,"%umin for SECURITY ERASE UNIT. ", jj==ERASE_BITS ? 508 : jj<<1); + if_printf(kk,"%umin for ENHANCED SECURITY ERASE UNIT.", kk==ERASE_BITS ? 508 : kk<<1); + printf("\n"); + } + } + + /* reset result */ + if((val[HWRST_RSLT] & VALID) == VALID_VAL) + { + printf("HW reset results:\n"); + if_else_printf((val[HWRST_RSLT] & CBLID),"\tCBLID- above Vih\n","\tCBLID- below Vih\n"); + + if(val[HWRST_RSLT] & RST0) + { + printf("\tDevice num = 0"); + jj = val[HWRST_RSLT]; + } + else + { + printf("\tDevice num = 1"); + jj = val[HWRST_RSLT] >> 8; + } + + if((jj & DEV_DET) == JUMPER_VAL) + printf(" determined by the jumper"); + else if((jj & DEV_DET) == CSEL_VAL) + printf(" determined by CSEL"); + printf("\n"); + } + + /* more stuff from std 5 */ + if((like_std > 4) && (eqpt != CDROM)) + { + if(val[CFA_PWR_MODE] & VALID_W160) + { + printf("CFA power mode 1:\n\t"); + if_else_printf((val[CFA_PWR_MODE] & PWR_MODE_OFF),"disabled","enabled"); + + if_printf((val[CFA_PWR_MODE] & PWR_MODE_REQ)," and required by some commands"); + printf("\n"); + + if_printf((val[CFA_PWR_MODE] & MAX_AMPS),"\tMaximum current = %uma\n",val[CFA_PWR_MODE] & MAX_AMPS); + } + if((val[INTEGRITY] & SIG) == SIG_VAL) + { + printf("Checksum: "); + if_printf(chksum,"in"); + printf("correct\n"); + } + } + + exit(0); +} +#endif + +static int verbose = 0, get_identity = 0, get_geom = 0, noisy = 1, quiet = 0; +static int flagcount = 0, do_flush = 0, is_scsi_hd = 0, is_xt_hd = 0; +static int do_ctimings, do_timings = 0; + +static unsigned long set_readahead= 0, get_readahead= 0, Xreadahead= 0; +static unsigned long set_readonly = 0, get_readonly = 0, readonly = 0; +static unsigned long set_unmask = 0, get_unmask = 0, unmask = 0; +static unsigned long set_mult = 0, get_mult = 0, mult = 0; +#ifdef CONFIG_FEATURE_HDPARM_HDIO_GETSET_DMA +static unsigned long set_dma = 0, get_dma = 0, dma = 0; +#endif +static unsigned long set_dma_q = 0, get_dma_q = 0, dma_q = 0; +static unsigned long set_nowerr = 0, get_nowerr = 0, nowerr = 0; +static unsigned long set_keep = 0, get_keep = 0, keep = 0; +static unsigned long set_io32bit = 0, get_io32bit = 0, io32bit = 0; +static unsigned long set_piomode = 0, noisy_piomode= 0; +static int piomode = 0; +#ifdef HDIO_DRIVE_CMD +static unsigned long set_dkeep = 0, get_dkeep = 0, dkeep = 0; +static unsigned long set_standby = 0, get_standby = 0, standby_requested= 0; +static unsigned long set_xfermode = 0, get_xfermode = 0; +static int xfermode_requested= 0; +static unsigned long set_lookahead= 0, get_lookahead= 0, lookahead= 0; +static unsigned long set_prefetch = 0, get_prefetch = 0, prefetch = 0; +static unsigned long set_defects = 0, get_defects = 0, defects = 0; +static unsigned long set_wcache = 0, get_wcache = 0, wcache = 0; +static unsigned long set_doorlock = 0, get_doorlock = 0, doorlock = 0; +static unsigned long set_seagate = 0, get_seagate = 0; +static unsigned long set_standbynow = 0, get_standbynow = 0; +static unsigned long set_sleepnow = 0, get_sleepnow = 0; +static unsigned long get_powermode = 0; +static unsigned long set_apmmode = 0, get_apmmode= 0, apmmode = 0; +#endif +#ifdef CONFIG_FEATURE_HDPARM_GET_IDENTITY +static int get_IDentity = 0; +#endif +#ifdef CONFIG_FEATURE_HDPARM_HDIO_UNREGISTER_HWIF +static int unregister_hwif = 0; +static int hwif = 0; +#endif +#ifdef CONFIG_FEATURE_HDPARM_HDIO_SCAN_HWIF +static int scan_hwif = 0; +static int hwif_data = 0; +static int hwif_ctrl = 0; +static int hwif_irq = 0; +#endif +#ifdef CONFIG_FEATURE_HDPARM_HDIO_TRISTATE_HWIF +static int set_busstate = 0, get_busstate = 0, busstate = 0; +#endif +static int reread_partn = 0; + +#ifdef CONFIG_FEATURE_HDPARM_HDIO_DRIVE_RESET +static int perform_reset = 0; +#endif /* CONFIG_FEATURE_HDPARM_HDIO_DRIVE_RESET */ +#ifdef CONFIG_FEATURE_HDPARM_HDIO_TRISTATE_HWIF +static int perform_tristate = 0, tristate = 0; +#endif /* CONFIG_FEATURE_HDPARM_HDIO_TRISTATE_HWIF */ + +// Historically, if there was no HDIO_OBSOLETE_IDENTITY, then +// then the HDIO_GET_IDENTITY only returned 142 bytes. +// Otherwise, HDIO_OBSOLETE_IDENTITY returns 142 bytes, +// and HDIO_GET_IDENTITY returns 512 bytes. But the latest +// 2.5.xx kernels no longer define HDIO_OBSOLETE_IDENTITY +// (which they should, but they should just return -EINVAL). +// +// So.. we must now assume that HDIO_GET_IDENTITY returns 512 bytes. +// On a really old system, it will not, and we will be confused. +// Too bad, really. + +#ifdef CONFIG_FEATURE_HDPARM_GET_IDENTITY +static const char *cfg_str[] = +{ "", " HardSect", " SoftSect", " NotMFM", + " HdSw>15uSec", " SpinMotCtl", " Fixed", " Removeable", + " DTR<=5Mbs", " DTR>5Mbs", " DTR>10Mbs", " RotSpdTol>.5%", + " dStbOff", " TrkOff", " FmtGapReq", " nonMagnetic" +}; + +static const char *BuffType[] = {"unknown", "1Sect", "DualPort", "DualPortCache"}; + +static void dump_identity (const struct hd_driveid *id) +{ + int i; + char pmodes[64] = {0,}, dmodes[128]={0,}, umodes[128]={0,}; + const unsigned short int *id_regs= (const void*) id; + unsigned long capacity; + + printf("\n Model=%.40s, FwRev=%.8s, SerialNo=%.20s\n Config={", + id->model, id->fw_rev, id->serial_no); + for (i=0; i<=15; i++) + if_printf((id->config & (1<cyls, id->heads, id->sectors, id->track_bytes, + id->sector_bytes, id->ecc_bytes); + + if (id->buf_type > 3) + printf("%s%u", " BuffType=", id->buf_type); + else + printf("%s%s", " BuffType=", BuffType[id->buf_type]); + + printf(", BuffSize=%ukB, MaxMultSect=%u", id->buf_size/2, id->max_multsect); + if (id->max_multsect) + { + printf(", MultSect="); + if (!(id->multsect_valid&1)) + printf("?%u?", id->multsect); + else if (id->multsect) + printf("%u", id->multsect); + else + printf("off"); + } + printf("\n"); + if (id->tPIO <= 5) + { + strcat(pmodes, "pio0 "); + if_strcat((id->tPIO >= 1), pmodes, "pio1 "); + if_strcat((id->tPIO >= 2), pmodes, "pio2 "); + + } + if_printf((!(id->field_valid&1))," (maybe):"); +#if __BYTE_ORDER == __BIG_ENDIAN + capacity = (id->cur_capacity0 << 16) | id->cur_capacity1; +#else + capacity = (id->cur_capacity1 << 16) | id->cur_capacity0; +#endif + printf(" CurCHS=%u/%u/%u, CurSects=%lu, LBA=%s",id->cur_cyls, id->cur_heads, + id->cur_sectors, capacity , + ((id->capability&2)==0)?"no":"yes"); + + if_printf((id->capability&2),", LBAsects=%u", id->lba_capacity); + + if (id->capability&1) + { + if (id->dma_1word | id->dma_mword) + { + if_strcat((id->dma_1word & 0x100), dmodes, "*"); + if_strcat((id->dma_1word & 1), dmodes, "sdma0 "); + if_strcat((id->dma_1word & 0x200), dmodes, "*"); + if_strcat((id->dma_1word & 2), dmodes, "sdma1 "); + if_strcat((id->dma_1word & 0x400), dmodes, "*"); + if_strcat((id->dma_1word & 4), dmodes, "sdma2 "); + if_strcat((id->dma_1word & 0xf800), dmodes, "*"); + if_strcat((id->dma_1word & 0xf8), dmodes, "sdma? "); + if_strcat((id->dma_mword & 0x100), dmodes, "*"); + if_strcat((id->dma_mword & 1), dmodes, "mdma0 "); + if_strcat((id->dma_mword & 0x200), dmodes, "*"); + if_strcat((id->dma_mword & 2), dmodes, "mdma1 "); + if_strcat((id->dma_mword & 0x400), dmodes, "*"); + if_strcat((id->dma_mword & 4), dmodes, "mdma2 "); + if_strcat((id->dma_mword & 0xf800), dmodes, "*"); + if_strcat((id->dma_mword & 0xf8), dmodes, "mdma? "); + } + } + printf("\n IORDY="); + if (id->capability&8) + printf((id->capability&4) ? "on/off" : "yes"); + else + printf("no"); + + if ((id->capability&8) || (id->field_valid&2)) + { + if (id->field_valid&2) + { + printf(", tPIO={min:%u,w/IORDY:%u}", id->eide_pio, id->eide_pio_iordy); + if_strcat((id->eide_pio_modes & 1), pmodes, "pio3 "); + if_strcat((id->eide_pio_modes & 2), pmodes, "pio4 "); + if_strcat((id->eide_pio_modes &~3), pmodes, "pio? "); + } + if (id->field_valid&4) + { + if_strcat((id->dma_ultra & 0x100),umodes,"*"); + if_strcat((id->dma_ultra & 0x001),umodes,"udma0 "); + if_strcat((id->dma_ultra & 0x200),umodes,"*"); + if_strcat((id->dma_ultra & 0x002),umodes,"udma1 "); + if_strcat((id->dma_ultra & 0x400),umodes,"*"); + if_strcat((id->dma_ultra & 0x004),umodes,"udma2 "); +#ifdef __NEW_HD_DRIVE_ID + if (id->hw_config & 0x2000) + { +#else /* !__NEW_HD_DRIVE_ID */ + if (id->word93 & 0x2000) + { +#endif /* __NEW_HD_DRIVE_ID */ + if_strcat((id->dma_ultra & 0x0800),umodes,"*"); + if_strcat((id->dma_ultra & 0x0008),umodes,"udma3 "); + if_strcat((id->dma_ultra & 0x1000),umodes,"*"); + if_strcat((id->dma_ultra & 0x0010),umodes,"udma4 "); + if_strcat((id->dma_ultra & 0x2000),umodes,"*"); + if_strcat((id->dma_ultra & 0x0020),umodes,"udma5 "); + if_strcat((id->dma_ultra & 0x4000),umodes,"*"); + if_strcat((id->dma_ultra & 0x0040),umodes,"udma6 "); + if_strcat((id->dma_ultra & 0x8000),umodes,"*"); + if_strcat((id->dma_ultra & 0x0080),umodes,"udma7 "); + } + } + } + if_printf(((id->capability&1) && (id->field_valid&2)), + ", tDMA={min:%u,rec:%u}", id->eide_dma_min, id->eide_dma_time); + printf("\n PIO modes: %s", pmodes); + if_printf((*dmodes),"\n DMA modes: %s", dmodes); + if_printf((*umodes),"\n UDMA modes: %s", umodes); + + printf("\n AdvancedPM=%s",((id_regs[83]&8)==0)?"no":"yes"); + if (id_regs[83] & 8) + { + if (!(id_regs[86]&8)) + printf(": disabled (255)"); + else if ((id_regs[91]&0xFF00)!=0x4000) + printf(": unknown setting"); + else + printf(": mode=0x%02X (%u)",id_regs[91]&0xFF,id_regs[91]&0xFF); + } + if_printf( (id_regs[82]&0x20)," WriteCache=%s",(id_regs[85]&0x20) ? "enabled" : "disabled"); +#ifdef __NEW_HD_DRIVE_ID + if ((id->minor_rev_num && id->minor_rev_num <= 31) || (id->major_rev_num && id->minor_rev_num <= 31)) + { + printf("\n Drive conforms to: "); + if_else_printf((id->minor_rev_num <= 31),"%s: ","unknown: ", minor_str[id->minor_rev_num]); + if (id->major_rev_num < 31) + { + for (i=0; i <= 15; i++) + if_printf((id->major_rev_num & (1< 0; --i) + { + if (seek_to_zero (fd)) + goto quit; + if (read_big_block (fd, buf)) + goto quit; + } + getitimer(ITIMER_REAL, &e2); + correction = (e1.it_value.tv_sec - e2.it_value.tv_sec) + ((e1.it_value.tv_usec - e2.it_value.tv_usec) / 1000000.0); + + /* Now remove the lseek() from the correction factor */ + getitimer(ITIMER_REAL, &e1); + for (i = (BUFCACHE_FACTOR * TIMING_BUF_COUNT) ; i > 0; --i) + { + if (seek_to_zero (fd)) + goto quit; + } + getitimer(ITIMER_REAL, &e2); + correction -= (e1.it_value.tv_sec - e2.it_value.tv_sec) + + ((e1.it_value.tv_usec - e2.it_value.tv_usec) / 1000000.0); + + if ((BUFCACHE_FACTOR * timing_MB) >= correction) /* more than 1MB/s */ + printf("%2d MB in %5.2f seconds =%6.2f MB/sec\n", + (BUFCACHE_FACTOR * timing_MB), correction, + (BUFCACHE_FACTOR * timing_MB) / correction); + else + printf("%2d MB in %5.2f seconds =%6.2f kB/sec\n", + (BUFCACHE_FACTOR * timing_MB), correction, + (BUFCACHE_FACTOR * timing_MB) / correction * 1024); + correction /= BUFCACHE_FACTOR; + + flush_buffer_cache(fd); + sleep(1); + } + else /* Time device */ + { + printf(" Timing buffered disk reads: "); + fflush(stdout); + + /* + * getitimer() is used rather than gettimeofday() because + * it is much more consistent (on my machine, at least). + */ + setitimer(ITIMER_REAL, &(struct itimerval){{1000,0},{1000,0}}, NULL); + + /* Now do the timings for real */ + getitimer(ITIMER_REAL, &e1); + for (i = TIMING_BUF_COUNT; i > 0; --i) + { + if (read_big_block (fd, buf)) + goto quit; + } + getitimer(ITIMER_REAL, &e2); + + elapsed = (e1.it_value.tv_sec - e2.it_value.tv_sec) + ((e1.it_value.tv_usec - e2.it_value.tv_usec) / 1000000.0); + + if (timing_MB >= elapsed) /* more than 1MB/s */ + printf("%2d MB in %5.2f seconds =%6.2f MB/sec\n",timing_MB, elapsed, timing_MB / elapsed); + else + printf("%2d MB in %5.2f seconds =%6.2f kB/sec\n",timing_MB, elapsed, timing_MB / elapsed * 1024); + + /*"Hmm.. suspicious results: probably not enough free memory for a proper test.");*/ + if (elapsed <= (correction * 2)) + bb_error_msg(bb_msg_memory_exhausted); + +#if 0 /* the "estimate" is just plain wrong for many systems.. */ + else if (correction != 0.0) { + printf(" Estimating raw driver speed: "); + elapsed -= correction; + if (timing_MB >= elapsed) /* more than 1MB/s */ + printf("%2d MB in %5.2f seconds =%6.2f MB/sec\n", + timing_MB, elapsed, timing_MB / elapsed); + else + printf("%2d MB in %5.2f seconds =%6.2f kB/sec\n", + timing_MB, elapsed, timing_MB / elapsed * 1024); + } +#endif + } +quit: + if (-1 == shmdt(buf)) + bb_error_msg (bb_msg_shared_mem,"detach"); /*"could not detach sharedmem buf"*/ +} + + +static void no_scsi (void) +{ + /*" operation not supported on SCSI disks"*/ + if (is_scsi_hd) + bb_error_msg_and_die(bb_msg_op_not_supp,"SCSI"); +} + +static void no_xt (void) +{ + if (is_xt_hd) + bb_error_msg_and_die(bb_msg_op_not_supp,"XT"); +} + +static void on_off (unsigned int value) +{ + printf(value ? " (on)\n" : " (off)\n"); +} + +#ifdef CONFIG_FEATURE_HDPARM_HDIO_TRISTATE_HWIF +static void bus_state_value (unsigned int value) +{ + const char *string; + + switch (value) + { + case BUSSTATE_ON: + string = " (on)\n"; + break; + case BUSSTATE_OFF: + string = " (off)\n"; + break; + case BUSSTATE_TRISTATE: + string = " (tristate)\n"; + break; + default: + string = " (unknown: %d)\n"; + break; + } + printf(string, value); +} +#endif + +#ifdef HDIO_DRIVE_CMD +static void interpret_standby (unsigned int standby) +{ + printf(" ("); + switch(standby) + { + case 0: + printf("off"); + break; + case 252: + printf("21 minutes"); + break; + case 253: + printf("vendor-specific"); + break; + case 254: + printf("?reserved"); + break; + case 255: + printf("21 minutes + 15 seconds"); + break; + default: + if (standby <= 240) + { + unsigned int secs = standby * 5; + unsigned int mins = secs / 60; + secs %= 60; + if_printf(mins,"%u minutes", mins); + if_printf((mins && secs)," + "); + if_printf(secs,"%u seconds", secs); + } + else if (standby <= 251) + { + unsigned int mins = (standby - 240) * 30; + unsigned int hrs = mins / 60; + mins %= 60; + if_printf(hrs,"%u hours", hrs); + if_printf((hrs && mins)," + "); + if_printf(mins,"%u minutes", mins); + } + else + printf("illegal value"); + break; + } + printf(")\n"); +} + +struct xfermode_entry { + int val; + const char *name; +}; + +static const struct xfermode_entry xfermode_table[] = { + { 8, "pio0" }, + { 9, "pio1" }, + { 10, "pio2" }, + { 11, "pio3" }, + { 12, "pio4" }, + { 13, "pio5" }, + { 14, "pio6" }, + { 15, "pio7" }, + { 16, "sdma0" }, + { 17, "sdma1" }, + { 18, "sdma2" }, + { 19, "sdma3" }, + { 20, "sdma4" }, + { 21, "sdma5" }, + { 22, "sdma6" }, + { 23, "sdma7" }, + { 32, "mdma0" }, + { 33, "mdma1" }, + { 34, "mdma2" }, + { 35, "mdma3" }, + { 36, "mdma4" }, + { 37, "mdma5" }, + { 38, "mdma6" }, + { 39, "mdma7" }, + { 64, "udma0" }, + { 65, "udma1" }, + { 66, "udma2" }, + { 67, "udma3" }, + { 68, "udma4" }, + { 69, "udma5" }, + { 70, "udma6" }, + { 71, "udma7" }, + { 0, NULL } +}; + +static int translate_xfermode(char * name) +{ + const struct xfermode_entry *tmp; + char *endptr; + int val = -1; + + + for (tmp = xfermode_table; tmp->name != NULL; ++tmp) + { + if (!strcmp(name, tmp->name)) + return tmp->val; + + } + + val = strtol(name, &endptr, 10); + if (*endptr == '\0') + return val; + + return -1; +} + +static void interpret_xfermode (unsigned int xfermode) +{ + printf(" ("); + switch(xfermode) { + case 0: + printf("default PIO mode"); + break; + case 1: + printf("default PIO mode, disable IORDY"); + break; + case 8: + case 9: + case 10: + case 11: + case 12: + case 13: + case 14: + case 15: + printf("PIO flow control mode%u", xfermode-8); + break; + case 16: + case 17: + case 18: + case 19: + case 20: + case 21: + case 22: + case 23: + printf("singleword DMA mode%u", xfermode-16); + break; + case 32: + case 33: + case 34: + case 35: + case 36: + case 37: + case 38: + case 39: + printf("multiword DMA mode%u", xfermode-32); + break; + case 64: + case 65: + case 66: + case 67: + case 68: + case 69: + case 70: + case 71: + printf("UltraDMA mode%u", xfermode-64); + break; + default: + printf("unknown, probably not valid"); + break; + } + printf(")\n"); +} +#endif /* HDIO_DRIVE_CMD */ + +#ifndef VXVM_MAJOR +#define VXVM_MAJOR 199 +#endif + +#ifndef CCISS_MAJOR +#define CCISS_MAJOR 104 +#endif + +static void process_dev (char *devname) +{ + int fd; + static long parm, multcount; + struct stat stat_buf; +#ifndef HDIO_DRIVE_CMD + int force_operation = 0; +#endif + if (stat(devname,&stat_buf)) + bb_perror_msg_and_die(devname); + + switch(major(stat_buf.st_rdev)) + { +#ifdef SCSI_DISK0_MAJOR + case (SCSI_DISK0_MAJOR): + case (SCSI_DISK1_MAJOR): + case (SCSI_DISK2_MAJOR): + case (SCSI_DISK3_MAJOR): + case (SCSI_DISK4_MAJOR): + case (SCSI_DISK5_MAJOR): + case (SCSI_DISK6_MAJOR): + case (SCSI_DISK7_MAJOR): +#else + case (SCSI_DISK_MAJOR): +#endif +#ifdef MD_MAJOR + case (MD_MAJOR): +#endif + case (VXVM_MAJOR): +#ifdef LVM_BLK_MAJOR + case (LVM_BLK_MAJOR): +#endif + case (CCISS_MAJOR): + is_scsi_hd = 1; + break; +#ifdef XT_DISK_MAJOR + case (XT_DISK_MAJOR): + is_xt_hd = 1; + break; +#endif + case IDE0_MAJOR: + case IDE1_MAJOR: +#ifdef IDE2_MAJOR + case IDE2_MAJOR: +#endif +#ifdef IDE3_MAJOR + case IDE3_MAJOR: +#endif +#ifdef IDE4_MAJOR + case IDE4_MAJOR: +#endif +#ifdef IDE5_MAJOR + case IDE5_MAJOR: +#endif +#ifdef IDE6_MAJOR + case IDE6_MAJOR: +#endif +#ifdef IDE7_MAJOR + case IDE7_MAJOR: +#endif +#ifdef IDE8_MAJOR + case IDE8_MAJOR: +#endif +#ifdef IDE9_MAJOR + case IDE9_MAJOR: +#endif + break; /* do nothing */ + default: + bb_error_msg_and_die("%s not supported",devname); + } + + fd = bb_xopen (devname, O_RDONLY|O_NONBLOCK); + if_printf( (!quiet),"\n%s:\n", devname); + + if (set_readahead) + { + if_printf(get_readahead," setting fs readahead to %ld\n", Xreadahead); + bb_ioctl(fd, BLKRASET,(int *)Xreadahead,"BLKRASET"); + } +#ifdef CONFIG_FEATURE_HDPARM_HDIO_UNREGISTER_HWIF + if (unregister_hwif) + { + no_scsi(); + printf(" attempting to unregister hwif#%u\n", hwif); + bb_ioctl(fd, HDIO_UNREGISTER_HWIF,(int *)hwif,"HDIO_UNREGISTER_HWIF"); + } +#endif +#ifdef CONFIG_FEATURE_HDPARM_HDIO_SCAN_HWIF + if (scan_hwif) + { + int args[3]; + no_scsi(); + printf(" attempting to scan hwif (0x%x, 0x%x, %u)\n", hwif_data, hwif_ctrl, hwif_irq); + args[0] = hwif_data; + args[1] = hwif_ctrl; + args[2] = hwif_irq; + bb_ioctl(fd, HDIO_SCAN_HWIF, args, "HDIO_SCAN_HWIF"); + } +#endif + if (set_piomode) + { + no_scsi(); + no_xt(); + + if (noisy_piomode) + { + printf(" attempting to "); + if (piomode == 255) + printf("auto-tune PIO mode\n"); + else if (piomode < 100) + printf("set PIO mode to %d\n", piomode); + else if (piomode < 200) + printf("set MDMA mode to %d\n", (piomode-100)); + else + printf("set UDMA mode to %d\n", (piomode-200)); + } + bb_ioctl(fd, HDIO_SET_PIO_MODE, (int *)piomode, "HDIO_SET_PIO_MODE"); + } + if (set_io32bit) + { + no_scsi(); + no_xt(); + if_printf(get_io32bit," setting 32-bit IO_support flag to %ld\n", io32bit); + bb_ioctl(fd, HDIO_SET_32BIT, (int *)io32bit, "HDIO_SET_32BIT"); + } + if (set_mult) + { + no_scsi(); + no_xt(); + if_printf(get_mult, " setting multcount to %ld\n", mult); + if(ioctl(fd, HDIO_SET_MULTCOUNT, mult)) + bb_perror_msg("HDIO_SET_MULTCOUNT"); +#ifndef HDIO_DRIVE_CMD + else + force_operation = 1; +#endif + } + if (set_readonly) + { + if_printf_on_off(get_readonly," setting readonly to %ld", readonly); + bb_ioctl(fd, BLKROSET, &readonly, "BLKROSET"); + } + if (set_unmask) + { + no_scsi(); + no_xt(); + if_printf_on_off(get_unmask," setting unmaskirq to %ld", unmask); + bb_ioctl(fd, HDIO_SET_UNMASKINTR, (int *)unmask, "HDIO_SET_UNMASKINTR"); + } +#ifdef CONFIG_FEATURE_HDPARM_HDIO_GETSET_DMA + if (set_dma) + { + no_scsi(); + if_printf_on_off(get_dma," setting using_dma to %ld", dma); + bb_ioctl(fd, HDIO_SET_DMA, (int *)dma, "HDIO_SET_DMA"); + } +#endif /* CONFIG_FEATURE_HDPARM_HDIO_GETSET_DMA */ + if (set_dma_q) + { + no_scsi(); + if_printf_on_off(get_dma_q," setting DMA queue_depth to %ld", dma_q); + bb_ioctl(fd, HDIO_SET_QDMA, (int *)dma_q, "HDIO_SET_QDMA"); + } + if (set_nowerr) + { + no_scsi(); + no_xt(); + if_printf_on_off(get_nowerr," setting nowerr to %ld", nowerr); + bb_ioctl(fd, HDIO_SET_NOWERR, (int *)nowerr,"HDIO_SET_NOWERR"); + } + if (set_keep) + { + no_scsi(); + no_xt(); + if_printf_on_off(get_keep," setting keep_settings to %ld", keep); + bb_ioctl(fd, HDIO_SET_KEEPSETTINGS, (int *)keep,"HDIO_SET_KEEPSETTINGS"); + } +#ifdef HDIO_DRIVE_CMD + if (set_doorlock) + { + unsigned char args[4] = {0,0,0,0}; + no_scsi(); + no_xt(); + + args[0] = doorlock ? WIN_DOORLOCK : WIN_DOORUNLOCK; + if_printf_on_off(get_doorlock," setting drive doorlock to %ld", doorlock); + bb_ioctl(fd, HDIO_DRIVE_CMD, &args,"HDIO_DRIVE_CMD(doorlock)"); + } + if (set_dkeep) + { + /* lock/unlock the drive's "feature" settings */ + unsigned char args[4] = {WIN_SETFEATURES,0,0,0}; + no_scsi(); + no_xt(); + + if_printf_on_off(get_dkeep," setting drive keep features to %ld", dkeep); + args[2] = dkeep ? 0x66 : 0xcc; + bb_ioctl(fd, HDIO_DRIVE_CMD, &args,"HDIO_DRIVE_CMD(keepsettings)"); + } + if (set_defects) + { + unsigned char args[4] = {WIN_SETFEATURES,0,0x04,0}; + no_scsi(); + args[2] = defects ? 0x04 : 0x84; + if_printf(get_defects," setting drive defect-mgmt to %ld\n", defects); + bb_ioctl(fd, HDIO_DRIVE_CMD, &args,"HDIO_DRIVE_CMD(defectmgmt)"); + } + if (set_prefetch) + { + unsigned char args[4] = {WIN_SETFEATURES,0,0xab,0}; + no_scsi(); + no_xt(); + + args[1] = prefetch; + if_printf(get_prefetch," setting drive prefetch to %ld\n", prefetch); + bb_ioctl(fd, HDIO_DRIVE_CMD, &args, "HDIO_DRIVE_CMD(setprefetch)"); + } + if (set_xfermode) + { + unsigned char args[4] = {WIN_SETFEATURES,0,3,0}; + no_scsi(); + no_xt(); + + args[1] = xfermode_requested; + if (get_xfermode) + { + printf(" setting xfermode to %d", xfermode_requested); + interpret_xfermode(xfermode_requested); + } + bb_ioctl(fd, HDIO_DRIVE_CMD, &args,"HDIO_DRIVE_CMD(setxfermode)"); + } + if (set_lookahead) + { + unsigned char args[4] = {WIN_SETFEATURES,0,0,0}; + no_scsi(); + no_xt(); + + args[2] = lookahead ? 0xaa : 0x55; + if_printf_on_off(get_lookahead," setting drive read-lookahead to %ld", lookahead); + bb_ioctl(fd, HDIO_DRIVE_CMD, &args, "HDIO_DRIVE_CMD(setreadahead)"); + } + if (set_apmmode) + { + unsigned char args[4] = {WIN_SETFEATURES,0,0,0}; + no_scsi(); + apmmode=check_if_min_and_set_val(apmmode,1); + apmmode=check_if_maj_and_set_val(apmmode,255); + if_printf(get_apmmode," setting APM level to"); + if (apmmode==255) + { + /* disable Advanced Power Management */ + args[2] = 0x85; /* feature register */ + if_printf(get_apmmode," disabled\n"); + } + else + { + /* set Advanced Power Management mode */ + args[2] = 0x05; /* feature register */ + args[1] = apmmode; /* sector count register */ + if_printf(get_apmmode," 0x%02lX (%ld)\n",apmmode,apmmode); + } + bb_ioctl(fd, HDIO_DRIVE_CMD, &args,"HDIO_DRIVE_CMD"); + } + if (set_wcache) + { +#ifdef DO_FLUSHCACHE +#ifndef WIN_FLUSHCACHE +#define WIN_FLUSHCACHE 0xe7 +#endif + unsigned char flushcache[4] = {WIN_FLUSHCACHE,0,0,0}; +#endif /* DO_FLUSHCACHE */ + unsigned char args[4] = {WIN_SETFEATURES,0,0,0}; + no_scsi(); + no_xt(); + args[2] = wcache ? 0x02 : 0x82; + if_printf_on_off(get_wcache," setting drive write-caching to %ld", wcache); +#ifdef DO_FLUSHCACHE + if (!wcache && ioctl(fd, HDIO_DRIVE_CMD, &flushcache)) + bb_perror_msg ("HDIO_DRIVE_CMD(flushcache)"); +#endif /* DO_FLUSHCACHE */ + bb_ioctl(fd, HDIO_DRIVE_CMD, &args, "HDIO_DRIVE_CMD(setcache)"); +#ifdef DO_FLUSHCACHE + if (!wcache && ioctl(fd, HDIO_DRIVE_CMD, &flushcache)) + bb_perror_msg ("HDIO_DRIVE_CMD(flushcache)"); +#endif /* DO_FLUSHCACHE */ + } + if (set_standbynow) + { +#ifndef WIN_STANDBYNOW1 +#define WIN_STANDBYNOW1 0xE0 +#endif +#ifndef WIN_STANDBYNOW2 +#define WIN_STANDBYNOW2 0x94 +#endif + unsigned char args1[4] = {WIN_STANDBYNOW1,0,0,0}; + unsigned char args2[4] = {WIN_STANDBYNOW2,0,0,0}; + no_scsi(); + if_printf(get_standbynow," issuing standby command\n"); + if (ioctl(fd, HDIO_DRIVE_CMD, &args1) + && ioctl(fd, HDIO_DRIVE_CMD, &args2)) + bb_perror_msg("HDIO_DRIVE_CMD(standby)"); + } + if (set_sleepnow) + { +#ifndef WIN_SLEEPNOW1 +#define WIN_SLEEPNOW1 0xE6 +#endif +#ifndef WIN_SLEEPNOW2 +#define WIN_SLEEPNOW2 0x99 +#endif + unsigned char args1[4] = {WIN_SLEEPNOW1,0,0,0}; + unsigned char args2[4] = {WIN_SLEEPNOW2,0,0,0}; + no_scsi(); + if_printf(get_sleepnow," issuing sleep command\n"); + if (ioctl(fd, HDIO_DRIVE_CMD, &args1) + && ioctl(fd, HDIO_DRIVE_CMD, &args2)) + bb_perror_msg("HDIO_DRIVE_CMD(sleep)"); + } + if (set_seagate) + { + unsigned char args[4] = {0xfb,0,0,0}; + no_scsi(); + no_xt(); + if_printf(get_seagate," disabling Seagate auto powersaving mode\n"); + bb_ioctl(fd, HDIO_DRIVE_CMD, &args, "HDIO_DRIVE_CMD(seagatepwrsave)"); + } + if (set_standby) + { + unsigned char args[4] = {WIN_SETIDLE1,standby_requested,0,0}; + no_scsi(); + no_xt(); + if (get_standby) + { + printf(" setting standby to %lu", standby_requested); + interpret_standby(standby_requested); + } + bb_ioctl(fd, HDIO_DRIVE_CMD, &args, "HDIO_DRIVE_CMD(setidle1)"); + } +#else /* HDIO_DRIVE_CMD */ + if (force_operation) + { + char buf[512]; + flush_buffer_cache(fd); + if (-1 == read(fd, buf, sizeof(buf))) + bb_error_msg("access failed"); + } +#endif /* HDIO_DRIVE_CMD */ + + if (!flagcount) + verbose = 1; + + if ((verbose && !is_scsi_hd && !is_xt_hd) || get_mult || get_identity) + { + no_scsi(); + multcount = -1; + if (ioctl(fd, HDIO_GET_MULTCOUNT, &multcount)) + { + if ((verbose && !is_xt_hd) || get_mult) + bb_perror_msg("HDIO_GET_MULTCOUNT"); + } + else if (verbose | get_mult) + { + printf(" multcount = %2ld", multcount); + on_off(multcount); + } + } + if ((verbose && !is_scsi_hd && !is_xt_hd) || get_io32bit) + { + no_scsi(); + no_xt(); + if(ioctl(fd, HDIO_GET_32BIT, &parm)) + bb_perror_msg("HDIO_GET_32BIT"); + else + { + printf(" IO_support =%3ld (", parm); + switch (parm) + { + case 0: + printf("default "); + case 2: + printf("16-bit)\n"); + break; + case 1: + printf("32-bit)\n"); + break; + case 3: + printf("32-bit w/sync)\n"); + break; + case 8: + printf("Request-Queue-Bypass)\n"); + break; + default: + printf("\?\?\?)\n"); + /*esac*/ + } + } + } + if ((verbose && !is_scsi_hd && !is_xt_hd) || get_unmask) + { + no_scsi(); + no_xt(); + bb_ioctl_on_off(fd, HDIO_GET_UNMASKINTR,(unsigned long *)parm, + "HDIO_GET_UNMASKINTR"," unmaskirq = %2ld"); + } + + +#ifdef CONFIG_FEATURE_HDPARM_HDIO_GETSET_DMA + if ((verbose && !is_scsi_hd) || get_dma) { + no_scsi(); + if(ioctl(fd, HDIO_GET_DMA, &parm)) + bb_perror_msg("HDIO_GET_DMA"); + else + { + printf(" using_dma = %2ld", parm); + if (parm == 8) + printf(" (DMA-Assisted-PIO)\n"); + else + on_off(parm); + } + } +#endif + if (get_dma_q) + { + no_scsi(); + bb_ioctl_on_off (fd, HDIO_GET_QDMA,(unsigned long *)parm, + "HDIO_GET_QDMA"," queue_depth = %2ld"); + } + if ((verbose && !is_scsi_hd && !is_xt_hd) || get_keep) + { + no_scsi(); + no_xt(); + bb_ioctl_on_off (fd, HDIO_GET_KEEPSETTINGS,(unsigned long *)parm, + "HDIO_GET_KEEPSETTINGS"," keepsettings = %2ld"); + } + + if (get_nowerr) + { + no_scsi(); + no_xt(); + bb_ioctl_on_off (fd, HDIO_GET_NOWERR,(unsigned long *)&parm, + " HDIO_GET_NOWERR"," nowerr = %2ld"); + } + if (verbose || get_readonly) + { + bb_ioctl_on_off(fd, BLKROGET,(unsigned long *)parm, + " BLKROGET"," readonly = %2ld"); + } + if ((verbose && !is_scsi_hd) || get_readahead) + { + bb_ioctl_on_off (fd, BLKRAGET, (unsigned long *) parm, + " BLKRAGET"," readahead = %2ld"); + } + if (verbose || get_geom) + { + static const char msg[] = " geometry = %u/%u/%u, sectors = %ld, start = %ld\n"; + static struct hd_geometry g; +#ifdef HDIO_GETGEO_BIG + static struct hd_big_geometry bg; +#endif + + if (ioctl(fd, BLKGETSIZE, &parm)) + bb_perror_msg("BLKGETSIZE"); +#ifdef HDIO_GETGEO_BIG + else if (!ioctl(fd, HDIO_GETGEO_BIG, &bg)) + printf(msg, bg.cylinders, bg.heads, bg.sectors, parm, bg.start); +#endif + else if (ioctl(fd, HDIO_GETGEO, &g)) + bb_perror_msg("HDIO_GETGEO"); + else + printf(msg, g.cylinders, g.heads, g.sectors, parm, g.start); + } +#ifdef HDIO_DRIVE_CMD + if (get_powermode) + { +#ifndef WIN_CHECKPOWERMODE1 +#define WIN_CHECKPOWERMODE1 0xE5 +#endif +#ifndef WIN_CHECKPOWERMODE2 +#define WIN_CHECKPOWERMODE2 0x98 +#endif + unsigned char args[4] = {WIN_CHECKPOWERMODE1,0,0,0}; + const char *state; + no_scsi(); + if (ioctl(fd, HDIO_DRIVE_CMD, &args) + && (args[0] = WIN_CHECKPOWERMODE2) /* try again with 0x98 */ + && ioctl(fd, HDIO_DRIVE_CMD, &args)) + { + if (errno != EIO || args[0] != 0 || args[1] != 0) + state = "unknown"; + else + state = "sleeping"; + } + else + state = (args[2] == 255) ? "active/idle" : "standby"; + + printf(" drive state is: %s\n", state); + } +#endif +#ifdef CONFIG_FEATURE_HDPARM_HDIO_DRIVE_RESET + if (perform_reset) + { + no_scsi(); + no_xt(); + bb_ioctl(fd, HDIO_DRIVE_RESET, NULL, "HDIO_DRIVE_RESET"); + } +#endif /* CONFIG_FEATURE_HDPARM_HDIO_DRIVE_RESET */ +#ifdef CONFIG_FEATURE_HDPARM_HDIO_TRISTATE_HWIF + if (perform_tristate) + { + unsigned char args[4] = {0,tristate,0,0}; + no_scsi(); + no_xt(); + bb_ioctl(fd, HDIO_TRISTATE_HWIF, &args, "HDIO_TRISTATE_HWIF"); + } +#endif /* CONFIG_FEATURE_HDPARM_HDIO_TRISTATE_HWIF */ +#ifdef CONFIG_FEATURE_HDPARM_GET_IDENTITY + if (get_identity) + { + static struct hd_driveid id; + + no_scsi(); + no_xt(); + + if (!ioctl(fd, HDIO_GET_IDENTITY, &id)) + { + if (multcount != -1) + { + id.multsect = multcount; + id.multsect_valid |= 1; + } + else + id.multsect_valid &= ~1; + dump_identity(&id); + } + else if (errno == -ENOMSG) + printf(" no identification info available\n"); + else + bb_perror_msg("HDIO_GET_IDENTITY"); + } + + if (get_IDentity) + { + unsigned char args[4+512] = {WIN_IDENTIFY,0,0,1,}; + unsigned i; + + no_scsi(); + no_xt(); + + if (ioctl(fd, HDIO_DRIVE_CMD, &args)) + { + args[0] = WIN_PIDENTIFY; + if (ioctl(fd, HDIO_DRIVE_CMD, &args)) + { + bb_perror_msg("HDIO_DRIVE_CMD(identify)"); + goto identify_abort; + } + } + for(i=0; i<(sizeof args)/2; i+=2) + __le16_to_cpus((uint16_t *)(&args[i])); + + identify((void *)&args[4], NULL); +identify_abort: + /* VOID */; + } +#endif +#ifdef CONFIG_FEATURE_HDPARM_HDIO_TRISTATE_HWIF + if (set_busstate) + { + no_scsi(); + if (get_busstate) + { + printf(" setting bus state to %d", busstate); + bus_state_value(busstate); + } + bb_ioctl(fd, HDIO_SET_BUSSTATE, (int *)busstate, "HDIO_SET_BUSSTATE"); + } +#endif +#ifdef CONFIG_FEATURE_HDPARM_HDIO_TRISTATE_HWIF + if (get_busstate) + { + no_scsi(); + if (ioctl(fd, HDIO_GET_BUSSTATE, &parm)) + bb_perror_msg("HDIO_GET_BUSSTATE"); + else + { + printf(" busstate = %2ld", parm); + bus_state_value(parm); + } + } +#endif + if (reread_partn) + bb_ioctl(fd, BLKRRPART, NULL, "BLKRRPART"); + + + if (do_ctimings) + do_time(0,fd); /*time cache */ + if (do_timings) + do_time(1,fd); /*time device */ + if (do_flush) + flush_buffer_cache (fd); + close (fd); +} + +static char * GET_NUMBER(char *p, unsigned long *flag, unsigned long *num) +{ + *num = 0; + while (isdigit(*p)) { + *flag = 1; + *num = (*num * 10) + (*p++ - '0'); + } + return p; +} + +static char * GET_STRING(char *p, unsigned long *flag, int *num) +{ + char *tmpstr; + char name[32]; + tmpstr = name; + tmpstr[0] = '\0'; + while (isalnum(*p) && (tmpstr - name) < 31) { + tmpstr[0] = *p++; + tmpstr[1] = '\0'; + ++tmpstr; + } + *num = translate_xfermode(name); + if (*num == -1) + *flag = 0; + else + *flag = 1; + return p; +} + +#ifdef CONFIG_FEATURE_HDPARM_GET_IDENTITY +static int fromhex (unsigned char c) +{ + if (c >= 'a' && c <= 'f') + return 10 + (c - 'a'); + if (c >= '0' && c <= '9') + return (c - '0'); + bb_error_msg_and_die("bad char: '%c' 0x%02x", c, c); +} + +static int identify_from_stdin (void) +{ + unsigned short sbuf[800]; + unsigned char buf[1600], *b = (unsigned char *)buf; + int i, count = read(0, buf, 1280); + + if (count != 1280) + bb_error_msg_and_die("read(1280 bytes) failed (rc=%d)", count); + for (i = 0; count >= 4; ++i) + { + sbuf[i] = (fromhex(b[0]) << 12) | (fromhex(b[1]) << 8) | (fromhex(b[2]) << 4) | fromhex(b[3]); + __le16_to_cpus((uint16_t *)(&sbuf[i])); + b += 5; + count -= 5; + } + identify(sbuf, NULL); + return 0; +} +#endif + +static void missing_arg(int arg, char c, char* add) +{ + if (!arg) + bb_error_msg("-%c: missing value %s", c, (add!=NULL)? add :""); +} + +/* our main() routine: */ +int hdparm_main(int argc, char **argv) +{ + char c, *p; + + ++argv; + if (!--argc) + bb_show_usage(); + + while (argc--) + { +#ifdef CONFIG_FEATURE_HDPARM_GET_IDENTITY + if (!strcmp("-Istdin", *argv)) + { + exit(identify_from_stdin()); + } +#endif + p = *argv++; + if (*p == '-') + { + if (!*++p) + bb_show_usage(); + while ((c = *p++)) + { + ++flagcount; + switch (c) + { + case 'V': + /*bb_error_msg_and_die("%s", VERSION);*/ + /* We have to return 0 here and not 1 */ + printf("%s %s\n",bb_applet_name, VERSION); + exit(EXIT_SUCCESS); + case 'v': + verbose = 1; + break; +#ifdef CONFIG_FEATURE_HDPARM_GET_IDENTITY + case 'I': + get_IDentity = 1; + break; + case 'i': + get_identity = 1; + break; +#endif + case 'g': + get_geom = 1; + break; + case 'f': + do_flush = 1; + break; + case 'q': + quiet = 1; + noisy = 0; + break; + case 'u': + get_unmask = noisy; + noisy = 1; + if (!*p && argc && isdigit(**argv)) + p = *argv++, --argc; + if((set_unmask = set_flag(p,'1'))==1) + unmask = *p++ - '0'; + break; +#ifdef CONFIG_FEATURE_HDPARM_HDIO_GETSET_DMA + case 'd': + get_dma = noisy; + noisy = 1; + if (!*p && argc && isdigit(**argv)) + p = *argv++, --argc; + if((set_dma = set_flag(p,'9'))==1) + dma = *p++ - '0'; + break; +#endif /* CONFIG_FEATURE_HDPARM_HDIO_GETSET_DMA */ + case 'n': + get_nowerr = noisy; + noisy = 1; + if (!*p && argc && isdigit(**argv)) + p = *argv++, --argc; + if((set_nowerr = set_flag(p,'1'))==1) + nowerr = *p++ - '0'; + break; + case 'p': + noisy_piomode = noisy; + noisy = 1; + if (!*p && argc && isalnum(**argv)) + p = *argv++, --argc; + p=GET_STRING(p,&set_piomode,&piomode); + break; + case 'r': + get_readonly = noisy; + noisy = 1; + if (!*p && argc && isdigit(**argv)) + p = *argv++, --argc; + if((set_readonly = set_flag(p,'1'))==1) + readonly = *p++ - '0'; + break; + case 'm': + get_mult = noisy; + noisy = 1; + if (!*p && argc && isalnum(**argv)) + p = *argv++, --argc; + p=GET_NUMBER(p,&set_mult,&mult); + break; + case 'c': + get_io32bit = noisy; + noisy = 1; + if (!*p && argc && isalnum(**argv)) + p = *argv++, --argc; + p=GET_NUMBER(p,&set_io32bit,&io32bit); + break; +#ifdef HDIO_DRIVE_CMD + case 'S': + get_standby = noisy; + noisy = 1; + if (!*p && argc && isalnum(**argv)) + p = *argv++, --argc; + p=GET_NUMBER(p,&set_standby,&standby_requested); + missing_arg(set_standby, c, NULL); + break; + + case 'D': + get_defects = noisy; + noisy = 1; + if (!*p && argc && isalnum(**argv)) + p = *argv++, --argc; + p=GET_NUMBER(p,&set_defects,&defects); + missing_arg(set_defects, c, NULL); + break; + case 'P': + get_prefetch = noisy; + noisy = 1; + if (!*p && argc && isalnum(**argv)) + p = *argv++, --argc; + p=GET_NUMBER(p,&set_prefetch,&prefetch); + missing_arg(set_prefetch, c, NULL); + break; + + case 'X': + get_xfermode = noisy; + noisy = 1; + if (!*p && argc && isalnum(**argv)) + p = *argv++, --argc; + p=GET_STRING(p,&set_xfermode,&xfermode_requested); + missing_arg(set_xfermode, c, NULL); + break; + + case 'K': + get_dkeep = noisy; + noisy = 1; + if (!*p && argc && isdigit(**argv)) + p = *argv++, --argc; + if((set_dkeep = set_flag(p,'1'))==1) + dkeep = *p++ - '0'; + else + goto missing_arg_error; + break; + + case 'A': + get_lookahead = noisy; + noisy = 1; + if (!*p && argc && isdigit(**argv)) + p = *argv++, --argc; + if((set_lookahead = set_flag(p,'1'))==1) + lookahead = *p++ - '0'; + else + goto missing_arg_error; + break; + + case 'L': + get_doorlock = noisy; + noisy = 1; + if (!*p && argc && isdigit(**argv)) + p = *argv++, --argc; + if((set_doorlock = set_flag(p,'1'))==1) + doorlock = *p++ - '0'; + else + goto missing_arg_error; + break; + + case 'W': + get_wcache = noisy; + noisy = 1; + if (!*p && argc && isdigit(**argv)) + p = *argv++, --argc; + if((set_wcache = set_flag(p,'1'))==1) + wcache = *p++ - '0'; + else +missing_arg_error: + missing_arg(1, c, "(0/1)"); + break; + + case 'C': + get_powermode = noisy; + noisy = 1; + break; + + case 'y': + get_standbynow = noisy; + noisy = 1; + set_standbynow = 1; + break; + + case 'Y': + get_sleepnow = noisy; + noisy = 1; + set_sleepnow = 1; + break; + + case 'z': + reread_partn = 1; + break; + + case 'Z': + get_seagate = noisy; + noisy = 1; + set_seagate = 1; + break; +#endif /* HDIO_DRIVE_CMD */ + case 'k': + get_keep = noisy; + noisy = 1; + if (!*p && argc && isdigit(**argv)) + p = *argv++, --argc; + if((set_keep = set_flag(p,'1'))==1) + keep = *p++ - '0'; + break; +#ifdef CONFIG_FEATURE_HDPARM_HDIO_UNREGISTER_HWIF + case 'U': + if (!*p && argc && isdigit(**argv)) + p = *argv++, --argc; + if(! p) + goto expected_hwif_error; /* "expected hwif_nr" */ + + sscanf(p++, "%i", &hwif); + + unregister_hwif = 1; + break; +#endif /* CONFIG_FEATURE_HDPARM_HDIO_UNREGISTER_HWIF */ +#ifdef CONFIG_FEATURE_HDPARM_HDIO_SCAN_HWIF + case 'R': + if (!*p && argc && isdigit(**argv)) + p = *argv++, --argc; + if(! p) + goto expected_hwif_error; /* "expected hwif_data" */ + + sscanf(p++, "%i", &hwif_data); + + if (argc && isdigit(**argv)) + p = *argv++, --argc; + else + goto expected_hwif_error; /* "expected hwif_ctrl" */ + + sscanf(p, "%i", &hwif_ctrl); + + if (argc && isdigit(**argv)) + p = *argv++, --argc; + else +expected_hwif_error: + bb_error_msg_and_die("expected hwif value"); /* "expected hwif_irq" */ + + sscanf(p, "%i", &hwif_irq); + + *p = '\0'; + + scan_hwif = 1; + break; +#endif /* CONFIG_FEATURE_HDPARM_HDIO_SCAN_HWIF */ + case 'Q': +#ifdef HDIO_GET_QDMA + get_dma_q = noisy; + noisy = 1; +#ifdef HDIO_SET_QDMA + if (!*p && argc && isalnum(**argv)) + p = *argv++, --argc; + p=GET_NUMBER(p,&set_dma_q,&dma_q); +#ifdef HDIO_GET_QDMA + dma_q = -dma_q; +#endif +#endif +#endif + break; + +#ifdef CONFIG_FEATURE_HDPARM_HDIO_DRIVE_RESET + case 'w': + perform_reset = 1; + break; +#endif /* CONFIG_FEATURE_HDPARM_HDIO_DRIVE_RESET */ +#ifdef CONFIG_FEATURE_HDPARM_HDIO_TRISTATE_HWIF + case 'x': + if (!*p && argc && isdigit(**argv)) + p = *argv++, --argc; + if((perform_tristate = set_flag(p,'1'))==1) + tristate = *p++ - '0'; + else + missing_arg(1, c, "(0/1)"); + break; + +#endif /* CONFIG_FEATURE_HDPARM_HDIO_TRISTATE_HWIF */ + case 'a': + get_readahead = noisy; + noisy = 1; + if (!*p && argc && isalnum(**argv)) + p = *argv++, --argc; + p=GET_NUMBER(p,&set_readahead,&Xreadahead); + break; + case 'B': + get_apmmode = noisy; + noisy = 1; + if (!*p && argc && isalnum(**argv)) + p = *argv++, --argc; + p=GET_NUMBER(p,&set_apmmode,&apmmode); + missing_arg(set_apmmode, c, "(1-255)"); + break; + case 't': + do_timings = 1; + do_flush = 1; + break; + case 'T': + do_ctimings = 1; + do_flush = 1; + break; +#ifdef CONFIG_FEATURE_HDPARM_HDIO_TRISTATE_HWIF + case 'b': + get_busstate = noisy; + noisy = 1; + if (!*p && argc && isdigit(**argv)) + p = *argv++, --argc; + if((set_busstate = set_flag(p,'2'))==1) + busstate = *p++ - '0'; + break; +#endif + case 'h': + default: + bb_show_usage(); + } + } + if (!argc) + bb_show_usage(); + } else { + process_dev (p); + } + } + return 0 ; +} diff --git a/busybox/miscutils/last.c b/busybox/miscutils/last.c new file mode 100644 index 0000000..86613bf --- /dev/null +++ b/busybox/miscutils/last.c @@ -0,0 +1,107 @@ +/* vi: set sw=4 ts=4: */ +/* + * last implementation for busybox + * + * Copyright (C) 2003-2004 by Erik Andersen + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "busybox.h" + +#ifndef SHUTDOWN_TIME +# define SHUTDOWN_TIME 254 +#endif + +/* Grr... utmp char[] members do not have to be nul-terminated. + * Do what we can while still keeping this reasonably small. + * Note: We are assuming the ut_id[] size is fixed at 4. */ + +#if (UT_LINESIZE != 32) || (UT_NAMESIZE != 32) || (UT_HOSTSIZE != 256) +#error struct utmp member char[] size(s) have changed! +#endif + +extern int last_main(int argc, char **argv) +{ + struct utmp ut; + int n, file = STDIN_FILENO; + + if (argc > 1) { + bb_show_usage(); + } + file = bb_xopen(_PATH_WTMP, O_RDONLY); + + printf("%-10s %-14s %-18s %-12.12s %s\n", "USER", "TTY", "HOST", "LOGIN", "TIME"); + while ((n = safe_read(file, (void*)&ut, sizeof(struct utmp))) != 0) { + + if (n != sizeof(struct utmp)) { + bb_perror_msg_and_die("short read"); + } + + if (strncmp(ut.ut_line, "~", 1) == 0) { + if (strncmp(ut.ut_user, "shutdown", 8) == 0) + ut.ut_type = SHUTDOWN_TIME; + else if (strncmp(ut.ut_user, "reboot", 6) == 0) + ut.ut_type = BOOT_TIME; + else if (strncmp(ut.ut_user, "runlevel", 7) == 0) + ut.ut_type = RUN_LVL; + } else { + if (!ut.ut_name[0] || strcmp(ut.ut_name, "LOGIN") == 0 || + ut.ut_name[0] == 0) + { + /* Don't bother. This means we can't find how long + * someone was logged in for. Oh well. */ + continue; + } + if (ut.ut_type != DEAD_PROCESS && + ut.ut_name[0] && ut.ut_line[0]) + { + ut.ut_type = USER_PROCESS; + } + if (strcmp(ut.ut_name, "date") == 0) { + if (ut.ut_line[0] == '|') ut.ut_type = OLD_TIME; + if (ut.ut_line[0] == '{') ut.ut_type = NEW_TIME; + } + } + + if (ut.ut_type!=USER_PROCESS) { + switch (ut.ut_type) { + case OLD_TIME: + case NEW_TIME: + case RUN_LVL: + case SHUTDOWN_TIME: + continue; + case BOOT_TIME: + strcpy(ut.ut_line, "system boot"); + break; + } + } + + printf("%-10s %-14s %-18s %-12.12s\n", ut.ut_user, ut.ut_line, ut.ut_host, + ctime(&(ut.ut_tv.tv_sec)) + 4); + } + + bb_fflush_stdout_and_exit(EXIT_SUCCESS); +} diff --git a/busybox/miscutils/makedevs.c b/busybox/miscutils/makedevs.c new file mode 100644 index 0000000..54a2e00 --- /dev/null +++ b/busybox/miscutils/makedevs.c @@ -0,0 +1,93 @@ +/* vi: set sw=4 ts=4: */ +/* + * public domain -- Dave 'Kill a Cop' Cinege + * + * makedevs + * Make ranges of device files quickly. + * known bugs: can't deal with alpha ranges + */ + +#include +#include +#include +#include +#include +#include +#include /* major() and minor() */ +#include "busybox.h" + +int makedevs_main(int argc, char **argv) +{ + mode_t mode; + char *basedev, *type, *nodname, buf[255]; + int Smajor, Sminor, S, E; + + if (argc < 7 || *argv[1]=='-') + bb_show_usage(); + + basedev = argv[1]; + type = argv[2]; + Smajor = atoi(argv[3]); + Sminor = atoi(argv[4]); + S = atoi(argv[5]); + E = atoi(argv[6]); + nodname = argc == 8 ? basedev : buf; + + mode = 0660; + + switch (type[0]) { + case 'c': + mode |= S_IFCHR; + break; + case 'b': + mode |= S_IFBLK; + break; + case 'f': + mode |= S_IFIFO; + break; + default: + bb_show_usage(); + } + + while (S <= E) { + int sz; + + sz = snprintf(buf, sizeof(buf), "%s%d", basedev, S); + if(sz<0 || sz>=sizeof(buf)) /* libc different */ + bb_error_msg_and_die("%s too large", basedev); + + /* if mode != S_IFCHR and != S_IFBLK third param in mknod() ignored */ + + if (mknod(nodname, mode, makedev(Smajor, Sminor))) + bb_error_msg("Failed to create: %s", nodname); + + if (nodname == basedev) /* ex. /dev/hda - to /dev/hda1 ... */ + nodname = buf; + S++; + Sminor++; + } + + return 0; +} + +/* +And this is what this program replaces. The shell is too slow! + +makedev () { +local basedev=$1; local S=$2; local E=$3 +local major=$4; local Sminor=$5; local type=$6 +local sbase=$7 + + if [ ! "$sbase" = "" ]; then + mknod "$basedev" $type $major $Sminor + S=`expr $S + 1` + Sminor=`expr $Sminor + 1` + fi + + while [ $S -le $E ]; do + mknod "$basedev$S" $type $major $Sminor + S=`expr $S + 1` + Sminor=`expr $Sminor + 1` + done +} +*/ diff --git a/busybox/miscutils/mt.c b/busybox/miscutils/mt.c new file mode 100644 index 0000000..b0cdacc --- /dev/null +++ b/busybox/miscutils/mt.c @@ -0,0 +1,121 @@ +/* vi: set sw=4 ts=4: */ +#include +#include +#include +#include +#include +#include "busybox.h" + +struct mt_opcodes { + char *name; + short value; +}; + +/* missing: eod/seod, stoptions, stwrthreshold, densities */ +static const struct mt_opcodes opcodes[] = { + {"bsf", MTBSF}, + {"bsfm", MTBSFM}, + {"bsr", MTBSR}, + {"bss", MTBSS}, + {"datacompression", MTCOMPRESSION}, + {"eom", MTEOM}, + {"erase", MTERASE}, + {"fsf", MTFSF}, + {"fsfm", MTFSFM}, + {"fsr", MTFSR}, + {"fss", MTFSS}, + {"load", MTLOAD}, + {"lock", MTLOCK}, + {"mkpart", MTMKPART}, + {"nop", MTNOP}, + {"offline", MTOFFL}, + {"rewoffline", MTOFFL}, + {"ras1", MTRAS1}, + {"ras2", MTRAS2}, + {"ras3", MTRAS3}, + {"reset", MTRESET}, + {"retension", MTRETEN}, + {"rewind", MTREW}, + {"seek", MTSEEK}, + {"setblk", MTSETBLK}, + {"setdensity", MTSETDENSITY}, + {"drvbuffer", MTSETDRVBUFFER}, + {"setpart", MTSETPART}, + {"tell", MTTELL}, + {"wset", MTWSM}, + {"unload", MTUNLOAD}, + {"unlock", MTUNLOCK}, + {"eof", MTWEOF}, + {"weof", MTWEOF}, + {0, 0} +}; + +extern int mt_main(int argc, char **argv) +{ + const char *file = "/dev/tape"; + const struct mt_opcodes *code = opcodes; + struct mtop op; + struct mtpos position; + int fd, mode; + + if (argc < 2) { + bb_show_usage(); + } + + if (strcmp(argv[1], "-f") == 0) { + if (argc < 4) { + bb_show_usage(); + } + file = argv[2]; + argv += 2; + argc -= 2; + } + + while (code->name != 0) { + if (strcmp(code->name, argv[1]) == 0) + break; + code++; + } + + if (code->name == 0) { + bb_error_msg("unrecognized opcode %s.", argv[1]); + return EXIT_FAILURE; + } + + op.mt_op = code->value; + if (argc >= 3) + op.mt_count = atoi(argv[2]); + else + op.mt_count = 1; /* One, not zero, right? */ + + switch (code->value) { + case MTWEOF: + case MTERASE: + case MTWSM: + case MTSETDRVBUFFER: + mode = O_WRONLY; + break; + + default: + mode = O_RDONLY; + break; + } + + if ((fd = open(file, mode, 0)) < 0) + bb_perror_msg_and_die("%s", file); + + switch (code->value) { + case MTTELL: + if (ioctl(fd, MTIOCPOS, &position) < 0) + bb_perror_msg_and_die("%s", file); + printf ("At block %d.\n", (int) position.mt_blkno); + break; + + default: + if (ioctl(fd, MTIOCTOP, &op) != 0) + bb_perror_msg_and_die("%s", file); + break; + } + + return EXIT_SUCCESS; +} diff --git a/busybox/miscutils/rx.c b/busybox/miscutils/rx.c new file mode 100644 index 0000000..8edc887 --- /dev/null +++ b/busybox/miscutils/rx.c @@ -0,0 +1,344 @@ +/*------------------------------------------------------------------------- + * Filename: xmodem.c + * Version: $Id: rx.c,v 1.2 2004/03/15 08:28:46 andersen Exp $ + * Copyright: Copyright (C) 2001, Hewlett-Packard Company + * Author: Christopher Hoover + * Description: xmodem functionality for uploading of kernels + * and the like + * Created at: Thu Dec 20 01:58:08 PST 2001 + *-----------------------------------------------------------------------*/ +/* + * xmodem.c: xmodem functionality for uploading of kernels and + * the like + * + * Copyright (C) 2001 Hewlett-Packard Laboratories + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * + * This was originally written for blob and then adapted for busybox. + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "busybox.h" + + +#define SOH 0x01 +#define STX 0x02 +#define EOT 0x04 +#define ACK 0x06 +#define NAK 0x15 +#define CAN 0x18 +#define BS 0x08 + +/* + +Cf: + + http://www.textfiles.com/apple/xmodem + http://www.phys.washington.edu/~belonis/xmodem/docxmodem.txt + http://www.phys.washington.edu/~belonis/xmodem/docymodem.txt + http://www.phys.washington.edu/~belonis/xmodem/modmprot.col + +*/ + +#define TIMEOUT 1 +#define TIMEOUT_LONG 10 +#define MAXERRORS 10 + +static inline void write_byte(int fd, char cc) { + write(fd, &cc, 1); +} + +static inline void write_flush(int fd) { + tcdrain(fd); +} + +static inline void read_flush(int fd) { + tcflush(fd, TCIFLUSH); +} + +static int read_byte(int fd, unsigned int timeout) { + char buf[1]; + int n; + + alarm(timeout); + + n = read(fd, &buf, 1); + + alarm(0); + + if (n == 1) + return buf[0] & 0xff; + else + return -1; +} + +static int receive(char *error_buf, size_t error_buf_size, + int ttyfd, int filefd) +{ + char blockBuf[1024]; + unsigned int errors = 0; + unsigned int wantBlockNo = 1; + unsigned int length = 0; + int docrc = 1; + char nak = 'C'; + unsigned int timeout = TIMEOUT_LONG; + +#define note_error(fmt,args...) \ + snprintf(error_buf, error_buf_size, fmt,##args) + + read_flush(ttyfd); + + /* Ask for CRC; if we get errors, we will go with checksum */ + write_byte(ttyfd, nak); + write_flush(ttyfd); + + for (;;) { + int blockBegin; + int blockNo, blockNoOnesCompl; + int blockLength; + int cksum = 0; + int crcHi = 0; + int crcLo = 0; + + blockBegin = read_byte(ttyfd, timeout); + if (blockBegin < 0) + goto timeout; + + timeout = TIMEOUT; + nak = NAK; + + switch (blockBegin) { + case SOH: + case STX: + break; + + case EOT: + write_byte(ttyfd, ACK); + write_flush(ttyfd); + goto done; + + default: + goto error; + } + + /* block no */ + blockNo = read_byte(ttyfd, TIMEOUT); + if (blockNo < 0) + goto timeout; + + /* block no one's compliment */ + blockNoOnesCompl = read_byte(ttyfd, TIMEOUT); + if (blockNoOnesCompl < 0) + goto timeout; + + if (blockNo != (255 - blockNoOnesCompl)) { + note_error("bad block ones compl"); + goto error; + } + + blockLength = (blockBegin == SOH) ? 128 : 1024; + + { + int i; + + for (i = 0; i < blockLength; i++) { + int cc = read_byte(ttyfd, TIMEOUT); + if (cc < 0) + goto timeout; + blockBuf[i] = cc; + } + } + + if (docrc) { + crcHi = read_byte(ttyfd, TIMEOUT); + if (crcHi < 0) + goto timeout; + + crcLo = read_byte(ttyfd, TIMEOUT); + if (crcLo < 0) + goto timeout; + } else { + cksum = read_byte(ttyfd, TIMEOUT); + if (cksum < 0) + goto timeout; + } + + if (blockNo == ((wantBlockNo - 1) & 0xff)) { + /* a repeat of the last block is ok, just ignore it. */ + /* this also ignores the initial block 0 which is */ + /* meta data. */ + goto next; + } else if (blockNo != (wantBlockNo & 0xff)) { + note_error("unexpected block no, 0x%08x, expecting 0x%08x", blockNo, wantBlockNo); + goto error; + } + + if (docrc) { + int crc = 0; + int i, j; + int expectedCrcHi; + int expectedCrcLo; + + for (i = 0; i < blockLength; i++) { + crc = crc ^ (int) blockBuf[i] << 8; + for (j = 0; j < 8; j++) + if (crc & 0x8000) + crc = crc << 1 ^ 0x1021; + else + crc = crc << 1; + } + + expectedCrcHi = (crc >> 8) & 0xff; + expectedCrcLo = crc & 0xff; + + if ((crcHi != expectedCrcHi) || + (crcLo != expectedCrcLo)) { + note_error("crc error, expected 0x%02x 0x%02x, got 0x%02x 0x%02x", expectedCrcHi, expectedCrcLo, crcHi, crcLo); + goto error; + } + } else { + unsigned char expectedCksum = 0; + int i; + + for (i = 0; i < blockLength; i++) + expectedCksum += blockBuf[i]; + + if (cksum != expectedCksum) { + note_error("checksum error, expected 0x%02x, got 0x%02x", expectedCksum, cksum); + goto error; + } + } + + wantBlockNo++; + length += blockLength; + + if (bb_full_write(filefd, blockBuf, blockLength) < 0) { + note_error("write to file failed: %m"); + goto fatal; + } + + next: + errors = 0; + write_byte(ttyfd, ACK); + write_flush(ttyfd); + continue; + + error: + timeout: + errors++; + if (errors == MAXERRORS) { + /* Abort */ + int i; + + // if using crc, try again w/o crc + if (nak == 'C') { + nak = NAK; + errors = 0; + docrc = 0; + goto timeout; + } + + note_error("too many errors; giving up"); + + fatal: + for (i = 0; i < 5; i ++) + write_byte(ttyfd, CAN); + for (i = 0; i < 5; i ++) + write_byte(ttyfd, BS); + write_flush(ttyfd); + return -1; + } + + read_flush(ttyfd); + write_byte(ttyfd, nak); + write_flush(ttyfd); + } + + done: + return length; + +#undef note_error +} + +static void sigalrm_handler(int signum) +{ +} + +int rx_main(int argc, char **argv) +{ + char *fn; + int ttyfd, filefd; + struct termios tty, orig_tty; + struct sigaction act; + int n; + char error_buf[256]; + + if (argc != 2) + bb_show_usage(); + + fn = argv[1]; + ttyfd = open("/dev/tty", O_RDWR); + if (ttyfd < 0) + bb_error_msg_and_die("%s: open on /dev/tty failed: %m\n", argv[0]); + + filefd = open(fn, O_RDWR|O_CREAT|O_TRUNC, 0666); + if (filefd < 0) + bb_error_msg_and_die("%s: open on %s failed: %m\n", argv[0], fn); + + if (tcgetattr(ttyfd, &tty) < 0) + bb_error_msg_and_die("%s: tcgetattr failed: %m\n", argv[0]); + + orig_tty = tty; + + cfmakeraw(&tty); + tcsetattr(ttyfd, TCSAFLUSH, &tty); + + memset(&act, 0, sizeof(act)); + act.sa_handler = sigalrm_handler; + sigaction(SIGALRM, &act, 0); + + n = receive(error_buf, sizeof(error_buf), ttyfd, filefd); + + close(filefd); + + tcsetattr(ttyfd, TCSAFLUSH, &orig_tty); + + if (n < 0) + bb_error_msg_and_die("\n%s: receive failed:\n %s\n", + argv[0], error_buf); + + bb_fflush_stdout_and_exit(EXIT_SUCCESS); +} + +/* +Local Variables: +c-file-style: "linux" +c-basic-offset: 4 +tab-width: 4 +End: +*/ diff --git a/busybox/miscutils/strings.c b/busybox/miscutils/strings.c new file mode 100644 index 0000000..92e9f0d --- /dev/null +++ b/busybox/miscutils/strings.c @@ -0,0 +1,156 @@ +/* vi: set sw=4 ts=4: */ +/* + * strings implementation for busybox + * + * Copyright (c) 1980, 1987 + * The Regents of the University of California. All rights reserved. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * Original copyright notice is retained at the end of this file. + * + * Modified for BusyBox by Erik Andersen + * Badly hacked by Tito Ragusa + */ + +#include +#include +#include +#include +#include +#include +#include "busybox.h" + +#define ISSTR(ch) (isprint(ch) || ch == '\t') + +int strings_main(int argc, char **argv) +{ + int n=4, c, i, opt=0, status=EXIT_SUCCESS; + long t=0, count; + FILE *file = stdin; + char *string=NULL; + const char *fmt="%s: "; + + while ((i = getopt(argc, argv, "afon:")) > 0) + switch(i) + { + case 'a': + break; + case 'f': + opt+=1; + break; + case 'o': + opt+=2; + break; + case 'n': + n = bb_xgetlarg(optarg, 10, 1, INT_MAX); + break; + default: + bb_show_usage(); + } + + argc -= optind; + argv += optind; + + i=0; + + string=xmalloc(n+1); + string[n]='\0'; + n-=1; + + if(argc==0) + { + fmt="{%s}: "; + *argv=(char *)bb_msg_standard_input; + goto pipe; + } + + for( ;*argv!=NULL && argc>0;argv++) + { + if((file=bb_wfopen(*argv,"r"))) + { +pipe: + + count=0; + do{ + c=fgetc(file); + if(ISSTR(c)) + { + if(i==0) + t=count; + if(i<=n) + string[i]=c; + if(i==n) + { + if(opt == 1 || opt == 3 ) + printf(fmt,*argv); + if(opt >= 2 ) + printf("%7lo ", t); + printf("%s", string); + } + if(i>n) + putchar(c); + i++; + } + else + { + if(i>n) + putchar('\n'); + i=0; + } + count++; + }while(c!=EOF); + + bb_fclose_nonstdin(file); + } + else + status=EXIT_FAILURE; + } + /*free(string);*/ + exit(status); +} + +/* + * Copyright (c) 1980, 1987 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. + * + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ diff --git a/busybox/miscutils/time.c b/busybox/miscutils/time.c new file mode 100644 index 0000000..ca896a1 --- /dev/null +++ b/busybox/miscutils/time.c @@ -0,0 +1,502 @@ +/* `time' utility to display resource usage of processes. + Copyright (C) 1990, 91, 92, 93, 96 Free Software Foundation, Inc. + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2, or (at your option) + any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + 02111-1307, USA. */ + +/* Originally written by David Keppel . + Heavily modified by David MacKenzie . + Heavily modified for busybox by Erik Andersen + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include /* For pid_t. */ +#include +#include /* For getpagesize, maybe. */ + +#define TV_MSEC tv_usec / 1000 +#include +#include "busybox.h" + +/* Information on the resources used by a child process. */ +typedef struct +{ + int waitstatus; + struct rusage ru; + struct timeval start, elapsed; /* Wallclock time of process. */ +} resource_t; + +/* msec = milliseconds = 1/1,000 (1*10e-3) second. + usec = microseconds = 1/1,000,000 (1*10e-6) second. */ + +#ifndef TICKS_PER_SEC +#define TICKS_PER_SEC 100 +#endif + +/* The number of milliseconds in one `tick' used by the `rusage' structure. */ +#define MSEC_PER_TICK (1000 / TICKS_PER_SEC) + +/* Return the number of clock ticks that occur in M milliseconds. */ +#define MSEC_TO_TICKS(m) ((m) / MSEC_PER_TICK) + +#define UL unsigned long + +static const char *const default_format = "real\t%E\nuser\t%u\nsys\t%T"; + +/* The output format for the -p option .*/ +static const char *const posix_format = "real %e\nuser %U\nsys %S"; + + +/* Format string for printing all statistics verbosely. + Keep this output to 24 lines so users on terminals can see it all.*/ +static const char *const long_format = + "\tCommand being timed: \"%C\"\n" + "\tUser time (seconds): %U\n" + "\tSystem time (seconds): %S\n" + "\tPercent of CPU this job got: %P\n" + "\tElapsed (wall clock) time (h:mm:ss or m:ss): %E\n" + "\tAverage shared text size (kbytes): %X\n" + "\tAverage unshared data size (kbytes): %D\n" + "\tAverage stack size (kbytes): %p\n" + "\tAverage total size (kbytes): %K\n" + "\tMaximum resident set size (kbytes): %M\n" + "\tAverage resident set size (kbytes): %t\n" + "\tMajor (requiring I/O) page faults: %F\n" + "\tMinor (reclaiming a frame) page faults: %R\n" + "\tVoluntary context switches: %w\n" + "\tInvoluntary context switches: %c\n" + "\tSwaps: %W\n" + "\tFile system inputs: %I\n" + "\tFile system outputs: %O\n" + "\tSocket messages sent: %s\n" + "\tSocket messages received: %r\n" + "\tSignals delivered: %k\n" + "\tPage size (bytes): %Z\n" + "\tExit status: %x"; + + + /* Wait for and fill in data on child process PID. + Return 0 on error, 1 if ok. */ + +/* pid_t is short on BSDI, so don't try to promote it. */ +static int resuse_end (pid_t pid, resource_t *resp) +{ + int status; + + pid_t caught; + + /* Ignore signals, but don't ignore the children. When wait3 + returns the child process, set the time the command finished. */ + while ((caught = wait3 (&status, 0, &resp->ru)) != pid) + { + if (caught == -1) + return 0; + } + + gettimeofday (&resp->elapsed, (struct timezone *) 0); + resp->elapsed.tv_sec -= resp->start.tv_sec; + if (resp->elapsed.tv_usec < resp->start.tv_usec) + { + /* Manually carry a one from the seconds field. */ + resp->elapsed.tv_usec += 1000000; + --resp->elapsed.tv_sec; + } + resp->elapsed.tv_usec -= resp->start.tv_usec; + + resp->waitstatus = status; + + return 1; +} + +/* Print ARGV to FP, with each entry in ARGV separated by FILLER. */ +static void fprintargv (FILE *fp, char *const *argv, const char *filler) +{ + char *const *av; + + av = argv; + fputs (*av, fp); + while (*++av) + { + fputs (filler, fp); + fputs (*av, fp); + } + if (ferror (fp)) + bb_error_msg_and_die("write error"); +} + +/* Return the number of kilobytes corresponding to a number of pages PAGES. + (Actually, we use it to convert pages*ticks into kilobytes*ticks.) + + Try to do arithmetic so that the risk of overflow errors is minimized. + This is funky since the pagesize could be less than 1K. + Note: Some machines express getrusage statistics in terms of K, + others in terms of pages. */ + +static unsigned long ptok (unsigned long pages) +{ + static unsigned long ps = 0; + unsigned long tmp; + static long size = LONG_MAX; + + /* Initialization. */ + if (ps == 0) + ps = (long) getpagesize (); + + /* Conversion. */ + if (pages > (LONG_MAX / ps)) + { /* Could overflow. */ + tmp = pages / 1024; /* Smaller first, */ + size = tmp * ps; /* then larger. */ + } + else + { /* Could underflow. */ + tmp = pages * ps; /* Larger first, */ + size = tmp / 1024; /* then smaller. */ + } + return size; +} + +/* summarize: Report on the system use of a command. + + Copy the FMT argument to FP except that `%' sequences + have special meaning, and `\n' and `\t' are translated into + newline and tab, respectively, and `\\' is translated into `\'. + + The character following a `%' can be: + (* means the tcsh time builtin also recognizes it) + % == a literal `%' + C == command name and arguments +* D == average unshared data size in K (ru_idrss+ru_isrss) +* E == elapsed real (wall clock) time in [hour:]min:sec +* F == major page faults (required physical I/O) (ru_majflt) +* I == file system inputs (ru_inblock) +* K == average total mem usage (ru_idrss+ru_isrss+ru_ixrss) +* M == maximum resident set size in K (ru_maxrss) +* O == file system outputs (ru_oublock) +* P == percent of CPU this job got (total cpu time / elapsed time) +* R == minor page faults (reclaims; no physical I/O involved) (ru_minflt) +* S == system (kernel) time (seconds) (ru_stime) +* T == system time in [hour:]min:sec +* U == user time (seconds) (ru_utime) +* u == user time in [hour:]min:sec +* W == times swapped out (ru_nswap) +* X == average amount of shared text in K (ru_ixrss) + Z == page size +* c == involuntary context switches (ru_nivcsw) + e == elapsed real time in seconds +* k == signals delivered (ru_nsignals) + p == average unshared stack size in K (ru_isrss) +* r == socket messages received (ru_msgrcv) +* s == socket messages sent (ru_msgsnd) + t == average resident set size in K (ru_idrss) +* w == voluntary context switches (ru_nvcsw) + x == exit status of command + + Various memory usages are found by converting from page-seconds + to kbytes by multiplying by the page size, dividing by 1024, + and dividing by elapsed real time. + + FP is the stream to print to. + FMT is the format string, interpreted as described above. + COMMAND is the command and args that are being summarized. + RESP is resource information on the command. */ + +static void summarize (FILE *fp, const char *fmt, char **command, resource_t *resp) +{ + unsigned long r; /* Elapsed real milliseconds. */ + unsigned long v; /* Elapsed virtual (CPU) milliseconds. */ + + if (WIFSTOPPED (resp->waitstatus)) + fprintf (fp, "Command stopped by signal %d\n", WSTOPSIG (resp->waitstatus)); + else if (WIFSIGNALED (resp->waitstatus)) + fprintf (fp, "Command terminated by signal %d\n", WTERMSIG (resp->waitstatus)); + else if (WIFEXITED (resp->waitstatus) && WEXITSTATUS (resp->waitstatus)) + fprintf (fp, "Command exited with non-zero status %d\n", WEXITSTATUS (resp->waitstatus)); + + /* Convert all times to milliseconds. Occasionally, one of these values + comes out as zero. Dividing by zero causes problems, so we first + check the time value. If it is zero, then we take `evasive action' + instead of calculating a value. */ + + r = resp->elapsed.tv_sec * 1000 + resp->elapsed.tv_usec / 1000; + + v = resp->ru.ru_utime.tv_sec * 1000 + resp->ru.ru_utime.TV_MSEC + + resp->ru.ru_stime.tv_sec * 1000 + resp->ru.ru_stime.TV_MSEC; + + while (*fmt) + { + switch (*fmt) + { + case '%': + switch (*++fmt) + { + case '%': /* Literal '%'. */ + putc ('%', fp); + break; + case 'C': /* The command that got timed. */ + fprintargv (fp, command, " "); + break; + case 'D': /* Average unshared data size. */ + fprintf (fp, "%lu", + MSEC_TO_TICKS (v) == 0 ? 0 : + ptok ((UL) resp->ru.ru_idrss) / MSEC_TO_TICKS (v) + + ptok ((UL) resp->ru.ru_isrss) / MSEC_TO_TICKS (v)); + break; + case 'E': /* Elapsed real (wall clock) time. */ + if (resp->elapsed.tv_sec >= 3600) /* One hour -> h:m:s. */ + fprintf (fp, "%ldh %ldm %02lds", + resp->elapsed.tv_sec / 3600, + (resp->elapsed.tv_sec % 3600) / 60, + resp->elapsed.tv_sec % 60); + else + fprintf (fp, "%ldm %ld.%02lds", /* -> m:s. */ + resp->elapsed.tv_sec / 60, + resp->elapsed.tv_sec % 60, + resp->elapsed.tv_usec / 10000); + break; + case 'F': /* Major page faults. */ + fprintf (fp, "%ld", resp->ru.ru_majflt); + break; + case 'I': /* Inputs. */ + fprintf (fp, "%ld", resp->ru.ru_inblock); + break; + case 'K': /* Average mem usage == data+stack+text. */ + fprintf (fp, "%lu", + MSEC_TO_TICKS (v) == 0 ? 0 : + ptok ((UL) resp->ru.ru_idrss) / MSEC_TO_TICKS (v) + + ptok ((UL) resp->ru.ru_isrss) / MSEC_TO_TICKS (v) + + ptok ((UL) resp->ru.ru_ixrss) / MSEC_TO_TICKS (v)); + break; + case 'M': /* Maximum resident set size. */ + fprintf (fp, "%lu", ptok ((UL) resp->ru.ru_maxrss)); + break; + case 'O': /* Outputs. */ + fprintf (fp, "%ld", resp->ru.ru_oublock); + break; + case 'P': /* Percent of CPU this job got. */ + /* % cpu is (total cpu time)/(elapsed time). */ + if (r > 0) + fprintf (fp, "%lu%%", (v * 100 / r)); + else + fprintf (fp, "?%%"); + break; + case 'R': /* Minor page faults (reclaims). */ + fprintf (fp, "%ld", resp->ru.ru_minflt); + break; + case 'S': /* System time. */ + fprintf (fp, "%ld.%02ld", + resp->ru.ru_stime.tv_sec, + resp->ru.ru_stime.TV_MSEC / 10); + break; + case 'T': /* System time. */ + if (resp->ru.ru_stime.tv_sec >= 3600) /* One hour -> h:m:s. */ + fprintf (fp, "%ldh %ldm %02lds", + resp->ru.ru_stime.tv_sec / 3600, + (resp->ru.ru_stime.tv_sec % 3600) / 60, + resp->ru.ru_stime.tv_sec % 60); + else + fprintf (fp, "%ldm %ld.%02lds", /* -> m:s. */ + resp->ru.ru_stime.tv_sec / 60, + resp->ru.ru_stime.tv_sec % 60, + resp->ru.ru_stime.tv_usec / 10000); + break; + case 'U': /* User time. */ + fprintf (fp, "%ld.%02ld", + resp->ru.ru_utime.tv_sec, + resp->ru.ru_utime.TV_MSEC / 10); + break; + case 'u': /* User time. */ + if (resp->ru.ru_utime.tv_sec >= 3600) /* One hour -> h:m:s. */ + fprintf (fp, "%ldh %ldm %02lds", + resp->ru.ru_utime.tv_sec / 3600, + (resp->ru.ru_utime.tv_sec % 3600) / 60, + resp->ru.ru_utime.tv_sec % 60); + else + fprintf (fp, "%ldm %ld.%02lds", /* -> m:s. */ + resp->ru.ru_utime.tv_sec / 60, + resp->ru.ru_utime.tv_sec % 60, + resp->ru.ru_utime.tv_usec / 10000); + break; + case 'W': /* Times swapped out. */ + fprintf (fp, "%ld", resp->ru.ru_nswap); + break; + case 'X': /* Average shared text size. */ + fprintf (fp, "%lu", + MSEC_TO_TICKS (v) == 0 ? 0 : + ptok ((UL) resp->ru.ru_ixrss) / MSEC_TO_TICKS (v)); + break; + case 'Z': /* Page size. */ + fprintf (fp, "%d", getpagesize ()); + break; + case 'c': /* Involuntary context switches. */ + fprintf (fp, "%ld", resp->ru.ru_nivcsw); + break; + case 'e': /* Elapsed real time in seconds. */ + fprintf (fp, "%ld.%02ld", + resp->elapsed.tv_sec, + resp->elapsed.tv_usec / 10000); + break; + case 'k': /* Signals delivered. */ + fprintf (fp, "%ld", resp->ru.ru_nsignals); + break; + case 'p': /* Average stack segment. */ + fprintf (fp, "%lu", + MSEC_TO_TICKS (v) == 0 ? 0 : + ptok ((UL) resp->ru.ru_isrss) / MSEC_TO_TICKS (v)); + break; + case 'r': /* Incoming socket messages received. */ + fprintf (fp, "%ld", resp->ru.ru_msgrcv); + break; + case 's': /* Outgoing socket messages sent. */ + fprintf (fp, "%ld", resp->ru.ru_msgsnd); + break; + case 't': /* Average resident set size. */ + fprintf (fp, "%lu", + MSEC_TO_TICKS (v) == 0 ? 0 : + ptok ((UL) resp->ru.ru_idrss) / MSEC_TO_TICKS (v)); + break; + case 'w': /* Voluntary context switches. */ + fprintf (fp, "%ld", resp->ru.ru_nvcsw); + break; + case 'x': /* Exit status. */ + fprintf (fp, "%d", WEXITSTATUS (resp->waitstatus)); + break; + case '\0': + putc ('?', fp); + return; + default: + putc ('?', fp); + putc (*fmt, fp); + } + ++fmt; + break; + + case '\\': /* Format escape. */ + switch (*++fmt) + { + case 't': + putc ('\t', fp); + break; + case 'n': + putc ('\n', fp); + break; + case '\\': + putc ('\\', fp); + break; + default: + putc ('?', fp); + putc ('\\', fp); + putc (*fmt, fp); + } + ++fmt; + break; + + default: + putc (*fmt++, fp); + } + + if (ferror (fp)) + bb_error_msg_and_die("write error"); + } + putc ('\n', fp); + + if (ferror (fp)) + bb_error_msg_and_die("write error"); +} + +/* Run command CMD and return statistics on it. + Put the statistics in *RESP. */ +static void run_command (char *const *cmd, resource_t *resp) +{ + pid_t pid; /* Pid of child. */ + __sighandler_t interrupt_signal, quit_signal; + + gettimeofday (&resp->start, (struct timezone *) 0); + pid = fork (); /* Run CMD as child process. */ + if (pid < 0) + bb_error_msg_and_die("cannot fork"); + else if (pid == 0) + { /* If child. */ + /* Don't cast execvp arguments; that causes errors on some systems, + versus merely warnings if the cast is left off. */ + execvp (cmd[0], cmd); + bb_error_msg("cannot run %s", cmd[0]); + _exit (errno == ENOENT ? 127 : 126); + } + + /* Have signals kill the child but not self (if possible). */ + interrupt_signal = signal (SIGINT, SIG_IGN); + quit_signal = signal (SIGQUIT, SIG_IGN); + + if (resuse_end (pid, resp) == 0) + bb_error_msg("error waiting for child process"); + + /* Re-enable signals. */ + signal (SIGINT, interrupt_signal); + signal (SIGQUIT, quit_signal); +} + +extern int time_main (int argc, char **argv) +{ + int gotone; + resource_t res; + const char *output_format = default_format; + + argc--; + argv++; + /* Parse any options -- don't use getopt() here so we don't + * consume the args of our client application... */ + while (argc > 0 && **argv == '-') { + gotone = 0; + while (gotone==0 && *++(*argv)) { + switch (**argv) { + case 'v': + output_format = long_format; + break; + case 'p': + output_format = posix_format; + break; + default: + bb_show_usage(); + } + argc--; + argv++; + gotone = 1; + } + } + + if (argv == NULL || *argv == NULL) + bb_show_usage(); + + run_command (argv, &res); + summarize (stderr, output_format, argv, &res); + fflush (stderr); + + if (WIFSTOPPED (res.waitstatus)) + exit (WSTOPSIG (res.waitstatus)); + else if (WIFSIGNALED (res.waitstatus)) + exit (WTERMSIG (res.waitstatus)); + else if (WIFEXITED (res.waitstatus)) + exit (WEXITSTATUS (res.waitstatus)); + return 0; +} diff --git a/busybox/miscutils/watchdog.c b/busybox/miscutils/watchdog.c new file mode 100644 index 0000000..276fade --- /dev/null +++ b/busybox/miscutils/watchdog.c @@ -0,0 +1,81 @@ +/* vi: set sw=4 ts=4: */ +/* + * Mini watchdog implementation for busybox + * + * Copyright (C) 2003 Paul Mundt + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + */ + +#include +#include +#include +#include +#include +#include "busybox.h" + +/* Userspace timer duration, in seconds */ +static unsigned int timer_duration = 30; + +/* Watchdog file descriptor */ +static int fd; + +static void watchdog_shutdown(int unused) +{ + write(fd, "V", 1); /* Magic */ + close(fd); + exit(0); +} + +extern int watchdog_main(int argc, char **argv) +{ + int opt; + + while ((opt = getopt(argc, argv, "t:")) > 0) { + switch (opt) { + case 't': + timer_duration = bb_xgetlarg(optarg, 10, 0, INT_MAX); + break; + default: + bb_show_usage(); + } + } + + /* We're only interested in the watchdog device .. */ + if (optind < argc - 1 || argc == 1) + bb_show_usage(); + + if (daemon(0, 1) < 0) + bb_perror_msg_and_die("Failed forking watchdog daemon"); + + signal(SIGHUP, watchdog_shutdown); + signal(SIGINT, watchdog_shutdown); + + fd = bb_xopen(argv[argc - 1], O_WRONLY); + + while (1) { + /* + * Make sure we clear the counter before sleeping, as the counter value + * is undefined at this point -- PFM + */ + write(fd, "\0", 1); + sleep(timer_duration); + } + + watchdog_shutdown(0); + + return EXIT_SUCCESS; +} -- cgit v1.1