diff options
Diffstat (limited to 'miscutils')
-rw-r--r-- | miscutils/Config.in | 374 | ||||
-rw-r--r-- | miscutils/Kbuild | 30 | ||||
-rw-r--r-- | miscutils/adjtimex.c | 117 | ||||
-rw-r--r-- | miscutils/bbconfig.c | 11 | ||||
-rw-r--r-- | miscutils/crond.c | 1016 | ||||
-rw-r--r-- | miscutils/crontab.c | 344 | ||||
-rw-r--r-- | miscutils/dc.c | 231 | ||||
-rw-r--r-- | miscutils/devfsd.c | 2032 | ||||
-rw-r--r-- | miscutils/eject.c | 60 | ||||
-rw-r--r-- | miscutils/hdparm.c | 2184 | ||||
-rw-r--r-- | miscutils/last.c | 91 | ||||
-rw-r--r-- | miscutils/less.c | 1144 | ||||
-rw-r--r-- | miscutils/makedevs.c | 230 | ||||
-rw-r--r-- | miscutils/mountpoint.c | 65 | ||||
-rw-r--r-- | miscutils/mt.c | 120 | ||||
-rw-r--r-- | miscutils/nmeter.c | 848 | ||||
-rw-r--r-- | miscutils/raidautorun.c | 26 | ||||
-rw-r--r-- | miscutils/readahead.c | 34 | ||||
-rw-r--r-- | miscutils/runlevel.c | 42 | ||||
-rw-r--r-- | miscutils/rx.c | 290 | ||||
-rw-r--r-- | miscutils/setsid.c | 44 | ||||
-rw-r--r-- | miscutils/strings.c | 88 | ||||
-rw-r--r-- | miscutils/taskset.c | 96 | ||||
-rw-r--r-- | miscutils/time.c | 467 | ||||
-rw-r--r-- | miscutils/watchdog.c | 65 |
25 files changed, 10049 insertions, 0 deletions
diff --git a/miscutils/Config.in b/miscutils/Config.in new file mode 100644 index 0000000..90e2b6f --- /dev/null +++ b/miscutils/Config.in @@ -0,0 +1,374 @@ +# +# For a description of the syntax of this configuration file, +# see scripts/kbuild/config-language.txt. +# + +menu "Miscellaneous Utilities" + +config ADJTIMEX + bool "adjtimex" + default n + help + Adjtimex reads and optionally sets adjustment parameters for + the Linux clock adjustment algorithm. + +config BBCONFIG + bool "bbconfig" + default n + help + The bbconfig applet will print the config file with which + busybox was built. + +config CROND + bool "crond" + default n + select FEATURE_SUID + select FEATURE_SYSLOG + 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/<username> 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 DEBUG_CROND_OPTION + bool "Support debug option -d" + depends on CROND + default n + help + Support option -d to enter debug mode. + +config FEATURE_CROND_CALL_SENDMAIL + bool "Using /usr/sbin/sendmail?" + default n + depends on CROND + help + Support calling /usr/sbin/sendmail for send cmd outputs. + +config CRONTAB + bool "crontab" + default n + select FEATURE_SUID + help + Crontab manipulates the crontab for a particular user. Only + the superuser may specify a different user and/or crontab directory. + +config DC + bool "dc" + default n + help + Dc is a reverse-polish desk calculator which supports unlimited + precision arithmetic. + +config DEVFSD + bool "devfsd (obsolete)" + default n + select FEATURE_SYSLOG + help + This is deprecated, and will be removed at the end of 2008. + + 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 DEVFSD_MODLOAD + bool "Adds support for MODLOAD keyword in devsfd.conf" + default n + depends on DEVFSD + help + This actually doesn't work with busybox modutils but needs + the external modutils. + +config DEVFSD_FG_NP + bool "Enables the -fg and -np options" + default n + depends on DEVFSD + help + -fg Run the daemon in the foreground. + -np Exit after parsing the configuration file. Do not poll for events. + +config DEVFSD_VERBOSE + bool "Increases logging (and size)" + default n + depends on DEVFSD + help + Increases logging to stderr or syslog. + +config FEATURE_DEVFS + bool " Use devfs names for all devices (obsolete)" + default n + help + This is obsolete and will be going away at the end of 2008.. + + This tells busybox to look for names like /dev/loop/0 instead of + /dev/loop0. If your /dev directory has normal names instead of + devfs names, you don't want this. + +config EJECT + bool "eject" + default n + help + Used to eject cdroms. (defaults to /dev/cdrom) + +config LAST + bool "last" + default n + select FEATURE_WTMP + help + 'last' displays a list of the last users that logged into the system. + +config LESS + bool "less" + default n + help + 'less' is a pager, meaning that it displays text files. It possesses + a wide array of features, and is an improvement over 'more'. + +config FEATURE_LESS_BRACKETS + bool "Enable bracket searching" + default y + depends on LESS + help + This option adds the capability to search for matching left and right + brackets, facilitating programming. + +config FEATURE_LESS_FLAGS + bool "Enable extra flags" + default y + depends on LESS + help + The extra flags provided do the following: + + The -M flag enables a more sophisticated status line. + The -m flag enables a simpler status line with a percentage. + +config FEATURE_LESS_FLAGCS + bool "Enable flag changes" + default n + depends on LESS + help + This enables the ability to change command-line flags within + less itself. + +config FEATURE_LESS_MARKS + bool "Enable marks" + default n + depends on LESS + help + Marks enable positions in a file to be stored for easy reference. + +config FEATURE_LESS_REGEXP + bool "Enable regular expressions" + default n + depends on LESS + help + Enable regular expressions, allowing complex file searches. + +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 + FEATURE_HDPARM_GET_IDENTITY option).... + +config FEATURE_HDPARM_GET_IDENTITY + bool "Support obtaining detailed information directly from drives" + default y + depends on HDPARM + help + Enables the -I and -i options to obtain detailed information + directly from drives about their capabilities and supported ATA + feature set. If no device name is specified, hdparm will read + identify data from stdin. Enabling this option will add about 16k... + +config FEATURE_HDPARM_HDIO_SCAN_HWIF + bool "Register an IDE interface (DANGEROUS)" + default n + depends on HDPARM + help + Enables the 'hdparm -R' option to register an IDE interface. + This is dangerous stuff, so you should probably say N. + +config FEATURE_HDPARM_HDIO_UNREGISTER_HWIF + bool "Un-register an IDE interface (DANGEROUS)" + default n + depends on HDPARM + help + Enables the 'hdparm -U' option to un-register an IDE interface. + This is dangerous stuff, so you should probably say N. + +config FEATURE_HDPARM_HDIO_DRIVE_RESET + bool "perform device reset (DANGEROUS)" + default n + depends on HDPARM + help + Enables the 'hdparm -w' option to perform a device reset. + This is dangerous stuff, so you should probably say N. + +config FEATURE_HDPARM_HDIO_TRISTATE_HWIF + bool "tristate device for hotswap (DANGEROUS)" + default n + depends on 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 FEATURE_HDPARM_HDIO_GETSET_DMA + bool "get/set using_dma flag (DANGEROUS)" + default n + depends on HDPARM + help + Enables the 'hdparm -d' option to get/set using_dma flag. + This is dangerous stuff, so you should probably say N. + +config MAKEDEVS + bool "makedevs" + default n + help + 'makedevs' is a utility used to create a batch of devices with + one command. + . + There are two choices for command line behaviour, the interface + as used by LEAF/Linux Router Project, or a device table file. + . + 'leaf' is traditionally what busybox follows, it allows multiple + devices of a particluar type to be created per command. + e.g. /dev/hda[0-9] + Device properties are passed as command line arguments. + . + 'table' reads device properties from a file or stdin, allowing + a batch of unrelated devices to be made with one command. + User/group names are allowed as an alternative to uid/gid. + +choice + prompt "Choose makedevs behaviour" + depends MAKEDEVS + default FEATURE_MAKEDEVS_TABLE + +config FEATURE_MAKEDEVS_LEAF + bool "leaf" + +config FEATURE_MAKEDEVS_TABLE + bool "table" + +endchoice + +config MOUNTPOINT + bool "mountpoint" + default n + help + mountpoint checks if the directory is a mountpoint. + +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 NMETER + bool "nmeter" + default n + help + nmeter prints various system parameters continuously. + +config RAIDAUTORUN + bool "raidautorun" + default n + help + raidautorun tells the kernel md driver to + search and start RAID arrays. + +config READAHEAD + bool "readahead" + default n + help + Preload the files listed on the command line into RAM cache so that + subsequent reads on these files will not block on disk I/O. + + This applet just calls the readahead(2) system call on each file. + It is mainly useful in system startup scripts to preload files + or executables before they are used. When used at the right time + (in particular when a CPU boundprocess is running) it can + significantly speed up system startup. + + As readahead(2) blocks until each file has been read, it is best to + run this applet as a background job. + +config RUNLEVEL + bool "runlevel" + default n + help + find the current and previous system runlevel. + + This applet uses utmp but does not rely on busybox supporing + utmp on purpose. It is used by e.g. emdebian via /etc/init.d/rc. + +config RX + bool "rx" + default n + help + Receive files using the Xmodem protocol. + +config STRINGS + bool "strings" + default n + help + strings prints the printable character sequences for each file + specified. + +config SETSID + bool "setsid" + default n + help + setsid runs a program in a new session + +config TASKSET + bool "taskset" + default n + help + Retrieve or set a processes's CPU affinity. + This requires sched_{g,s}etaffinity support in your libc. + +config FEATURE_TASKSET_FANCY + bool "fancy output" + default y + depends on TASKSET + help + Add code for fancy output. This merely silences a compiler-warning + and adds about 135 Bytes. May be needed for machines with alot + of CPUs. + +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 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/miscutils/Kbuild b/miscutils/Kbuild new file mode 100644 index 0000000..8d1b9f4 --- /dev/null +++ b/miscutils/Kbuild @@ -0,0 +1,30 @@ +# Makefile for busybox +# +# Copyright (C) 1999-2005 by Erik Andersen <andersen@codepoet.org> +# +# Licensed under the GPL v2, see the file LICENSE in this tarball. + +lib-y:= +lib-$(CONFIG_ADJTIMEX) += adjtimex.o +lib-$(CONFIG_CROND) += crond.o +lib-$(CONFIG_CRONTAB) += crontab.o +lib-$(CONFIG_BBCONFIG) += bbconfig.o +lib-$(CONFIG_DC) += dc.o +lib-$(CONFIG_DEVFSD) += devfsd.o +lib-$(CONFIG_EJECT) += eject.o +lib-$(CONFIG_HDPARM) += hdparm.o +lib-$(CONFIG_LAST) += last.o +lib-$(CONFIG_LESS) += less.o +lib-$(CONFIG_MAKEDEVS) += makedevs.o +lib-$(CONFIG_MOUNTPOINT) += mountpoint.o +lib-$(CONFIG_MT) += mt.o +lib-$(CONFIG_NMETER) += nmeter.o +lib-$(CONFIG_RAIDAUTORUN) += raidautorun.o +lib-$(CONFIG_READAHEAD) += readahead.o +lib-$(CONFIG_RUNLEVEL) += runlevel.o +lib-$(CONFIG_RX) += rx.o +lib-$(CONFIG_SETSID) += setsid.o +lib-$(CONFIG_STRINGS) += strings.o +lib-$(CONFIG_TASKSET) += taskset.o +lib-$(CONFIG_TIME) += time.o +lib-$(CONFIG_WATCHDOG) += watchdog.o diff --git a/miscutils/adjtimex.c b/miscutils/adjtimex.c new file mode 100644 index 0000000..b35538a --- /dev/null +++ b/miscutils/adjtimex.c @@ -0,0 +1,117 @@ +/* vi: set sw=4 ts=4: */ +/* + * 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 <LRDoolittle@lbl.gov> + * + * busyboxed 20 March 2001, Larry Doolittle <ldoolitt@recycle.lbl.gov> + * + * Licensed under GPLv2 or later, see file License in this tarball for details. + */ + +#include "busybox.h" +#include <sys/timex.h> + +static const struct {int bit; const 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 const char * const ret_code_descript[] = { + "clock synchronized", + "insert leap second", + "delete leap second", + "leap second in progress", + "leap second has occurred", + "clock not synchronized" }; + +int adjtimex_main(int argc, char **argv) +{ + enum { + OPT_quiet = 0x1 + }; + unsigned opt; + char *opt_o, *opt_f, *opt_p, *opt_t; + struct timex txc; + int i, ret, sep; + const char *descript; + txc.modes=0; + + opt = getopt32(argc, argv, "qo:f:p:t:", + &opt_o, &opt_f, &opt_p, &opt_t); + //if (opt & 0x1) // -q + if (opt & 0x2) { // -o + txc.offset = xatoi(opt_o); + txc.modes |= ADJ_OFFSET_SINGLESHOT; + } + if (opt & 0x4) { // -f + txc.freq = xatou(opt_f); + txc.modes |= ADJ_FREQUENCY; + } + if (opt & 0x8) { // -p + txc.constant = xatoi(opt_p); + txc.modes |= ADJ_TIMECONST; + } + if (opt & 0x10) { // -t + txc.tick = xatoi(opt_t); + txc.modes |= ADJ_TICK; + } + if (argc != optind) { /* no valid non-option parameters */ + bb_show_usage(); + } + + ret = adjtimex(&txc); + + if (ret < 0) perror("adjtimex"); + + if (!(opt & OPT_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/miscutils/bbconfig.c b/miscutils/bbconfig.c new file mode 100644 index 0000000..ce14d4a --- /dev/null +++ b/miscutils/bbconfig.c @@ -0,0 +1,11 @@ +/* vi: set sw=4 ts=4: */ +/* This file was released into the public domain by Paul Fox. + */ +#include "busybox.h" +#include "bbconfigopts.h" + +int bbconfig_main(int argc, char **argv) +{ + printf(bbconfig_config); + return 0; +} diff --git a/miscutils/crond.c b/miscutils/crond.c new file mode 100644 index 0000000..fa7964e --- /dev/null +++ b/miscutils/crond.c @@ -0,0 +1,1016 @@ +/* vi: set sw=4 ts=4: */ +/* + * crond -d[#] -c <crondir> -f -b + * + * run as root, but NOT setuid root + * + * Copyright 1994 Matthew Dillon (dillon@apollo.west.oic.com) + * Vladimir Oleynik <dzo@simtreas.ru> (C) 2002 + * + * Licensed under the GPL v2 or later, see the file LICENSE in this tarball. + */ + +#define VERSION "2.3.2" + +#include "busybox.h" +#include <sys/syslog.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 + +#if ENABLE_DEBUG_CROND_OPTION +static unsigned DebugOpt; +#endif + +static unsigned 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); + +#if ENABLE_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) { + +#if ENABLE_DEBUG_CROND_OPTION + 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, 0600); + if (logfd >= 0) { + vdprintf(logfd, fmt, va); + close(logfd); +#if ENABLE_DEBUG_CROND_OPTION + } 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 opt; + char *lopt, *Lopt, *copt; + +#if ENABLE_DEBUG_CROND_OPTION + char *dopt; + + opt_complementary = "f-b:b-f:S-L:L-S:d-l"; +#else + opt_complementary = "f-b:b-f:S-L:L-S"; +#endif + + opterr = 0; /* disable getopt 'errors' message. */ + opt = getopt32(ac, av, "l:L:fbSc:" +#if ENABLE_DEBUG_CROND_OPTION + "d:" +#endif + , &lopt, &Lopt, &copt +#if ENABLE_DEBUG_CROND_OPTION + , &dopt +#endif + ); + if (opt & 1) { + LogLevel = xatou(lopt); + } + if (opt & 2) { + if (*Lopt != 0) { + LogFile = Lopt; + } + } + if (opt & 32) { + if (*copt != 0) { + CDir = copt; + } + } +#if ENABLE_DEBUG_CROND_OPTION + if (opt & 64) { + DebugOpt = xatou(dopt); + LogLevel = 0; + } +#endif + + /* + * change directory + */ + + xchdir(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)) { +#ifdef BB_NOMMU + /* reexec for vfork() do continue parent */ + vfork_daemon_rexec(1, 0, ac, av, "-f"); +#else + xdaemon(1, 0); +#endif + } + + (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", + applet_name, LogLevel); + + SynchronizeDir(); + + { + time_t t1 = time(NULL); + time_t t2; + long dt; + int 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(); +#if ENABLE_DEBUG_CROND_OPTION + 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; + } + } + } + return 0; /* not reached */ +} + +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(applet_name, LOG_CONS | LOG_PID, LOG_CRON); + } +#if ENABLE_DEBUG_CROND_OPTION + else { /* test logfile */ + int logfd; + + if ((logfd = open(LogFile, O_WRONLY | O_CREAT | O_APPEND, 0600)) >= 0) { + close(logfd); + } else { + bb_perror_msg("failed to open log file '%s': ", 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; + } +#if ENABLE_DEBUG_CROND_OPTION + 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) +{ + int i; + int weekUsed = 0; + int daysUsed = 0; + + for (i = 0; i < (int)(arysize(line->cl_Dow)); ++i) { + if (line->cl_Dow[i] == 0) { + weekUsed = 1; + break; + } + } + for (i = 0; i < (int)(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; + + trim(buf); + if (buf[0] == 0 || buf[0] == '#') { + continue; + } + if (--maxEntries == 0) { + break; + } + memset(&line, 0, sizeof(line)); + +#if ENABLE_DEBUG_CROND_OPTION + 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); + +#if ENABLE_DEBUG_CROND_OPTION + 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("\311cannot 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("\311cannot 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) +{ + int 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) { +#if ENABLE_DEBUG_CROND_OPTION + 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) { +#if ENABLE_DEBUG_CROND_OPTION + 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]) { +#if ENABLE_DEBUG_CROND_OPTION + 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; +} + + +#if ENABLE_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); + } +#if ENABLE_DEBUG_CROND_OPTION + 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("\024cannot 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("\024cannot 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, SEEK_CUR); + } else { + crondlog("\024cannot 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); + } +#if ENABLE_DEBUG_CROND_OPTION + if (DebugOpt) { + crondlog("\005Child Running %s\n", DEFAULT_SHELL); + } +#endif + + execl(DEFAULT_SHELL, DEFAULT_SHELL, "-c", line->cl_Shell, NULL); + crondlog("\024cannot exec, user %s cmd %s -c %s\n", user, + DEFAULT_SHELL, line->cl_Shell); + exit(0); + } else if (pid < 0) { + /* FORK FAILED */ + crondlog("\024cannot, user %s\n", user); + pid = 0; + } + line->cl_Pid = pid; +} +#endif /* ENABLE_FEATURE_CROND_CALL_SENDMAIL */ diff --git a/miscutils/crontab.c b/miscutils/crontab.c new file mode 100644 index 0000000..39d3aae --- /dev/null +++ b/miscutils/crontab.c @@ -0,0 +1,344 @@ +/* vi: set sw=4 ts=4: */ +/* + * CRONTAB + * + * usually setuid root, -c option only works if getuid() == geteuid() + * + * Copyright 1994 Matthew Dillon (dillon@apollo.west.oic.com) + * Vladimir Oleynik <dzo@simtreas.ru> (C) 2002 + * + * Licensed under the GPL v2 or later, see the file LICENSE in this tarball. + */ + +#include "busybox.h" + +#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 + +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 */ + char buf[1024]; + int UserId; + + UserId = getuid(); + pas = getpwuid(UserId); + if (pas == NULL) + bb_perror_msg_and_die("getpwuid"); + + safe_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 + */ + + pas = getpwuid(UserId); + if (pas == 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("cannot read replacement file"); + } + + /* + * Change directory to our crontab directory + */ + + xchdir(CDir); + + /* + * Handle options as appropriate + */ + + switch (option) { + case LIST: + { + FILE *fi; + + fi = fopen(pas->pw_name, "r"); + if (fi) { + 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: + { +/* FIXME: messy code here! we have file copying helpers for this! */ + FILE *fi; + int fd; + int n; + char tmp[128]; + + snprintf(tmp, sizeof(tmp), TMPDIR "/crontab.%d", getpid()); + fd = xopen3(tmp, O_RDWR|O_CREAT|O_TRUNC|O_EXCL, 0600); +/* race, use fchown */ + chown(tmp, getuid(), getgid()); + fi = fopen(pas->pw_name, "r"); + if (fi) { + while ((n = fread(buf, 1, sizeof(buf), fi)) > 0) + full_write(fd, buf, n); + } + EditFile(caller, tmp); + remove(tmp); + lseek(fd, 0L, SEEK_SET); + repFd = fd; + } + option = REPLACE; + /* fall through */ + case REPLACE: + { +/* same here */ + char path[1024]; + int fd; + int n; + + snprintf(path, sizeof(path), "%s.new", pas->pw_name); + fd = open(path, O_CREAT|O_TRUNC|O_APPEND|O_WRONLY, 0600); + if (fd >= 0) { + while ((n = read(repFd, buf, sizeof(buf))) > 0) { + full_write(fd, buf, n); + } + close(fd); + rename(path, pas->pw_name); + } else { + bb_error_msg("cannot 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("cannot 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; + } + pid = fork(); + if (pid < 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); + + xfunc_error_retval = 0; + fd = xopen(file, O_RDONLY); + 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 = fork(); + + if (pid == 0) { + /* + * CHILD - change user and run editor + */ + char *ptr; + char visual[1024]; + + if (ChangeUser(user, 1) < 0) + exit(0); + ptr = getenv("VISUAL"); + if (ptr == 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 + */ + + pas = getpwnam(user); + if (pas == NULL) { + bb_perror_msg_and_die("failed to get uid for %s", user); + } + 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("chdir(%s) by %s failed", pas->pw_dir, user); + xchdir(TMPDIR); + } + } + return pas->pw_uid; +} diff --git a/miscutils/dc.c b/miscutils/dc.c new file mode 100644 index 0000000..7b64057 --- /dev/null +++ b/miscutils/dc.c @@ -0,0 +1,231 @@ +/* vi: set sw=4 ts=4: */ +/* + * Licensed under GPLv2 or later, see file LICENSE in this tarball for details. + */ + +#include "busybox.h" +#include <ctype.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <unistd.h> +#include <math.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; + + current = skip_whitespace(*buffer); + 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 = xmalloc_getline(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--; + } + } + return EXIT_SUCCESS; +} diff --git a/miscutils/devfsd.c b/miscutils/devfsd.c new file mode 100644 index 0000000..f39bb7e --- /dev/null +++ b/miscutils/devfsd.c @@ -0,0 +1,2032 @@ +/* vi: set sw=4 ts=4: */ +/* + * Licensed under GPLv2 or later, see file LICENSE in this tarball for details. + */ + +/* + devfsd implementation for busybox + + Copyright (C) 2003 by Tito Ragusa <farmatito@tiscali.it> + + 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 "busybox.h" +#include "xregex.h" +#include <unistd.h> +#include <stdio.h> +#include <stdlib.h> +#include <stdarg.h> +#include <string.h> +#include <ctype.h> +#include <sys/stat.h> +#include <sys/types.h> +#include <sys/wait.h> +#include <sys/ioctl.h> +#include <sys/socket.h> +#include <sys/un.h> +#include <dirent.h> +#include <fcntl.h> +#include <syslog.h> +#include <signal.h> +#include <errno.h> +#include <sys/sysmacros.h> + + +/* 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 + +/* 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); +static void action_modload (const struct devfsd_notify_struct *info, const struct config_entry_struct *entry); +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 */ +static void msg_logger(int pri, const char * fmt, ... )__attribute__ ((format (printf, 2, 3))); +static void msg_logger_and_die(int pri, const char * fmt, ... )__attribute__ ((noreturn, format (printf, 2, 3))); +static void do_ioctl_and_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 messages */ + +static const char * const bb_msg_proto_rev = "protocol revision"; +static const char * const bb_msg_bad_config = "bad %s config file: %s"; +static const char * const bb_msg_small_buffer = "buffer too small"; +static const char * const bb_msg_variable_not_found = "variable: %s not found"; + +/* Busybox functions */ +static void msg_logger(int pri, const char * fmt, ... ) +{ + va_list ap; + int ret; + + va_start(ap, fmt); + ret = access ("/dev/log", F_OK); + if (ret == 0) { + openlog(applet_name, 0, LOG_DAEMON); + vsyslog( pri , fmt, ap); + /* Man: A trailing newline is added when needed. */ + closelog(); + } + /* ENABLE_DEVFSD_VERBOSE is always enabled if msg_logger is used */ + if ((ENABLE_DEVFSD_VERBOSE && ret) || ENABLE_DEBUG) { + bb_error_msg(fmt, ap); + } + va_end(ap); +} + +static void msg_logger_and_die(int pri, const char* fmt, ...) +{ + va_list ap; + + va_start(ap, fmt); + msg_logger(pri, fmt, ap); + va_end(ap); + exit(EXIT_FAILURE); +} + +/* Busybox stuff */ +#if defined(CONFIG_DEVFSD_VERBOSE) || defined(CONFIG_DEBUG) +#define devfsd_error_msg(fmt, args...) bb_error_msg(fmt, ## args) +#define devfsd_perror_msg_and_die(fmt, args...) bb_perror_msg_and_die(fmt, ## args) +#define devfsd_error_msg_and_die(fmt, args...) bb_error_msg_and_die(fmt, ## args) +#if defined(CONFIG_DEBUG) +#define debug_msg_logger(x, fmt, args...) msg_logger(x, fmt, ## args) +#else +#define debug_msg_logger(x, fmt, args...) +#endif +#else +#define debug_msg_logger(x, fmt, args...) +#define msg_logger(p, fmt, args...) +#define msg_logger_and_die(p, fmt, args...) exit(1) +#define devfsd_perror_msg_and_die(fmt, args...) exit(1) +#define devfsd_error_msg_and_die(fmt, args...) exit(1) +#define devfsd_error_msg(fmt, args...) +#endif + +static void do_ioctl_and_die(int fd, int request, unsigned long event_mask_flag) +{ + if (ioctl (fd, request, event_mask_flag) == -1) + msg_logger_and_die(LOG_ERR, "ioctl"); +} + +static void fork_and_execute(int die, char *arg0, char **arg ) +{ + switch ( fork () ) + { + case 0: + /* Child */ + break; + case -1: + /* Parent: Error : die or return */ + msg_logger(LOG_ERR,(char *) bb_msg_memory_exhausted); + if(die) + exit(EXIT_FAILURE); + 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); + msg_logger_and_die(LOG_ERR, "execvp"); + } +} + +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; + if(d[n - 2]=='c' && d[n - 1]=='d') + return 3 + addendum; + if(ptr[0]=='p' && ptr[1]=='a' && ptr[2]=='r' && ptr[3]=='t') + return 4 + addendum; + if(ptr[n - 2]=='m' && ptr[n - 1]=='t') + return 5 + addendum; + 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); + } + 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); + if(d[0]=='s' && d[1]=='b' && d[2]=='p' && d[3]=='/') + return 10; + if(d[0]=='v' && d[1]=='c' && d[2]=='c' && d[3]=='/') + return 11; + 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; + int do_daemon = TRUE; + int no_polling = FALSE; + 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; + else if(ENABLE_DEVFSD_FG_NP && argv[count][1]=='f' + && argv[count][2]=='g' && !argv[count][3]) /* -fg */ + do_daemon = FALSE; + else if(ENABLE_DEVFSD_FG_NP && argv[count][1]=='n' + && argv[count][2]=='p' && !argv[count][3]) /* -np */ + no_polling = TRUE; + 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) + devfsd_perror_msg_and_die(mount_point); + + fd = xopen (".devfsd", O_RDONLY); + + if (fcntl (fd, F_SETFD, FD_CLOEXEC) != 0) + devfsd_perror_msg_and_die("FD_CLOEXEC"); + + if (ioctl (fd, DEVFSDIOC_GET_PROTO_REV, &proto_rev) == -1) + msg_logger_and_die(LOG_ERR, "ioctl"); + + /*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) ) + { + printf( "%s v%s\nDaemon %s:\t%d\nKernel-side %s:\t%d\n", + 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_and_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 ) + devfsd_error_msg_and_die( "sigaction"); + + printf("%s v%s started for %s\n",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); + + if (ENABLE_DEVFSD_FG_NP && no_polling) + exit (0); + if (do_daemon) + { + /* Release so that the child can grab it */ + do_ioctl_and_die(fd, DEVFSDIOC_RELEASE_EVENT_QUEUE, 0); + fork_and_execute(DIE, NULL, NULL); + setsid (); /* Prevent hangups and become pgrp leader */ + } else if(ENABLE_DEVFSD_FG_NP) { + setpgid (0, 0); /* Become process group leader */ + } + + 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. + <path> The path to read the database from. If this is a directory, all + entries in that directory will be read (except hidden entries). + <optional> If TRUE, the routine will silently ignore a missing config file. + <event_mask> The event mask is written here. This is not initialised. + [RETURNS] Nothing. +*/ +{ + struct stat statbuf; + FILE *fp; + char buf[STRING_LENGTH]; + char *line=NULL; + + debug_msg_logger(LOG_INFO, "%s: %s", __FUNCTION__, path); + + if (stat (path, &statbuf) == 0 ) + { + /* Don't read 0 length files: ignored */ + /*if( statbuf.st_size == 0 ) + return;*/ + 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) + { + /* Skip whitespace */ + for (line = buf; isspace (*line); ++line) + /*VOID*/; + if (line[0] == '\0' || line[0] == '#' ) + continue; + process_config_line (line, event_mask); + } + fclose (fp); + } else { + goto read_config_file_err; + } + } else { +read_config_file_err: + if(optional == 0 && errno == ENOENT) + msg_logger_and_die(LOG_ERR, "read config file: %s: %m", path); + } + 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. + <line> The configuration line. + <event_mask> 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; + int i; + + /* !!!! Only Uppercase Keywords in devsfd.conf */ + static const char *const options[] = { + "CLEAR_CONFIG", "INCLUDE", "OPTIONAL_INCLUDE", + "RESTORE", "PERMISSIONS", "MODLOAD", "EXECUTE", + "COPY", "IGNORE", "MKOLDCOMPAT", "MKNEWCOMPAT", + "RMOLDCOMPAT", "RMNEWCOMPAT", 0 + }; + + debug_msg_logger(LOG_INFO, __FUNCTION__); + + 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 = index_in_str_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 ); + msg_logger(LOG_INFO, "%sinclude: %s",(toupper (when[0]) == 'I') ? "": "optional_", name); + 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 = index_in_str_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; + 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.*/ + if (ENABLE_DEVFSD_MODLOAD) + new->action.what = AC_MODLOAD; + break; + case 6: /* EXECUTE */ + new->action.what = AC_EXECUTE; + num_args -= 3; + + for (count = 0; count < num_args; ++count) + new->u.execute.argv[count] = 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 = xstrdup (p[0]); + new->u.copy.destination = 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: + msg_logger_and_die(LOG_ERR, bb_msg_bad_config, msg , line); +} /* End Function process_config_line */ + +static int do_servicing (int fd, unsigned long event_mask) +/* [SUMMARY] Service devfs changes until a signal is received. + <fd> The open control file. + <event_mask> The event mask. + [RETURNS] TRUE if SIGHUP was caught, else FALSE. +*/ +{ + ssize_t bytes; + struct devfsd_notify_struct info; + unsigned long tmp_event_mask; + + debug_msg_logger(LOG_INFO, __FUNCTION__); + + /* Tell devfs what events we care about */ + tmp_event_mask = event_mask; + do_ioctl_and_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; + } + msg_logger_and_die(LOG_ERR, "read error on control file"); +} /* End Function do_servicing */ + +static void service_name (const struct devfsd_notify_struct *info) +/* [SUMMARY] Service a single devfs change. + <info> The devfs change. + [RETURNS] Nothing. +*/ +{ + unsigned int n; + regmatch_t mbuf[MAX_SUBEXPR]; + struct config_entry_struct *entry; + + debug_msg_logger(LOG_INFO, __FUNCTION__); + if (ENABLE_DEBUG && info->overrun_count > 0) + debug_msg_logger(LOG_ERR, "lost %u events", info->overrun_count); + + /* 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 */; + + debug_msg_logger(LOG_INFO, "%s: action.what %d", __FUNCTION__, entry->action.what); + + switch (entry->action.what) + { + case AC_PERMISSIONS: + action_permissions (info, entry); + break; + case AC_MODLOAD: + if(ENABLE_DEVFSD_MODLOAD) + action_modload (info, entry); + break; + 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: + msg_logger_and_die(LOG_ERR, "Unknown action"); + } + } +} /* 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. + <info> The devfs change. + <entry> The config file entry. + [RETURNS] Nothing. +*/ +{ + struct stat statbuf; + + debug_msg_logger(LOG_INFO, __FUNCTION__); + + 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) + { + msg_logger(LOG_ERR, "Can't chmod or chown: %s: %m",info->devname); + } +} /* End Function action_permissions */ + +static void action_modload (const struct devfsd_notify_struct *info, + const struct config_entry_struct *entry ATTRIBUTE_UNUSED) +/* [SUMMARY] Load a module. + <info> The devfs change. + <entry> 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); + debug_msg_logger(LOG_INFO, "%s: %s %s %s %s %s",__FUNCTION__, argv[0],argv[1],argv[2],argv[3],argv[4]); + fork_and_execute(DIE, argv[0], argv); +} /* End Function action_modload */ + +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. + <info> The devfs change. + <entry> The config file entry. + <regexpr> The number of subexpression (start, end) offsets within the + device name. + <numexpr> The number of elements within <<regexpr>>. + [RETURNS] Nothing. +*/ +{ + unsigned int count; + struct get_variable_info gv_info; + char *argv[MAX_ARGS + 1]; + char largv[MAX_ARGS + 1][STRING_LENGTH]; + + debug_msg_logger(LOG_INFO ,__FUNCTION__); + 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; + 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. + <info> The devfs change. + <entry> The config file entry. + <regexpr> This list of subexpression (start, end) offsets within the + device name. + <numexpr> The number of elements in <<regexpr>>. + [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]; + int ret = 0; + + debug_msg_logger(LOG_INFO, __FUNCTION__); + + dest_stat.st_mode = 0; + + 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; + ret = copy_inode (destination, &dest_stat, new_mode, source, &source_stat); + if (ENABLE_DEBUG && ret && (errno != EEXIST)) + debug_msg_logger(LOG_ERR, "copy_inode: %s to %s: %m", source, destination); + return; +} /* End Function action_copy */ + +static void action_compat (const struct devfsd_notify_struct *info, unsigned int action) +/* [SUMMARY] Process a compatibility request. + <info> The devfs change. + <action> The action to take. + [RETURNS] Nothing. +*/ +{ + int ret; + 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" */ + static const char *const 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); + + debug_msg_logger(LOG_INFO, "%s: scan_dev_name = %d", __FUNCTION__, i); + + /* 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; + + debug_msg_logger( LOG_INFO, "%s: %s", __FUNCTION__, compat_name); + + /* 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: + ret = unlink (compat_name); + if (ENABLE_DEBUG && ret) + debug_msg_logger(LOG_ERR, "unlink: %s: %m", compat_name); + 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; + + debug_msg_logger(LOG_INFO, __FUNCTION__); + + 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. + <destpath> The destination path. An existing inode may be deleted. + <dest_stat> The destination stat(2) information. + <new_mode> The desired new mode for the destination. + <sourcepath> The source path. + <source_stat> 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]; + + debug_msg_logger(LOG_INFO, __FUNCTION__); + + 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 (void) +/* [SUMMARY] Free the configuration information. + [RETURNS] Nothing. +*/ +{ + struct config_entry_struct *c_entry; + void *next; + + debug_msg_logger(LOG_INFO, __FUNCTION__); + + 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. + <flag> "UID" or "GID". + <string> The string. + [RETURNS] The UID or GID value. +*/ +{ + struct passwd *pw_ent; + struct group *grp_ent; + static char *msg; + + if (ENABLE_DEVFSD_VERBOSE) + msg="user"; + + debug_msg_logger(LOG_INFO, __FUNCTION__); + + if(ENABLE_DEBUG && flag != UID && flag != GID) + msg_logger_and_die(LOG_ERR,"%s: flag != UID && flag != GID", __FUNCTION__); + + 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; + else if(ENABLE_DEVFSD_VERBOSE) + msg="group"; + + if(ENABLE_DEVFSD_VERBOSE) + msg_logger(LOG_ERR,"unknown %s: %s, defaulting to %cid=0", msg, string, msg[0]); + return 0; +}/* End Function get_uid_gid */ + +static mode_t get_mode (const char *string) +/* [SUMMARY] Convert a string to a mode value. + <string> The string. + [RETURNS] The mode value. +*/ +{ + mode_t mode; + int i; + + debug_msg_logger(LOG_INFO, __FUNCTION__); + + if ( isdigit (string[0]) ) + return strtoul(string, NULL, 8); + if (strlen (string) != 9) + msg_logger_and_die(LOG_ERR, "bad mode: %s", string); + + 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) +{ + debug_msg_logger(LOG_INFO, __FUNCTION__); + + caught_signal = TRUE; + if (sig == SIGHUP) + caught_sighup = TRUE; + + msg_logger(LOG_INFO, "Caught signal %d", sig); +} /* 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 }; + int i; + + debug_msg_logger(LOG_INFO, __FUNCTION__); + + if (gethostname (hostname, STRING_LENGTH - 1) != 0) + msg_logger_and_die(LOG_ERR, "gethostname: %m"); + + /* Here on error we should do exit(RV_SYS_ERROR), instead we do exit(EXIT_FAILURE) */ + hostname[STRING_LENGTH - 1] = '\0'; + + /* index_in_str_array returns i>=0 */ + i=index_in_str_array(field_names, variable); + + if ( i > 6 || i < 0 || (i > 1 && gv_info == NULL)) + return NULL; + if( i >= 0 && i <= 3) + { + debug_msg_logger(LOG_INFO, "%s: i=%d %s", __FUNCTION__, i ,field_names[i+7]); + 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); + + debug_msg_logger(LOG_INFO, "%s: %s", __FUNCTION__, sbuf); + + return sbuf; +} /* End Function get_variable */ + +static void service(struct stat statbuf, char *path) +{ + struct devfsd_notify_struct info; + + debug_msg_logger(LOG_INFO, __FUNCTION__); + + 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. + <flag> To choose which function to perform + <dp> The directory pointer. This is closed upon completion. + <dir_name> The name of the directory. + <rootlen> string length parameter. + [RETURNS] Nothing. +*/ +{ + struct stat statbuf; + DIR *dp; + struct dirent *de; + char path[STRING_LENGTH]; + + debug_msg_logger(LOG_INFO, __FUNCTION__); + + if((dp = opendir( dir_name))==NULL) + { + debug_msg_logger(LOG_ERR, "opendir: %s: %m", dir_name); + 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); + debug_msg_logger(LOG_ERR, "%s: %s", __FUNCTION__, path); + + if (lstat (path, &statbuf) != 0) + { + debug_msg_logger(LOG_ERR, "%s: %s: %m", __FUNCTION__, path); + 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. + <oldpath> The string contained in the symlink. + <newpath> The name of the new symlink. + [RETURNS] 0 on success, else -1. +*/ +{ + debug_msg_logger(LOG_INFO, __FUNCTION__); + + if ( !make_dir_tree (newpath) ) + return -1; + + if (symlink (oldpath, newpath) != 0) { + if (errno != EEXIST) { + debug_msg_logger(LOG_ERR, "%s: %s to %s: %m", __FUNCTION__, oldpath, newpath); + return -1; + } + } + return 0; +} /* End Function mksymlink */ + + +static int make_dir_tree (const char *path) +/* [SUMMARY] Creating intervening directories for a path as required. + <path> The full pathname (including the leaf node). + [RETURNS] TRUE on success, else FALSE. +*/ +{ + debug_msg_logger(LOG_INFO, __FUNCTION__); + + if (bb_make_directory( dirname((char *)path), -1, FILEUTILS_RECUR )==-1) + { + debug_msg_logger(LOG_ERR, "%s: %s: %m",__FUNCTION__, path); + 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. + <output> The output expanded expression is written here. + <length> The size of the output buffer. + <input> The input expression. This may equal <<output>>. + <get_variable> 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. + <info> An arbitrary pointer passed to <<get_variable>>. + <devname> Device name; specifically, this is the string that contains all + of the regular subexpressions. + <ex> Array of start / end offsets into info->devname for each subexpression + <numexp> Number of regular subexpressions found in <<devname>>. + [RETURNS] TRUE on success, else FALSE. +*/ +{ + char temp[STRING_LENGTH]; + + debug_msg_logger(LOG_INFO, __FUNCTION__); + + 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. + <output> The output expanded expression is written here. + <outsize> The size of the output buffer. + <input> The input expression. This may NOT equal <<output>>, 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. + <devname> Device name; specifically, this is the string that contains all + of the regular subexpressions. + <ex> An array of start and end offsets into <<devname>>, one for each + subexpression + <numex> Number of subexpressions in the offset-array <<ex>>. + [RETURNS] Nothing. +*/ +{ + const char last_exp = '0' - 1 + numex; + int c = -1; + + debug_msg_logger(LOG_INFO, __FUNCTION__); + + /* 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. + <devname> The device name provided by the kernel. + <namelen> The length of the name. + <buffer> A buffer that may be used. This should be at least 128 bytes long. + <major> The major number for the device. + <minor> 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/ */ + static const char *const 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 + }; + + debug_msg_logger(LOG_INFO, __FUNCTION__); + + 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; + + debug_msg_logger(LOG_INFO, "%s: scan_dev_name = %d", __FUNCTION__, i); + + /* 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 ) + /* last arg should be ignored for i == 6 or i== 7 */ + sprintf (buffer, fmt[i] , get_old_ide_name (major, minor), ptr + 4); + + /* 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]); + } + + if(ENABLE_DEBUG && compat_name!=NULL) + msg_logger(LOG_INFO, "%s: compat_name %s", __FUNCTION__, compat_name); + + 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. + <major> The major number for the device. + <minor> The minor number for the device. + [RETURNS] The drive letter. +*/ +{ + char letter='y'; /* 121 */ + char c='a'; /* 97 */ + int i=IDE0_MAJOR; + + debug_msg_logger(LOG_INFO, __FUNCTION__); + + /* 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((unsigned int)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. + <buffer> The buffer to write to. + <major> The major number for the device. + <minor> The minor number for the device. + <part> The partition string. Must be "" for a whole-disc entry. + [RETURNS] A pointer to the buffer on success, else NULL. +*/ +{ + unsigned int disc_index; + + debug_msg_logger(LOG_INFO, __FUNCTION__); + + 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. + <output> The output expanded expression is written here. + <length> The size of the output buffer. + <input> The input expression. This may equal <<output>>. + <get_variable> 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. + <info> An arbitrary pointer passed to <<get_variable>>. + [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]; + + debug_msg_logger(LOG_INFO, __FUNCTION__); + + 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 ) + { + msg_logger(LOG_INFO, bb_msg_variable_not_found, "HOME"); + 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 ) + { + msg_logger(LOG_INFO, "no pwent for: %s", tmp); + 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: + msg_logger(LOG_INFO, bb_msg_small_buffer); + 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. + <buffer> The buffer to write to. + <length> The length of the output buffer. + <out_pos> The current output position. This is updated. + <input> A pointer to the input character pointer. + <func> 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. + <info> An arbitrary pointer passed to <<func>>. + <errfp> 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]; + + debug_msg_logger(LOG_INFO, __FUNCTION__); + + 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 ((size_t)len >= sizeof tmp) + goto expand_variable_out; + + safe_memcpy (tmp, input, len); + input = ptr - 1; + if ( ( env = get_variable_v2 (tmp, func, info) ) == NULL ) + { + msg_logger(LOG_INFO, bb_msg_variable_not_found, tmp); + 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 ((size_t)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] != '-' ) + { + msg_logger(LOG_INFO, "illegal char in var name"); + return NULL; + } + /* It's that handy "${var:-word}" expression. Check if var is defined */ + len = ptr - input; + if ((size_t)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': + msg_logger(LOG_INFO,"\"}\" not found in: %s", input); + 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 ((size_t)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: + msg_logger(LOG_INFO, bb_msg_small_buffer); + 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 . + <variable> The variable name. + <func> 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; + + debug_msg_logger(LOG_INFO, __FUNCTION__); + + 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/miscutils/eject.c b/miscutils/eject.c new file mode 100644 index 0000000..ff23b16 --- /dev/null +++ b/miscutils/eject.c @@ -0,0 +1,60 @@ +/* vi: set sw=4 ts=4: */ +/* + * eject implementation for busybox + * + * Copyright (C) 2004 Peter Willis <psyphreak@phreaker.net> + * Copyright (C) 2005 Tito Ragusa <farmatito@tiscali.it> + * + * Licensed under the GPL v2 or later, see the file LICENSE in this tarball. + */ + +/* + * This is a simple hack of eject based on something Erik posted in #uclibc. + * Most of the dirty work blatantly ripped off from cat.c =) + */ + +#include "busybox.h" + +/* various defines swiped from linux/cdrom.h */ +#define CDROMCLOSETRAY 0x5319 /* pendant of CDROMEJECT */ +#define CDROMEJECT 0x5309 /* Ejects the cdrom media */ +#define CDROM_DRIVE_STATUS 0x5326 /* Get tray position, etc. */ +/* drive status possibilities returned by CDROM_DRIVE_STATUS ioctl */ +#define CDS_TRAY_OPEN 2 + +#define FLAG_CLOSE 1 +#define FLAG_SMART 2 + +int eject_main(int argc, char **argv) +{ + unsigned long flags; + char *device; + int dev, cmd; + + opt_complementary = "?:?1:t--T:T--t"; + flags = getopt32(argc, argv, "tT"); + device = argv[optind] ? : "/dev/cdrom"; + + // We used to do "umount <device>" here, but it was buggy + // if something was mounted OVER cdrom and + // if cdrom is mounted many times. + // + // This works equally well (or better): + // #!/bin/sh + // umount /dev/cdrom + // eject + + dev = xopen(device, O_RDONLY|O_NONBLOCK); + cmd = CDROMEJECT; + if (flags & FLAG_CLOSE + || (flags & FLAG_SMART && ioctl(dev, CDROM_DRIVE_STATUS) == CDS_TRAY_OPEN)) + cmd = CDROMCLOSETRAY; + if (ioctl(dev, cmd)) { + bb_perror_msg_and_die("%s", device); + } + + if (ENABLE_FEATURE_CLEAN_UP) + close(dev); + + return EXIT_SUCCESS; +} diff --git a/miscutils/hdparm.c b/miscutils/hdparm.c new file mode 100644 index 0000000..90c1639 --- /dev/null +++ b/miscutils/hdparm.c @@ -0,0 +1,2184 @@ +/* vi: set sw=4 ts=4: */ +/* + * hdparm implementation for busybox + * + * Copyright (C) [2003] by [Matteo Croce] <3297627799@wind.it> + * Hacked by Tito <farmatito@tiscali.it> for size optimization. + * + * Licensed under the GPL v2 or later, see the file LICENSE in this tarball. + * + * 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 "busybox.h" +#include <linux/hdreg.h> + +/* 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 * const 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 * const 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 0x22 +#ifdef CONFIG_FEATURE_HDPARM_GET_IDENTITY +static const char *minor_str[MINOR_MAX+2] = { /* word 81 value: */ + "Unspecified", /* 0x0000 */ + "ATA-1 X3T9.2 781D prior to rev.4", /* 0x0001 */ + "ATA-1 published, ANSI X3.221-1994", /* 0x0002 */ + "ATA-1 X3T9.2 781D rev.4", /* 0x0003 */ + "ATA-2 published, ANSI X3.279-1996", /* 0x0004 */ + "ATA-2 X3T10 948D prior to rev.2k", /* 0x0005 */ + "ATA-3 X3T10 2008D rev.1", /* 0x0006 */ + "ATA-2 X3T10 948D rev.2k", /* 0x0007 */ + "ATA-3 X3T10 2008D rev.0", /* 0x0008 */ + "ATA-2 X3T10 948D rev.3", /* 0x0009 */ + "ATA-3 published, ANSI X3.298-199x", /* 0x000a */ + "ATA-3 X3T10 2008D rev.6", /* 0x000b */ + "ATA-3 X3T13 2008D rev.7 and 7a", /* 0x000c */ + "ATA/ATAPI-4 X3T13 1153D rev.6", /* 0x000d */ + "ATA/ATAPI-4 T13 1153D rev.13", /* 0x000e */ + "ATA/ATAPI-4 X3T13 1153D rev.7", /* 0x000f */ + "ATA/ATAPI-4 T13 1153D rev.18", /* 0x0010 */ + "ATA/ATAPI-4 T13 1153D rev.15", /* 0x0011 */ + "ATA/ATAPI-4 published, ANSI INCITS 317-1998", /* 0x0012 */ + "ATA/ATAPI-5 T13 1321D rev.3", + "ATA/ATAPI-4 T13 1153D rev.14", /* 0x0014 */ + "ATA/ATAPI-5 T13 1321D rev.1", /* 0x0015 */ + "ATA/ATAPI-5 published, ANSI INCITS 340-2000", /* 0x0016 */ + "ATA/ATAPI-4 T13 1153D rev.17", /* 0x0017 */ + "ATA/ATAPI-6 T13 1410D rev.0", /* 0x0018 */ + "ATA/ATAPI-6 T13 1410D rev.3a", /* 0x0019 */ + "ATA/ATAPI-7 T13 1532D rev.1", /* 0x001a */ + "ATA/ATAPI-6 T13 1410D rev.2", /* 0x001b */ + "ATA/ATAPI-6 T13 1410D rev.1", /* 0x001c */ + "ATA/ATAPI-7 published, ANSI INCITS 397-2005", /* 0x001d */ + "ATA/ATAPI-7 T13 1532D rev.0", /* 0x001e */ + "Reserved" /* 0x001f */ + "Reserved" /* 0x0020 */ + "ATA/ATAPI-7 T13 1532D rev.4a", /* 0x0021 */ + "ATA/ATAPI-6 published, ANSI INCITS 361-2002", /* 0x0022 */ + "Reserved" /* 0x0023-0xfffe*/ +}; +#endif +static const char actual_ver[MINOR_MAX+2] = { + /* 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: */ + 7, /* 0x001a WARNING: */ + 6, /* 0x001b WARNING: */ + 6, /* 0x001c WARNING: */ + 7, /* 0x001d WARNING: */ + 7, /* 0x001e WARNING: */ + 0, /* 0x001f WARNING: */ + 0, /* 0x0020 WARNING: */ + 7, /* 0x0021 WARNING: */ + 6, /* 0x0022 WARNING: */ + 0 /* 0x0023-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 * const 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 cmd", /* word 83 bit 13 */ + "Mandatory FLUSH CACHE cmd ", /* 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 */ +}; + +static void identify(uint16_t *id_supplied) ATTRIBUTE_NORETURN; +static void identify_from_stdin(void) ATTRIBUTE_NORETURN; +#else +void identify_from_stdin(void); +#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 * const 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 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 */ +static int bb_ioctl(int fd, int request, void *argp, const char *string) +{ + int e = ioctl(fd, request, argp); + if (e && string) + bb_perror_msg(" %s", string); + return e; +} + +static int bb_ioctl_alt(int fd, int cmd, unsigned char *args, int alt, const char *string) +{ + if (!ioctl(fd, cmd, args)) + return 0; + args[0] = alt; + return bb_ioctl(fd, cmd, args, string); +} + +static void on_off(unsigned int value); + +static void print_flag_on_off(unsigned long get_arg, const char *s, unsigned long arg) +{ + + if (get_arg) + { + printf(" setting %s to %ld", s, arg); + on_off(arg); + } +} + +static void bb_ioctl_on_off(int fd, int request, void *argp, const char *string, + const char * str) +{ + if (ioctl(fd, request, &argp) != 0) + bb_perror_msg(" %s", string); + else + { + printf(" %s\t= %2ld", str, (unsigned long) argp); + on_off((unsigned long) argp); + } +} + +#ifdef CONFIG_FEATURE_HDPARM_GET_IDENTITY +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); + } +} +#endif +/* 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 (cl != '\0') printf("%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++; + } + puts(""); +} + +// Parse 512 byte disk identification block and print much crap. + +static void identify(uint16_t *id_supplied) +{ + uint16_t buf[256]; + uint16_t *val, 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; + uint64_t bbbig; /* (:) */ + const char *strng; + + // Adjust for endianness if necessary. + + if (BB_BIG_ENDIAN) { + swab(id_supplied, buf, sizeof(buf)); + val = buf; + } else val = id_supplied; + + chksum &= 0xff; + + /* check if we recognise the device type */ + puts(""); + 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"); + + printf("%sremovable media\n", !(val[GEN_CONFIG] & MEDIA_REMOVABLE) ? "non-" : ""); + /* 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 ((val[CONFIG]==STBY_NID_VAL) || (val[CONFIG]==STBY_ID_VAL)) + printf("powers-up in standby; SET FEATURES subcmd spins-up.\n"); + if (((val[CONFIG]==STBY_NID_VAL) || (val[CONFIG]==PWRD_NID_VAL)) && (val[GEN_CONFIG] & INCOMPLETE)) + printf("\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)) + { + if (like_std < 3) like_std = 3; + std = actual_ver[val[MINOR]]; + if (std) printf("\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; + } + if (min_std > ii) min_std = ii; + } + jj <<= 1; + } + if (like_std < 3) 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. + */ + if (like_std < std) 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 + puts(""); + } + 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 (jj & 0x0001) printf("-%u ", ii); + jj >>= 1; + } + } + printf("%s\n", (!kk) ? "\n\tLikely used CD-ROM ATAPI-1" : "" ); + /* 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 (jj & 0x0001) printf("\t%s\n",ata1_cfg_str[ii]); + jj >>=1; + } + } + if (dev == ATAPI_DEV) + { + if ((val[GEN_CONFIG] & DRQ_RESPONSE_TIME) == DRQ_3MS_VAL) + strng = "3ms"; + else if ((val[GEN_CONFIG] & DRQ_RESPONSE_TIME) == DRQ_INTR_VAL) + strng = "<=10ms with INTRQ"; + else if ((val[GEN_CONFIG] & DRQ_RESPONSE_TIME) == DRQ_50US_VAL) + strng ="50us"; + else + strng = "Unknown"; + printf("\tDRQ response: %s\n\tPacket size: ", strng); /* Data Request (DRQ) */ + + if ((val[GEN_CONFIG] & PKT_SIZE_SUPPORTED) == PKT_SIZE_12_VAL) + strng = "12 bytes"; + else if ((val[GEN_CONFIG] & PKT_SIZE_SUPPORTED) == PKT_SIZE_16_VAL) + strng = "16 bytes"; + else + strng = "Unknown"; + puts(strng); + } + 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 ((min_std == 1) && (val[TRACK_BYTES] || val[SECT_BYTES])) + printf("\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 = (uint64_t)val[LBA_64_MSB] << 48 | + (uint64_t)val[LBA_48_MSB] << 32 | + (uint64_t)val[LBA_MID] << 16 | + val[LBA_LSB] ; + printf("\tLBA48 user addressable sectors:%11"PRIu64"\n",bbbig); + } + + if (!bbbig) + bbbig = (uint64_t)(ll>mm ? ll : mm); /* # 512 byte blocks */ + printf("\tdevice size with M = 1024*1024: %11"PRIu64" MBytes\n",bbbig>>11); + bbbig = (bbbig<<9)/1000000; + printf("\tdevice size with M = 1000*1000: %11"PRIu64" MBytes ",bbbig); + + if (bbbig > 1000) + printf("(%"PRIu64" GB)\n", bbbig/1000); + else + puts(""); + } + + /* hw support of commands (capabilities) */ + printf("Capabilities:\n\t"); + + if (dev == ATAPI_DEV) + { + if (eqpt != CDROM && (val[CAPAB_0] & CMD_Q_SUP)) printf("Cmd queuing, "); + if (val[CAPAB_0] & OVLP_SUP) printf("Cmd overlap, "); + } + if (val[CAPAB_0] & LBA_SUP) printf("LBA, "); + + if (like_std != 1) + { + printf("IORDY%s(can%s be disabled)\n", + !(val[CAPAB_0] & IORDY_SUP) ? "(may be)" : "", + (val[CAPAB_0] & IORDY_OFF) ? "" :"not"); + } + else + printf("no IORDY\n"); + + if ((like_std == 1) && val[BUF_TYPE]) + { + printf("\tBuffer type: %04x: %s%s\n", val[BUF_TYPE], + (val[BUF_TYPE] < 2) ? "single port, single-sector" : "dual port, multi-sector", + (val[BUF_TYPE] > 2) ? " with read caching ability" : ""); + } + + if ((min_std == 1) && (val[BUFFER__SIZE] && (val[BUFFER__SIZE] != NOVAL_1))) + { + printf("\tBuffer size: %.1fkB\n",(float)val[BUFFER__SIZE]/2); + } + if ((min_std < 4) && (val[RW_LONG])) + { + printf("\tbytes avail on r/w long: %u\n",val[RW_LONG]); + } + if ((eqpt != CDROM) && (like_std > 3)) + { + printf("\tQueue depth: %u\n",(val[QUEUE_DEPTH] & DEPTH_BITS)+1); + } + + 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 %s", (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 + puts(""); + } + 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 (val[SECTOR_XFER_CUR] & MULTIPLE_SETTING_VALID) + printf("%u\n", val[SECTOR_XFER_CUR] & SECTOR_XFER); + else + printf("?\n"); + } + 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 && val[ACOUSTIC]) { + printf("\tRecommended acoustic management value: %u, current value: %u\n", + (val[ACOUSTIC] >> 8) & 0x00ff, val[ACOUSTIC] & 0x00ff); + } + } + else + { + /* ATAPI */ + if (eqpt != CDROM && (val[CAPAB_0] & SWRST_REQ)) + printf("\tATA sw reset required\n"); + + if (val[PKT_REL] || val[SVC_NBSY]) + { + printf("\tOverlap support:"); + if (val[PKT_REL]) printf(" %uus to release bus.",val[PKT_REL]); + if (val[SVC_NBSY]) printf(" %uus to clear BSY after SERVICE cmd.",val[SVC_NBSY]); + puts(""); + } + } + + /* DMA stuff. Check that only one DMA mode is selected. */ + printf("\tDMA: "); + if (!(val[CAPAB_0] & DMA_SUP)) + printf("not supported\n"); + else + { + if (val[DMA_MODE] && !val[SINGLE_DMA] && !val[MULTI_DMA]) + printf(" 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 (err_dma || !have_mode) printf("(?)"); + puts(""); + + if ((dev == ATAPI_DEV) && (eqpt != CDROM) && (val[CAPAB_0] & DMA_IL_SUP)) + printf("\t\tInterleaved DMA support\n"); + + if ((val[WHATS_VALID] & OK_W64_70) && + (val[DMA_TIME_MIN] || val[DMA_TIME_NORM])) + { + printf("\t\tCycle time:"); + if (val[DMA_TIME_MIN]) printf(" min=%uns",val[DMA_TIME_MIN]); + if (val[DMA_TIME_NORM]) printf(" recommended=%uns",val[DMA_TIME_NORM]); + puts(""); + } + } + + /* 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 (jj & 0x0001) printf("pio%d ",ii); + jj >>=1; + } + puts(""); + } + else if (((min_std < 5) || (eqpt == CDROM)) && (val[PIO_MODE] & MODE) ) + { + for (ii = 0; ii <= val[PIO_MODE]>>8; ii++) + printf("pio%d ",ii); + puts(""); + } + else + printf("unknown\n"); + + if (val[WHATS_VALID] & OK_W64_70) + { + if (val[PIO_NO_FLOW] || val[PIO_FLOW]) + { + printf("\t\tCycle time:"); + if (val[PIO_NO_FLOW]) printf(" no flow control=%uns", val[PIO_NO_FLOW]); + if (val[PIO_FLOW]) printf(" IORDY flow control=%uns", val[PIO_FLOW]); + puts(""); + } + } + + 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')) + { + printf("\t%s\t%s\n", (kk & 0x8000) ? " *" : "", 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; + } + } + } + /* Removable Media Status Notification feature set */ + if ((val[RM_STAT] & RM_STAT_BITS) == RM_STAT_SUP) + printf("\t%s supported\n", cmd_feat_str[27]); + + + /* security */ + if ((eqpt != CDROM) && (like_std > 3) && + (val[SECU_STATUS] || val[ERASE_TIME] || val[ENH_ERASE_TIME])) + { + printf("Security:\n"); + if (val[PSWD_CODE] && (val[PSWD_CODE] != NOVAL_1)) + printf("\tMaster password revision code = %u\n",val[PSWD_CODE]); + jj = val[SECU_STATUS]; + if (jj) + { + for (ii = 0; ii < NUM_SECU_STR; ii++) + { + printf("\t%s\t%s\n", (!(jj & 0x0001)) ? "not" : "", secu_str[ii]); + jj >>=1; + } + if (val[SECU_STATUS] & SECU_ENABLED) + { + printf("\tSecurity level %s\n", (val[SECU_STATUS] & SECU_LEVEL) ? "maximum" : "high"); + } + } + jj = val[ERASE_TIME] & ERASE_BITS; + kk = val[ENH_ERASE_TIME] & ERASE_BITS; + if (jj || kk) + { + printf("\t"); + if (jj) printf("%umin for %sSECURITY ERASE UNIT. ", jj==ERASE_BITS ? 508 : jj<<1, ""); + if (kk) printf("%umin for %sSECURITY ERASE UNIT. ", kk==ERASE_BITS ? 508 : kk<<1, "ENHANCED "); + puts(""); + } + } + + /* reset result */ + jj = val[HWRST_RSLT]; + if ((jj & VALID) == VALID_VAL) + { + if (!(oo = (jj & RST0))) + jj >>= 8; + if ((jj & DEV_DET) == JUMPER_VAL) + strng = " determined by the jumper"; + else if ((jj & DEV_DET) == CSEL_VAL) + strng = " determined by CSEL"; + else + strng = ""; + printf("HW reset results:\n\tCBLID- %s Vih\n\tDevice num = %i%s\n", + (val[HWRST_RSLT] & CBLID) ? "above" : "below", !(oo), strng); + } + + /* 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%s%s\n", (val[CFA_PWR_MODE] & PWR_MODE_OFF) ? "disabled" : "enabled", + (val[CFA_PWR_MODE] & PWR_MODE_REQ) ? " and required by some commands" : ""); + + if (val[CFA_PWR_MODE] & MAX_AMPS) printf("\tMaximum current = %uma\n",val[CFA_PWR_MODE] & MAX_AMPS); + } + if ((val[INTEGRITY] & SIG) == SIG_VAL) + { + printf("Checksum: %scorrect\n", chksum ? "in" : ""); + } + } + + exit(EXIT_SUCCESS); +} +#endif + +static int get_identity, get_geom; +static int do_flush; +static int do_ctimings, do_timings; +static unsigned long set_readahead, get_readahead, Xreadahead; +static unsigned long set_readonly, get_readonly, readonly; +static unsigned long set_unmask, get_unmask, unmask; +static unsigned long set_mult, get_mult, mult; +#ifdef CONFIG_FEATURE_HDPARM_HDIO_GETSET_DMA +static unsigned long set_dma, get_dma, dma; +#endif +static unsigned long set_dma_q, get_dma_q, dma_q; +static unsigned long set_nowerr, get_nowerr, nowerr; +static unsigned long set_keep, get_keep, keep; +static unsigned long set_io32bit, get_io32bit, io32bit; +static unsigned long set_piomode, noisy_piomode; +static int piomode; +#ifdef HDIO_DRIVE_CMD +static unsigned long set_dkeep, get_dkeep, dkeep; +static unsigned long set_standby, get_standby, standby_requested; +static unsigned long set_xfermode, get_xfermode; +static int xfermode_requested; +static unsigned long set_lookahead, get_lookahead, lookahead; +static unsigned long set_prefetch, get_prefetch, prefetch; +static unsigned long set_defects, get_defects, defects; +static unsigned long set_wcache, get_wcache, wcache; +static unsigned long set_doorlock, get_doorlock, doorlock; +static unsigned long set_seagate, get_seagate; +static unsigned long set_standbynow, get_standbynow; +static unsigned long set_sleepnow, get_sleepnow; +static unsigned long get_powermode; +static unsigned long set_apmmode, get_apmmode, apmmode; +#endif +#ifdef CONFIG_FEATURE_HDPARM_GET_IDENTITY +static int get_IDentity; +#endif +#ifdef CONFIG_FEATURE_HDPARM_HDIO_UNREGISTER_HWIF +static unsigned long unregister_hwif; +static unsigned long hwif; +#endif +#ifdef CONFIG_FEATURE_HDPARM_HDIO_SCAN_HWIF +static unsigned long scan_hwif; +static unsigned long hwif_data; +static unsigned long hwif_ctrl; +static unsigned long hwif_irq; +#endif +#ifdef CONFIG_FEATURE_HDPARM_HDIO_TRISTATE_HWIF +static unsigned long set_busstate, get_busstate, busstate; +#endif +static int reread_partn; + +#ifdef CONFIG_FEATURE_HDPARM_HDIO_DRIVE_RESET +static int perform_reset; +#endif /* CONFIG_FEATURE_HDPARM_HDIO_DRIVE_RESET */ +#ifdef CONFIG_FEATURE_HDPARM_HDIO_TRISTATE_HWIF +static unsigned long perform_tristate, tristate; +#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 * const 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 * const BuffType[] = {"Unknown", "1Sect", "DualPort", "DualPortCache"}; + +static void dump_identity(const struct hd_driveid *id) +{ + int i; + const unsigned short int *id_regs= (const void*) id; + + 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 (id->config & (1<<i)) + printf(" %s", cfg_str[i]); + } + printf( " }\n RawCHS=%u/%u/%u, TrkSize=%u, SectSize=%u, ECCbytes=%u\n" + " BuffType=(%u) %s, BuffSize=%ukB, MaxMultSect=%u", + id->cyls, id->heads, id->sectors, id->track_bytes, + id->sector_bytes, id->ecc_bytes, + id->buf_type, BuffType[(id->buf_type > 3) ? 0 : id->buf_type], + 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"); + } + puts(""); + + if (!(id->field_valid&1)) + printf(" (maybe):"); + + printf(" CurCHS=%u/%u/%u, CurSects=%lu, LBA=%s",id->cur_cyls, id->cur_heads, + id->cur_sectors, + (BB_BIG_ENDIAN) ? + (long unsigned int)(id->cur_capacity0 << 16) | id->cur_capacity1 : + (long unsigned int)(id->cur_capacity1 << 16) | id->cur_capacity0, + ((id->capability&2) == 0) ? "no" : "yes"); + + if (id->capability&2) + printf(", LBAsects=%u", id->lba_capacity); + + printf("\n IORDY=%s", (id->capability&8) ? (id->capability&4) ? "on/off" : "yes" : "no"); + + if (((id->capability&8) || (id->field_valid&2)) && id->field_valid&2) + printf(", tPIO={min:%u,w/IORDY:%u}", id->eide_pio, id->eide_pio_iordy); + + if ((id->capability&1) && (id->field_valid&2)) + printf(", tDMA={min:%u,rec:%u}", id->eide_dma_min, id->eide_dma_time); + + printf("\n PIO modes: "); + if (id->tPIO <= 5) + { + printf("pio0 "); + if (id->tPIO >= 1) printf("pio1 "); + if (id->tPIO >= 2) printf("pio2 "); + } + if (id->field_valid&2) + { + if (id->eide_pio_modes & 1) printf("pio3 "); + if (id->eide_pio_modes & 2) printf("pio4 "); + if (id->eide_pio_modes &~3) printf("pio? "); + } + if (id->capability&1) + { + if (id->dma_1word | id->dma_mword) + { + printf("\n DMA modes: "); + if (id->dma_1word & 0x100) printf("*"); + if (id->dma_1word & 1) printf("sdma0 "); + if (id->dma_1word & 0x200) printf("*"); + if (id->dma_1word & 2) printf("sdma1 "); + if (id->dma_1word & 0x400) printf("*"); + if (id->dma_1word & 4) printf("sdma2 "); + if (id->dma_1word & 0xf800) printf("*"); + if (id->dma_1word & 0xf8) printf("sdma? "); + if (id->dma_mword & 0x100) printf("*"); + if (id->dma_mword & 1) printf("mdma0 "); + if (id->dma_mword & 0x200) printf("*"); + if (id->dma_mword & 2) printf("mdma1 "); + if (id->dma_mword & 0x400) printf("*"); + if (id->dma_mword & 4) printf("mdma2 "); + if (id->dma_mword & 0xf800) printf("*"); + if (id->dma_mword & 0xf8) printf("mdma? "); + } + } + if (((id->capability&8) || (id->field_valid&2)) && id->field_valid&4) + { + printf("\n UDMA modes: "); + if (id->dma_ultra & 0x100) printf("*"); + if (id->dma_ultra & 0x001) printf("udma0 "); + if (id->dma_ultra & 0x200) printf("*"); + if (id->dma_ultra & 0x002) printf("udma1 "); + if (id->dma_ultra & 0x400) printf("*"); + if (id->dma_ultra & 0x004) printf("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 (id->dma_ultra & 0x0800) printf("*"); + if (id->dma_ultra & 0x0008) printf("udma3 "); + if (id->dma_ultra & 0x1000) printf("*"); + if (id->dma_ultra & 0x0010) printf("udma4 "); + if (id->dma_ultra & 0x2000) printf("*"); + if (id->dma_ultra & 0x0020) printf("udma5 "); + if (id->dma_ultra & 0x4000) printf("*"); + if (id->dma_ultra & 0x0040) printf("udma6 "); + if (id->dma_ultra & 0x8000) printf("*"); + if (id->dma_ultra & 0x0080) printf("udma7 "); + } + } + 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 (id_regs[82]&0x20) + printf(" 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: %s: ", (id->minor_rev_num <= 31) ? minor_str[id->minor_rev_num] : "Unknown"); + if (id->major_rev_num != 0x0000 && /* NOVAL_0 */ + id->major_rev_num != 0xFFFF) { /* NOVAL_1 */ + for (i=0; i <= 15; i++) { + if (id->major_rev_num & (1<<i)) + printf(" ATA/ATAPI-%u", i); + } + } + } +#endif /* __NEW_HD_DRIVE_ID */ + printf("\n\n * current active mode\n\n"); +} +#endif + +static void flush_buffer_cache(int fd) +{ + fsync(fd); /* flush buffers */ + bb_ioctl(fd, BLKFLSBUF, NULL,"BLKFLSBUF" ) ;/* do it again, big time */ +#ifdef HDIO_DRIVE_CMD + sleep(1); + if (ioctl(fd, HDIO_DRIVE_CMD, NULL) && errno != EINVAL) /* await completion */ + bb_perror_msg("HDIO_DRIVE_CMD"); +#endif +} + +static int seek_to_zero(int fd) +{ + if (lseek(fd, (off_t) 0, SEEK_SET)) + return 1; + return 0; +} + +static int read_big_block(int fd, char *buf) +{ + int i; + + if ((i = read(fd, buf, TIMING_BUF_BYTES)) != TIMING_BUF_BYTES) { + bb_error_msg("read(%d bytes) failed (rc=%d)", TIMING_BUF_BYTES, i); + return 1; + } + /* access all sectors of buf to ensure the read fully completed */ + for (i = 0; i < TIMING_BUF_BYTES; i += 512) + buf[i] &= 1; + return 0; +} + +static void print_timing(int t, double e) +{ + if (t >= e) /* more than 1MB/s */ + printf("%2d MB in %5.2f seconds =%6.2f %cB/sec\n", t, e, t / e, 'M'); + else + printf("%2d MB in %5.2f seconds =%6.2f %cB/sec\n", t, e, t / e * 1024, 'k'); +} + +static int do_blkgetsize (int fd, unsigned long long *blksize64) +{ + int rc; + unsigned int blksize32 = 0; + + if (0 == ioctl(fd, BLKGETSIZE64, blksize64)) { // returns bytes + *blksize64 /= 512; + return 0; + } + rc = ioctl(fd, BLKGETSIZE, &blksize32); // returns sectors + if (rc) + bb_perror_msg("BLKGETSIZE"); + *blksize64 = blksize32; + return rc; +} + +static void do_time(int flag, int fd) +/* + flag = 0 time_cache + flag = 1 time_device +*/ +{ + struct itimerval e1, e2; + double elapsed, elapsed2; + unsigned int max_iterations = 1024, total_MB, iterations; + unsigned long long blksize; + RESERVE_CONFIG_BUFFER(buf, TIMING_BUF_BYTES); + + if (mlock(buf, TIMING_BUF_BYTES)) { + bb_perror_msg("mlock"); + goto quit2; + } + + if (0 == do_blkgetsize(fd, &blksize)) { + max_iterations = blksize / (2 * 1024) / TIMING_BUF_MB; + } + + /* Clear out the device request queues & give them time to complete */ + sync(); + sleep(3); + + setitimer(ITIMER_REAL, &(struct itimerval){{1000,0},{1000,0}}, NULL); + + if (flag == 0) /* Time cache */ + { + if (seek_to_zero (fd)) return; + if (read_big_block (fd, buf)) return; + printf(" Timing cached reads: "); + fflush(stdout); + + /* Now do the timing */ + iterations = 0; + getitimer(ITIMER_REAL, &e1); + do { + ++iterations; + if (seek_to_zero (fd) || 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); + } while (elapsed < 2.0); + total_MB = iterations * TIMING_BUF_MB; + + /* Now remove the lseek() and getitimer() overheads from the elapsed time */ + getitimer(ITIMER_REAL, &e1); + do { + if (seek_to_zero (fd)) + goto quit; + getitimer(ITIMER_REAL, &e2); + elapsed2 = (e1.it_value.tv_sec - e2.it_value.tv_sec) + + ((e1.it_value.tv_usec - e2.it_value.tv_usec) / 1000000.0); + } while (--iterations); + + elapsed -= elapsed2; + print_timing(BUFCACHE_FACTOR * total_MB, elapsed); + 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). + */ + /* Now do the timings for real */ + iterations = 0; + getitimer(ITIMER_REAL, &e1); + do { + ++iterations; + 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); + } while (elapsed < 3.0 && iterations < max_iterations); + + total_MB = iterations * TIMING_BUF_MB; + print_timing(total_MB, elapsed); + } +quit: + munlock(buf, TIMING_BUF_BYTES); +quit2: + RELEASE_CONFIG_BUFFER(buf); +} + +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) +{ + if (value == BUSSTATE_ON) + on_off(1); + else if (value == BUSSTATE_OFF) + on_off(0); + else if (value == BUSSTATE_TRISTATE) + printf(" (tristate)\n"); + else + printf(" (unknown: %d)\n", value); +} +#endif + +#ifdef HDIO_DRIVE_CMD +static void interpret_standby(unsigned int standby) +{ + unsigned int t; + + printf(" ("); + if (standby == 0) + printf("off"); + else if (standby == 252) + printf("21 minutes"); + else if (standby == 253) + printf("vendor-specific"); + else if (standby == 254) + printf("Reserved"); + else if (standby == 255) + printf("21 minutes + 15 seconds"); + else { + if (standby <= 240) { + t = standby * 5; + printf("%u minutes + %u seconds", t / 60, t % 60); + } else if (standby <= 251) { + t = (standby - 240) * 30; + printf("%u hours + %u minutes", t / 60, t % 60); + } else + printf("illegal value"); + } + 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(" ("); + if (xfermode == 0) + printf("default PIO mode"); + else if (xfermode == 1) + printf("default PIO mode, disable IORDY"); + else if (xfermode >= 8 && xfermode <= 15) + printf("PIO flow control mode%u", xfermode-8); + else if (xfermode >= 16 && xfermode <= 23) + printf("singleword DMA mode%u", xfermode-16); + else if (xfermode >= 32 && xfermode <= 39) + printf("multiword DMA mode%u", xfermode-32); + else if (xfermode >= 64 && xfermode <= 71) + printf("UltraDMA mode%u", xfermode-64); + else + printf("Unknown"); + printf(")\n"); +} +#endif /* HDIO_DRIVE_CMD */ + +static void print_flag(unsigned long flag, char *s, unsigned long value) +{ + if (flag) + printf(" setting %s to %ld\n", s, value); +} + +static void process_dev(char *devname) +{ + int fd; + static long parm, multcount; +#ifndef HDIO_DRIVE_CMD + int force_operation = 0; +#endif + /* Please restore args[n] to these values after each ioctl + except for args[2] */ + unsigned char args[4] = {WIN_SETFEATURES,0,0,0}; + const char *fmt = " %s\t= %2ld"; + + fd = xopen(devname, O_RDONLY|O_NONBLOCK); + printf("\n%s:\n", devname); + + if (set_readahead) + { + print_flag(get_readahead,"fs readahead", Xreadahead); + bb_ioctl(fd, BLKRASET,(int *)Xreadahead,"BLKRASET"); + } +#ifdef CONFIG_FEATURE_HDPARM_HDIO_UNREGISTER_HWIF + if (unregister_hwif) + { + printf(" attempting to unregister hwif#%lu\n", hwif); + bb_ioctl(fd, HDIO_UNREGISTER_HWIF,(int *)(unsigned long)hwif,"HDIO_UNREGISTER_HWIF"); + } +#endif +#ifdef CONFIG_FEATURE_HDPARM_HDIO_SCAN_HWIF + if (scan_hwif) + { + printf(" attempting to scan hwif (0x%lx, 0x%lx, %lu)\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"); + args[0] = WIN_SETFEATURES; + args[1] = 0; + } +#endif + if (set_piomode) + { + 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 *)(unsigned long)piomode, "HDIO_SET_PIO_MODE"); + } + if (set_io32bit) + { + print_flag(get_io32bit,"32-bit IO_support flag", io32bit); + bb_ioctl(fd, HDIO_SET_32BIT, (int *)io32bit, "HDIO_SET_32BIT"); + } + if (set_mult) + { + print_flag(get_mult, "multcount", mult); +#ifdef HDIO_DRIVE_CMD + bb_ioctl(fd, HDIO_SET_MULTCOUNT, &mult, "HDIO_SET_MULTCOUNT"); +#else + force_operation |= (!bb_ioctl(fd, HDIO_SET_MULTCOUNT, &mult, "HDIO_SET_MULTCOUNT")); +#endif + } + if (set_readonly) + { + print_flag_on_off(get_readonly,"readonly", readonly); + bb_ioctl(fd, BLKROSET, &readonly, "BLKROSET"); + } + if (set_unmask) + { + print_flag_on_off(get_unmask,"unmaskirq", unmask); + bb_ioctl(fd, HDIO_SET_UNMASKINTR, (int *)unmask, "HDIO_SET_UNMASKINTR"); + } +#ifdef CONFIG_FEATURE_HDPARM_HDIO_GETSET_DMA + if (set_dma) + { + print_flag_on_off(get_dma, "using_dma", dma); + bb_ioctl(fd, HDIO_SET_DMA, (int *)dma, "HDIO_SET_DMA"); + } +#endif /* CONFIG_FEATURE_HDPARM_HDIO_GETSET_DMA */ + if (set_dma_q) + { + print_flag_on_off(get_dma_q,"DMA queue_depth", dma_q); + bb_ioctl(fd, HDIO_SET_QDMA, (int *)dma_q, "HDIO_SET_QDMA"); + } + if (set_nowerr) + { + print_flag_on_off(get_nowerr,"nowerr", nowerr); + bb_ioctl(fd, HDIO_SET_NOWERR, (int *)nowerr,"HDIO_SET_NOWERR"); + } + if (set_keep) + { + print_flag_on_off(get_keep,"keep_settings", keep); + bb_ioctl(fd, HDIO_SET_KEEPSETTINGS, (int *)keep,"HDIO_SET_KEEPSETTINGS"); + } +#ifdef HDIO_DRIVE_CMD + if (set_doorlock) + { + args[0] = doorlock ? WIN_DOORLOCK : WIN_DOORUNLOCK; + args[2] = 0; + print_flag_on_off(get_doorlock,"drive doorlock", doorlock); + bb_ioctl(fd, HDIO_DRIVE_CMD, &args,"HDIO_DRIVE_CMD(doorlock)"); + args[0] = WIN_SETFEATURES; + } + if (set_dkeep) + { + /* lock/unlock the drive's "feature" settings */ + print_flag_on_off(get_dkeep,"drive keep features", dkeep); + args[2] = dkeep ? 0x66 : 0xcc; + bb_ioctl(fd, HDIO_DRIVE_CMD, &args,"HDIO_DRIVE_CMD(keepsettings)"); + } + if (set_defects) + { + args[2] = defects ? 0x04 : 0x84; + print_flag(get_defects,"drive defect-mgmt", defects); + bb_ioctl(fd, HDIO_DRIVE_CMD, &args,"HDIO_DRIVE_CMD(defectmgmt)"); + } + if (set_prefetch) + { + args[1] = prefetch; + args[2] = 0xab; + print_flag(get_prefetch,"drive prefetch", prefetch); + bb_ioctl(fd, HDIO_DRIVE_CMD, &args, "HDIO_DRIVE_CMD(setprefetch)"); + args[1] = 0; + } + if (set_xfermode) + { + args[1] = xfermode_requested; + args[2] = 3; + if (get_xfermode) + { + print_flag(1,"xfermode", xfermode_requested); + interpret_xfermode(xfermode_requested); + } + bb_ioctl(fd, HDIO_DRIVE_CMD, &args,"HDIO_DRIVE_CMD(setxfermode)"); + args[1] = 0; + } + if (set_lookahead) + { + args[2] = lookahead ? 0xaa : 0x55; + print_flag_on_off(get_lookahead,"drive read-lookahead", lookahead); + bb_ioctl(fd, HDIO_DRIVE_CMD, &args, "HDIO_DRIVE_CMD(setreadahead)"); + } + if (set_apmmode) + { + args[2] = (apmmode == 255) ? 0x85 /* disable */ : 0x05 /* set */; /* feature register */ + args[1] = apmmode; /* sector count register 1-255 */ + if (get_apmmode) + printf(" setting APM level to %s 0x%02lX (%ld)\n", (apmmode == 255) ? "disabled" : "", apmmode, apmmode); + bb_ioctl(fd, HDIO_DRIVE_CMD, &args,"HDIO_DRIVE_CMD"); + args[1] = 0; + } + if (set_wcache) + { +#ifdef DO_FLUSHCACHE +#ifndef WIN_FLUSHCACHE +#define WIN_FLUSHCACHE 0xe7 +#endif + static unsigned char flushcache[4] = {WIN_FLUSHCACHE,0,0,0}; +#endif /* DO_FLUSHCACHE */ + args[2] = wcache ? 0x02 : 0x82; + print_flag_on_off(get_wcache,"drive write-caching", wcache); +#ifdef DO_FLUSHCACHE + if (!wcache) + bb_ioctl(fd, HDIO_DRIVE_CMD, &flushcache, "HDIO_DRIVE_CMD(flushcache)"); +#endif /* DO_FLUSHCACHE */ + bb_ioctl(fd, HDIO_DRIVE_CMD, &args, "HDIO_DRIVE_CMD(setcache)"); +#ifdef DO_FLUSHCACHE + if (!wcache) + bb_ioctl(fd, HDIO_DRIVE_CMD, &flushcache, "HDIO_DRIVE_CMD(flushcache)"); +#endif /* DO_FLUSHCACHE */ + } + + /* In code below, we do not preserve args[0], but the rest + is preserved, including args[2] */ + args[2] = 0; + + if (set_standbynow) + { +#ifndef WIN_STANDBYNOW1 +#define WIN_STANDBYNOW1 0xE0 +#endif +#ifndef WIN_STANDBYNOW2 +#define WIN_STANDBYNOW2 0x94 +#endif + if (get_standbynow) printf(" issuing standby command\n"); + args[0] = WIN_STANDBYNOW1; + bb_ioctl_alt(fd, HDIO_DRIVE_CMD, args, WIN_STANDBYNOW2, "HDIO_DRIVE_CMD(standby)"); + } + if (set_sleepnow) + { +#ifndef WIN_SLEEPNOW1 +#define WIN_SLEEPNOW1 0xE6 +#endif +#ifndef WIN_SLEEPNOW2 +#define WIN_SLEEPNOW2 0x99 +#endif + if (get_sleepnow) printf(" issuing sleep command\n"); + args[0] = WIN_SLEEPNOW1; + bb_ioctl_alt(fd, HDIO_DRIVE_CMD, args, WIN_SLEEPNOW2, "HDIO_DRIVE_CMD(sleep)"); + } + if (set_seagate) + { + args[0] = 0xfb; + if (get_seagate) printf(" disabling Seagate auto powersaving mode\n"); + bb_ioctl(fd, HDIO_DRIVE_CMD, &args, "HDIO_DRIVE_CMD(seagatepwrsave)"); + } + if (set_standby) + { + args[0] = WIN_SETIDLE1; + args[1] = standby_requested; + if (get_standby) + { + print_flag(1,"standby", standby_requested); + interpret_standby(standby_requested); + } + bb_ioctl(fd, HDIO_DRIVE_CMD, &args, "HDIO_DRIVE_CMD(setidle1)"); + args[1] = 0; + } +#else /* HDIO_DRIVE_CMD */ + if (force_operation) + { + char buf[512]; + flush_buffer_cache(fd); + if (-1 == read(fd, buf, sizeof(buf))) + bb_perror_msg("read(%d bytes) failed (rc=%d)", sizeof(buf), -1); + } +#endif /* HDIO_DRIVE_CMD */ + + if (get_mult || get_identity) + { + multcount = -1; + if (ioctl(fd, HDIO_GET_MULTCOUNT, &multcount)) + { + if (get_mult) + bb_perror_msg("HDIO_GET_MULTCOUNT"); + } + else if (get_mult) + { + printf(fmt, "multcount", multcount); + on_off(multcount); + } + } + if (get_io32bit) + { + if (!bb_ioctl(fd, HDIO_GET_32BIT, &parm, "HDIO_GET_32BIT")) + { + printf(" IO_support\t=%3ld (", parm); + if (parm == 0) + printf("default 16-bit)\n"); + else if (parm == 2) + printf("16-bit)\n"); + else if (parm == 1) + printf("32-bit)\n"); + else if (parm == 3) + printf("32-bit w/sync)\n"); + else if (parm == 8) + printf("Request-Queue-Bypass)\n"); + else + printf("\?\?\?)\n"); + } + } + if (get_unmask) + { + bb_ioctl_on_off(fd, HDIO_GET_UNMASKINTR,(unsigned long *)parm, + "HDIO_GET_UNMASKINTR","unmaskirq"); + } + + +#ifdef CONFIG_FEATURE_HDPARM_HDIO_GETSET_DMA + if (get_dma) { + if (!bb_ioctl(fd, HDIO_GET_DMA, &parm, "HDIO_GET_DMA")) + { + printf(fmt, "using_dma", parm); + if (parm == 8) + printf(" (DMA-Assisted-PIO)\n"); + else + on_off(parm); + } + } +#endif + if (get_dma_q) + { + bb_ioctl_on_off (fd, HDIO_GET_QDMA,(unsigned long *)parm, + "HDIO_GET_QDMA","queue_depth"); + } + if (get_keep) + { + bb_ioctl_on_off (fd, HDIO_GET_KEEPSETTINGS,(unsigned long *)parm, + "HDIO_GET_KEEPSETTINGS","keepsettings"); + } + + if (get_nowerr) + { + bb_ioctl_on_off (fd, HDIO_GET_NOWERR,(unsigned long *)&parm, + "HDIO_GET_NOWERR","nowerr"); + } + if (get_readonly) + { + bb_ioctl_on_off(fd, BLKROGET,(unsigned long *)parm, + "BLKROGET","readonly"); + } + if (get_readahead) + { + bb_ioctl_on_off (fd, BLKRAGET, (unsigned long *) parm, + "BLKRAGET","readahead"); + } + if (get_geom) + { + if (!bb_ioctl(fd, BLKGETSIZE, &parm, "BLKGETSIZE")) + { + struct hd_geometry g; + + if (!bb_ioctl(fd, HDIO_GETGEO, &g, "HDIO_GETGEO")) + printf(" geometry\t= %u/%u/%u, sectors = %ld, start = %ld\n", + 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 + const char *state; + + args[0] = WIN_CHECKPOWERMODE1; + if (bb_ioctl_alt(fd, HDIO_DRIVE_CMD, args, WIN_CHECKPOWERMODE2, 0)) + { + if (errno != EIO || args[0] != 0 || args[1] != 0) + state = "Unknown"; + else + state = "sleeping"; + } + else + state = (args[2] == 255) ? "active/idle" : "standby"; + args[1] = args[2] = 0; + + printf(" drive state is: %s\n", state); + } +#endif +#ifdef CONFIG_FEATURE_HDPARM_HDIO_DRIVE_RESET + if (perform_reset) + { + 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) + { + args[0] = 0; + args[1] = tristate; + 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; + + 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 args1[4+512]; /* = { ... } will eat 0.5k of rodata! */ + + memset(args1, 0, sizeof(args1)); + args1[0] = WIN_IDENTIFY; + args1[3] = 1; + if (!bb_ioctl_alt(fd, HDIO_DRIVE_CMD, args1, WIN_PIDENTIFY, "HDIO_DRIVE_CMD(identify)")) + identify((void *)(args1 + 4)); + } +#endif +#ifdef CONFIG_FEATURE_HDPARM_HDIO_TRISTATE_HWIF + if (set_busstate) + { + if (get_busstate) + { + print_flag(1, "bus state", busstate); + bus_state_value(busstate); + } + bb_ioctl(fd, HDIO_SET_BUSSTATE, (int *)(unsigned long)busstate, "HDIO_SET_BUSSTATE"); + } + if (get_busstate) + { + if (!bb_ioctl(fd, HDIO_GET_BUSSTATE, &parm, "HDIO_GET_BUSSTATE")) + { + printf(fmt, "bus state", 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); +} + +#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 void identify_from_stdin(void) +{ + uint16_t sbuf[256]; + unsigned char buf[1280], *b = (unsigned char *)buf; + int i, count = read(0, buf, 1280); + + if (count != 1280) + bb_error_msg_and_die("read(%d bytes) failed (rc=%d)", 1280, count); + + // Convert the newline-separated hex data into an identify block. + + for (i = 0; i<256; i++) + { + int j; + for(j=0;j<4;j++) sbuf[i] = (sbuf[i] <<4) + fromhex(*(b++)); + } + + // Parse the data. + + identify(sbuf); +} +#endif + +/* busybox specific stuff */ +static void parse_opts(unsigned long *get, unsigned long *set, unsigned long *value, int min, int max) +{ + if (get) { + *get = 1; + } + if (optarg) { + *set = 1; + *value = xatol_range(optarg, min, max); + } +} + +static void parse_xfermode(int flag, unsigned long *get, unsigned long *set, int *value) +{ + if (flag) { + *get = 1; + if (optarg) { + *set = ((*value = translate_xfermode(optarg)) > -1); + } + } +} + +/*------- getopt short options --------*/ +static const char hdparm_options[] = "gfu::n::p:r::m::c::k::a::B:tTh" + USE_FEATURE_HDPARM_GET_IDENTITY("iI") + USE_FEATURE_HDPARM_HDIO_GETSET_DMA("d::") +#ifdef HDIO_DRIVE_CMD + "S:D:P:X:K:A:L:W:CyYzZ" +#endif + USE_FEATURE_HDPARM_HDIO_UNREGISTER_HWIF("U:") +#ifdef HDIO_GET_QDMA +#ifdef HDIO_SET_QDMA + "Q:" +#else + "Q" +#endif +#endif + USE_FEATURE_HDPARM_HDIO_DRIVE_RESET("w") + USE_FEATURE_HDPARM_HDIO_TRISTATE_HWIF("x::b:") + USE_FEATURE_HDPARM_HDIO_SCAN_HWIF("R:"); +/*-------------------------------------*/ + +/* our main() routine: */ +int hdparm_main(int argc, char **argv) ATTRIBUTE_NORETURN; +int hdparm_main(int argc, char **argv) +{ + int c; + int flagcount = 0; + + while ((c = getopt(argc, argv, hdparm_options)) >= 0) { + flagcount++; + if (c == 'h') bb_show_usage(); /* EXIT */ + USE_FEATURE_HDPARM_GET_IDENTITY(get_IDentity |= (c == 'I')); + USE_FEATURE_HDPARM_GET_IDENTITY(get_identity |= (c == 'i')); + get_geom |= (c == 'g'); + do_flush |= (c == 'f'); + if (c == 'u') parse_opts(&get_unmask, &set_unmask, &unmask, 0, 1); + USE_FEATURE_HDPARM_HDIO_GETSET_DMA(if (c == 'd') parse_opts(&get_dma, &set_dma, &dma, 0, 9)); + if (c == 'n') parse_opts(&get_nowerr, &set_nowerr, &nowerr, 0, 1); + parse_xfermode((c == 'p'),&noisy_piomode, &set_piomode, &piomode); + if (c == 'r') parse_opts(&get_readonly, &set_readonly, &readonly, 0, 1); + if (c == 'm') parse_opts(&get_mult, &set_mult, &mult, 0, INT_MAX /*32*/); + if (c == 'c') parse_opts(&get_io32bit, &set_io32bit, &io32bit, 0, INT_MAX /*8*/); + if (c == 'k') parse_opts(&get_keep, &set_keep, &keep, 0, 1); + if (c == 'a') parse_opts(&get_readahead, &set_readahead, &Xreadahead, 0, INT_MAX); + if (c == 'B') parse_opts(&get_apmmode, &set_apmmode, &apmmode, 1, 255); + do_flush |= do_timings |= (c == 't'); + do_flush |= do_ctimings |= (c == 'T'); +#ifdef HDIO_DRIVE_CMD + if (c == 'S') parse_opts(&get_standby, &set_standby, &standby_requested, 0, INT_MAX); + if (c == 'D') parse_opts(&get_defects, &set_defects, &defects, 0, INT_MAX); + if (c == 'P') parse_opts(&get_prefetch, &set_prefetch, &prefetch, 0, INT_MAX); + parse_xfermode((c == 'X'), &get_xfermode, &set_xfermode, &xfermode_requested); + if (c == 'K') parse_opts(&get_dkeep, &set_dkeep, &prefetch, 0, 1); + if (c == 'A') parse_opts(&get_lookahead, &set_lookahead, &lookahead, 0, 1); + if (c == 'L') parse_opts(&get_doorlock, &set_doorlock, &doorlock, 0, 1); + if (c == 'W') parse_opts(&get_wcache, &set_wcache, &wcache, 0, 1); + get_powermode |= (c == 'C'); + get_standbynow = set_standbynow |= (c == 'y'); + get_sleepnow = set_sleepnow |= (c == 'Y'); + reread_partn |= (c == 'z'); + get_seagate = set_seagate |= (c == 'Z'); +#endif + USE_FEATURE_HDPARM_HDIO_UNREGISTER_HWIF(if (c == 'U') parse_opts(NULL, &unregister_hwif, &hwif, 0, INT_MAX)); +#ifdef HDIO_GET_QDMA + if (c == 'Q') { +#ifdef HDIO_SET_QDMA + parse_opts(&get_dma_q, &set_dma_q, &dma_q, 0, INT_MAX); +#else + parse_opts(&get_dma_q, NULL, NULL, 0, 0); +#endif + } +#endif + USE_FEATURE_HDPARM_HDIO_DRIVE_RESET(perform_reset = (c == 'r')); + USE_FEATURE_HDPARM_HDIO_TRISTATE_HWIF(if (c == 'x') parse_opts(NULL, &perform_tristate, &tristate, 0, 1)); + USE_FEATURE_HDPARM_HDIO_TRISTATE_HWIF(if (c == 'b') parse_opts(&get_busstate, &set_busstate, &busstate, 0, 2)); +#if ENABLE_FEATURE_HDPARM_HDIO_SCAN_HWIF + if (c == 'R') { + parse_opts(NULL, &scan_hwif, &hwif_data, 0, INT_MAX); + hwif_ctrl = xatoi_u((argv[optind]) ? argv[optind] : ""); + hwif_irq = xatoi_u((argv[optind+1]) ? argv[optind+1] : ""); + /* Move past the 2 additional arguments */ + argv += 2; + argc -= 2; + } +#endif + } + /* When no flags are given (flagcount = 0), -acdgkmnru is assumed. */ + if (!flagcount) { + get_mult = get_io32bit = get_unmask = get_keep = get_readonly = get_readahead = get_geom = 1; + USE_FEATURE_HDPARM_HDIO_GETSET_DMA(get_dma = 1); + } + argc -= optind; + argv += optind; + + if (argc < 1) { + if (ENABLE_FEATURE_HDPARM_GET_IDENTITY && !isatty(STDIN_FILENO)) + identify_from_stdin(); /* EXIT */ + else bb_show_usage(); + } + + while (argc--) { + process_dev(*argv); + argv++; + } + exit(EXIT_SUCCESS); +} diff --git a/miscutils/last.c b/miscutils/last.c new file mode 100644 index 0000000..668f0c1 --- /dev/null +++ b/miscutils/last.c @@ -0,0 +1,91 @@ +/* vi: set sw=4 ts=4: */ +/* + * last implementation for busybox + * + * Copyright (C) 2003-2004 by Erik Andersen <andersen@codepoet.org> + * + * Licensed under the GPL version 2, see the file LICENSE in this tarball. + */ + +#include "busybox.h" +#include <utmp.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 defined UT_LINESIZE \ + && ((UT_LINESIZE != 32) || (UT_NAMESIZE != 32) || (UT_HOSTSIZE != 256)) +#error struct utmp member char[] size(s) have changed! +#elif defined __UT_LINESIZE \ + && ((__UT_LINESIZE != 32) || (__UT_NAMESIZE != 64) || (__UT_HOSTSIZE != 256)) +#error struct utmp member char[] size(s) have changed! +#endif + +int last_main(int argc, char **argv) +{ + struct utmp ut; + int n, file = STDIN_FILENO; + time_t t_tmp; + + if (argc > 1) { + bb_show_usage(); + } + file = xopen(bb_path_wtmp_file, 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; + } + } + t_tmp = (time_t)ut.ut_tv.tv_sec; + printf("%-10s %-14s %-18s %-12.12s\n", ut.ut_user, ut.ut_line, ut.ut_host, + ctime(&t_tmp) + 4); + } + + fflush_stdout_and_exit(EXIT_SUCCESS); +} diff --git a/miscutils/less.c b/miscutils/less.c new file mode 100644 index 0000000..03ffd78 --- /dev/null +++ b/miscutils/less.c @@ -0,0 +1,1144 @@ +/* vi: set sw=4 ts=4: */ +/* + * Mini less implementation for busybox + * + * Copyright (C) 2005 by Rob Sullivan <cogito.ergo.cogito@gmail.com> + * + * Licensed under the GPL v2 or later, see the file LICENSE in this tarball. + */ + +/* + * This program needs a lot of development, so consider it in a beta stage + * at best. + * + * TODO: + * - Add more regular expression support - search modifiers, certain matches, etc. + * - Add more complex bracket searching - currently, nested brackets are + * not considered. + * - Add support for "F" as an input. This causes less to act in + * a similar way to tail -f. + * - Check for binary files, and prompt the user if a binary file + * is detected. + * - Allow horizontal scrolling. Currently, lines simply continue onto + * the next line, per the terminal's discretion + * + * Notes: + * - filename is an array and not a pointer because that avoids all sorts + * of complications involving the fact that something that is pointed to + * will be changed if the pointer is changed. + * - the inp file pointer is used so that keyboard input works after + * redirected input has been read from stdin +*/ + +#include "busybox.h" + +#ifdef CONFIG_FEATURE_LESS_REGEXP +#include "xregex.h" +#endif + + +/* These are the escape sequences corresponding to special keys */ +#define REAL_KEY_UP 'A' +#define REAL_KEY_DOWN 'B' +#define REAL_KEY_RIGHT 'C' +#define REAL_KEY_LEFT 'D' +#define REAL_PAGE_UP '5' +#define REAL_PAGE_DOWN '6' +#define REAL_KEY_HOME '7' +#define REAL_KEY_END '8' + +/* These are the special codes assigned by this program to the special keys */ +#define KEY_UP 20 +#define KEY_DOWN 21 +#define KEY_RIGHT 22 +#define KEY_LEFT 23 +#define PAGE_UP 24 +#define PAGE_DOWN 25 +#define KEY_HOME 26 +#define KEY_END 27 + +/* The escape codes for highlighted and normal text */ +#define HIGHLIGHT "\033[7m" +#define NORMAL "\033[0m" + +/* The escape code to clear the screen */ +#define CLEAR "\033[H\033[J" + +/* Maximum number of lines in a file */ +#define MAXLINES 10000 + +static int height; +static int width; +static char **files; +static char filename[256]; +static char **buffer; +static char **flines; +static int current_file = 1; +static int line_pos; +static int num_flines; +static int num_files = 1; + +/* Command line options */ +static unsigned flags; +#define FLAG_E 1 +#define FLAG_M (1<<1) +#define FLAG_m (1<<2) +#define FLAG_N (1<<3) +#define FLAG_TILDE (1<<4) +/* hijack command line options variable for internal state vars */ +#define LESS_STATE_INP_STDIN (1<<5) +#define LESS_STATE_PAST_EOF (1<<6) +#define LESS_STATE_MATCH_BACKWARDS (1<<7) +/* INP_STDIN is used to change behaviour when input comes from stdin */ + +#ifdef CONFIG_FEATURE_LESS_MARKS +static int mark_lines[15][2]; +static int num_marks; +#endif + +#ifdef CONFIG_FEATURE_LESS_REGEXP +static int match_found; +static int *match_lines; +static int match_pos; +static int num_matches; +static regex_t old_pattern; +#endif + +/* Needed termios structures */ +static struct termios term_orig, term_vi; + +/* File pointer to get input from */ +static FILE *inp; + +/* Reset terminal input to normal */ +static void set_tty_cooked(void) +{ + fflush(stdout); + tcsetattr(fileno(inp), TCSANOW, &term_orig); +} + +/* Exit the program gracefully */ +static void tless_exit(int code) +{ + /* TODO: We really should save the terminal state when we start, + and restore it when we exit. Less does this with the + "ti" and "te" termcap commands; can this be done with + only termios.h? */ + + putchar('\n'); + fflush_stdout_and_exit(code); +} + +/* Grab a character from input without requiring the return key. If the + character is ASCII \033, get more characters and assign certain sequences + special return codes. Note that this function works best with raw input. */ +static int tless_getch(void) +{ + int input; + /* Set terminal input to raw mode (taken from vi.c) */ + tcsetattr(fileno(inp), TCSANOW, &term_vi); + + input = getc(inp); + /* Detect escape sequences (i.e. arrow keys) and handle + them accordingly */ + + if (input == '\033' && getc(inp) == '[') { + unsigned int i; + input = getc(inp); + set_tty_cooked(); + + i = input - REAL_KEY_UP; + if (i < 4) + return 20 + i; + else if ((i = input - REAL_PAGE_UP) < 4) + return 24 + i; + } + /* The input is a normal ASCII value */ + else { + set_tty_cooked(); + return input; + } + return 0; +} + +/* Move the cursor to a position (x,y), where (0,0) is the + top-left corner of the console */ +static void move_cursor(int x, int y) +{ + printf("\033[%i;%iH", x, y); +} + +static void clear_line(void) +{ + move_cursor(height, 0); + printf("\033[K"); +} + +/* This adds line numbers to every line, as the -N flag necessitates */ +static void add_linenumbers(void) +{ + int i; + + for (i = 0; i <= num_flines; i++) { + char *new = xasprintf("%5d %s", i + 1, flines[i]); + free(flines[i]); + flines[i] = new; + } +} + +static void data_readlines(void) +{ + int i; + char current_line[256]; + FILE *fp; + + fp = (flags & LESS_STATE_INP_STDIN) ? stdin : xfopen(filename, "r"); + flines = NULL; + for (i = 0; (feof(fp)==0) && (i <= MAXLINES); i++) { + strcpy(current_line, ""); + fgets(current_line, 256, fp); + if (fp != stdin) + die_if_ferror(fp, filename); + flines = xrealloc(flines, (i+1) * sizeof(char *)); + flines[i] = xstrdup(current_line); + } + num_flines = i - 2; + + /* Reset variables for a new file */ + + line_pos = 0; + flags &= ~LESS_STATE_PAST_EOF; + + fclose(fp); + + if (inp == NULL) + inp = (flags & LESS_STATE_INP_STDIN) ? xfopen(CURRENT_TTY, "r") : stdin; + + if (flags & FLAG_N) + add_linenumbers(); +} + +#ifdef CONFIG_FEATURE_LESS_FLAGS + +/* Interestingly, writing calc_percent as a function and not a prototype saves around 32 bytes + * on my build. */ +static int calc_percent(void) +{ + return ((100 * (line_pos + height - 2) / num_flines) + 1); +} + +/* Print a status line if -M was specified */ +static void m_status_print(void) +{ + int percentage; + + if (!(flags & LESS_STATE_PAST_EOF)) { + if (!line_pos) { + if (num_files > 1) + printf("%s%s %s%i%s%i%s%i-%i/%i ", HIGHLIGHT, + filename, "(file ", current_file, " of ", num_files, ") lines ", + line_pos + 1, line_pos + height - 1, num_flines + 1); + else { + printf("%s%s lines %i-%i/%i ", HIGHLIGHT, + filename, line_pos + 1, line_pos + height - 1, + num_flines + 1); + } + } + else { + printf("%s %s lines %i-%i/%i ", HIGHLIGHT, filename, + line_pos + 1, line_pos + height - 1, num_flines + 1); + } + + if (line_pos == num_flines - height + 2) { + printf("(END) %s", NORMAL); + if ((num_files > 1) && (current_file != num_files)) + printf("%s- Next: %s%s", HIGHLIGHT, files[current_file], NORMAL); + } + else { + percentage = calc_percent(); + printf("%i%% %s", percentage, NORMAL); + } + } + else { + printf("%s%s lines %i-%i/%i (END) ", HIGHLIGHT, filename, + line_pos + 1, num_flines + 1, num_flines + 1); + if ((num_files > 1) && (current_file != num_files)) + printf("- Next: %s", files[current_file]); + printf("%s", NORMAL); + } +} + +/* Print a status line if -m was specified */ +static void medium_status_print(void) +{ + int percentage; + percentage = calc_percent(); + + if (!line_pos) + printf("%s%s %i%%%s", HIGHLIGHT, filename, percentage, NORMAL); + else if (line_pos == num_flines - height + 2) + printf("%s(END)%s", HIGHLIGHT, NORMAL); + else + printf("%s%i%%%s", HIGHLIGHT, percentage, NORMAL); +} +#endif + +/* Print the status line */ +static void status_print(void) +{ + /* Change the status if flags have been set */ +#ifdef CONFIG_FEATURE_LESS_FLAGS + if (flags & FLAG_M) + m_status_print(); + else if (flags & FLAG_m) + medium_status_print(); + /* No flags set */ + else { +#endif + if (!line_pos) { + printf("%s%s %s", HIGHLIGHT, filename, NORMAL); + if (num_files > 1) + printf("%s%s%i%s%i%s%s", HIGHLIGHT, "(file ", + current_file, " of ", num_files, ")", NORMAL); + } + else if (line_pos == num_flines - height + 2) { + printf("%s%s %s", HIGHLIGHT, "(END)", NORMAL); + if ((num_files > 1) && (current_file != num_files)) + printf("%s%s%s%s", HIGHLIGHT, "- Next: ", files[current_file], NORMAL); + } + else { + putchar(':'); + } +#ifdef CONFIG_FEATURE_LESS_FLAGS + } +#endif +} + +/* Print the buffer */ +static void buffer_print(void) +{ + int i; + + printf("%s", CLEAR); + if (num_flines >= height - 2) { + for (i = 0; i < height - 1; i++) + printf("%s", buffer[i]); + } + else { + for (i = 1; i < (height - 1 - num_flines); i++) + putchar('\n'); + for (i = 0; i < height - 1; i++) + printf("%s", buffer[i]); + } + + status_print(); +} + +/* Initialise the buffer */ +static void buffer_init(void) +{ + int i; + + if (buffer == NULL) { + /* malloc the number of lines needed for the buffer */ + buffer = xrealloc(buffer, height * sizeof(char *)); + } else { + for (i = 0; i < (height - 1); i++) + free(buffer[i]); + } + + /* Fill the buffer until the end of the file or the + end of the buffer is reached */ + for (i = 0; (i < (height - 1)) && (i <= num_flines); i++) { + buffer[i] = xstrdup(flines[i]); + } + + /* If the buffer still isn't full, fill it with blank lines */ + for (; i < (height - 1); i++) { + buffer[i] = xstrdup(""); + } +} + +/* Move the buffer up and down in the file in order to scroll */ +static void buffer_down(int nlines) +{ + int i; + + if (!(flags & LESS_STATE_PAST_EOF)) { + if (line_pos + (height - 3) + nlines < num_flines) { + line_pos += nlines; + for (i = 0; i < (height - 1); i++) { + free(buffer[i]); + buffer[i] = xstrdup(flines[line_pos + i]); + } + } + else { + /* As the number of lines requested was too large, we just move + to the end of the file */ + while (line_pos + (height - 3) + 1 < num_flines) { + line_pos += 1; + for (i = 0; i < (height - 1); i++) { + free(buffer[i]); + buffer[i] = xstrdup(flines[line_pos + i]); + } + } + } + + /* We exit if the -E flag has been set */ + if ((flags & FLAG_E) && (line_pos + (height - 2) == num_flines)) + tless_exit(0); + } +} + +static void buffer_up(int nlines) +{ + int i; + int tilde_line; + + if (!(flags & LESS_STATE_PAST_EOF)) { + if (line_pos - nlines >= 0) { + line_pos -= nlines; + for (i = 0; i < (height - 1); i++) { + free(buffer[i]); + buffer[i] = xstrdup(flines[line_pos + i]); + } + } + else { + /* As the requested number of lines to move was too large, we + move one line up at a time until we can't. */ + while (line_pos != 0) { + line_pos -= 1; + for (i = 0; i < (height - 1); i++) { + free(buffer[i]); + buffer[i] = xstrdup(flines[line_pos + i]); + } + } + } + } + else { + /* Work out where the tildes start */ + tilde_line = num_flines - line_pos + 3; + + line_pos -= nlines; + /* Going backwards nlines lines has taken us to a point where + nothing is past the EOF, so we revert to normal. */ + if (line_pos < num_flines - height + 3) { + flags &= ~LESS_STATE_PAST_EOF; + buffer_up(nlines); + } + else { + /* We only move part of the buffer, as the rest + is past the EOF */ + for (i = 0; i < (height - 1); i++) { + free(buffer[i]); + if (i < tilde_line - nlines + 1) + buffer[i] = xstrdup(flines[line_pos + i]); + else { + if (line_pos >= num_flines - height + 2) + buffer[i] = xstrdup("~\n"); + } + } + } + } +} + +static void buffer_line(int linenum) +{ + int i; + flags &= ~LESS_STATE_PAST_EOF; + + if (linenum < 0 || linenum > num_flines) { + clear_line(); + printf("%s%s%i%s", HIGHLIGHT, "Cannot seek to line number ", linenum + 1, NORMAL); + } + else if (linenum < (num_flines - height - 2)) { + for (i = 0; i < (height - 1); i++) { + free(buffer[i]); + buffer[i] = xstrdup(flines[linenum + i]); + } + line_pos = linenum; + buffer_print(); + } + else { + for (i = 0; i < (height - 1); i++) { + free(buffer[i]); + if (linenum + i < num_flines + 2) + buffer[i] = xstrdup(flines[linenum + i]); + else + buffer[i] = xstrdup((flags & FLAG_TILDE) ? "\n" : "~\n"); + } + line_pos = linenum; + /* Set past_eof so buffer_down and buffer_up act differently */ + flags |= LESS_STATE_PAST_EOF; + buffer_print(); + } +} + +/* Reinitialise everything for a new file - free the memory and start over */ +static void reinitialise(void) +{ + int i; + + for (i = 0; i <= num_flines; i++) + free(flines[i]); + free(flines); + + data_readlines(); + buffer_init(); + buffer_print(); +} + +static void examine_file(void) +{ + int newline_offset; + + clear_line(); + printf("Examine: "); + fgets(filename, 256, inp); + + /* As fgets adds a newline to the end of an input string, we + need to remove it */ + newline_offset = strlen(filename) - 1; + filename[newline_offset] = '\0'; + + files[num_files] = xstrdup(filename); + current_file = num_files + 1; + num_files++; + + flags &= ~LESS_STATE_INP_STDIN; + reinitialise(); +} + +/* This function changes the file currently being paged. direction can be one of the following: + * -1: go back one file + * 0: go to the first file + * 1: go forward one file +*/ +static void change_file(int direction) +{ + if (current_file != ((direction > 0) ? num_files : 1)) { + current_file = direction ? current_file + direction : 1; + strcpy(filename, files[current_file - 1]); + reinitialise(); + } + else { + clear_line(); + printf("%s%s%s", HIGHLIGHT, (direction > 0) ? "No next file" : "No previous file", NORMAL); + } +} + +static void remove_current_file(void) +{ + int i; + + if (current_file != 1) { + change_file(-1); + for (i = 3; i <= num_files; i++) + files[i - 2] = files[i - 1]; + num_files--; + buffer_print(); + } + else { + change_file(1); + for (i = 2; i <= num_files; i++) + files[i - 2] = files[i - 1]; + num_files--; + current_file--; + buffer_print(); + } +} + +static void colon_process(void) +{ + int keypress; + + /* Clear the current line and print a prompt */ + clear_line(); + printf(" :"); + + keypress = tless_getch(); + switch (keypress) { + case 'd': + remove_current_file(); + break; + case 'e': + examine_file(); + break; +#ifdef CONFIG_FEATURE_LESS_FLAGS + case 'f': + clear_line(); + m_status_print(); + break; +#endif + case 'n': + change_file(1); + break; + case 'p': + change_file(-1); + break; + case 'q': + tless_exit(0); + break; + case 'x': + change_file(0); + break; + default: + break; + } +} + +#ifdef CONFIG_FEATURE_LESS_REGEXP +/* The below two regular expression handler functions NEED development. */ + +/* Get a regular expression from the user, and then go through the current + file line by line, running a processing regex function on each one. */ + +static char *process_regex_on_line(char *line, regex_t *pattern, int action) +{ + /* This function takes the regex and applies it to the line. + Each part of the line that matches has the HIGHLIGHT + and NORMAL escape sequences placed around it by + insert_highlights if action = 1, or has the escape sequences + removed if action = 0, and then the line is returned. */ + int match_status; + char *line2 = xmalloc((sizeof(char) * (strlen(line) + 1)) + 64); + char *growline = ""; + regmatch_t match_structs; + + line2 = xstrdup(line); + + match_found = 0; + match_status = regexec(pattern, line2, 1, &match_structs, 0); + + while (match_status == 0) { + if (match_found == 0) + match_found = 1; + + if (action) { + growline = xasprintf("%s%.*s%s%.*s%s", growline, + match_structs.rm_so, line2, HIGHLIGHT, + match_structs.rm_eo - match_structs.rm_so, + line2 + match_structs.rm_so, NORMAL); + } + else { + growline = xasprintf("%s%.*s%.*s", growline, + match_structs.rm_so - 4, line2, + match_structs.rm_eo - match_structs.rm_so, + line2 + match_structs.rm_so); + } + + line2 += match_structs.rm_eo; + match_status = regexec(pattern, line2, 1, &match_structs, REG_NOTBOL); + } + + growline = xasprintf("%s%s", growline, line2); + + return (match_found ? growline : line); + + free(growline); + free(line2); +} + +static void goto_match(int match) +{ + /* This goes to a specific match - all line positions of matches are + stored within the match_lines[] array. */ + if ((match < num_matches) && (match >= 0)) { + buffer_line(match_lines[match]); + match_pos = match; + } +} + +static void regex_process(void) +{ + char uncomp_regex[100]; + char *current_line; + int i; + int j = 0; + regex_t pattern; + /* Get the uncompiled regular expression from the user */ + clear_line(); + putchar((flags & LESS_STATE_MATCH_BACKWARDS) ? '?' : '/'); + uncomp_regex[0] = 0; + fgets(uncomp_regex, sizeof(uncomp_regex), inp); + + if (strlen(uncomp_regex) == 1) { + if (num_matches) + goto_match((flags & LESS_STATE_MATCH_BACKWARDS) + ? match_pos - 1 : match_pos + 1); + else + buffer_print(); + return; + } + uncomp_regex[strlen(uncomp_regex) - 1] = '\0'; + + /* Compile the regex and check for errors */ + xregcomp(&pattern, uncomp_regex, 0); + + if (num_matches) { + /* Get rid of all the highlights we added previously */ + for (i = 0; i <= num_flines; i++) { + current_line = process_regex_on_line(flines[i], &old_pattern, 0); + flines[i] = xstrdup(current_line); + } + } + old_pattern = pattern; + + /* Reset variables */ + match_lines = xrealloc(match_lines, sizeof(int)); + match_lines[0] = -1; + match_pos = 0; + num_matches = 0; + match_found = 0; + /* Run the regex on each line of the current file here */ + for (i = 0; i <= num_flines; i++) { + current_line = process_regex_on_line(flines[i], &pattern, 1); + flines[i] = xstrdup(current_line); + if (match_found) { + match_lines = xrealloc(match_lines, (j + 1) * sizeof(int)); + match_lines[j] = i; + j++; + } + } + + num_matches = j; + if ((match_lines[0] != -1) && (num_flines > height - 2)) { + if (flags & LESS_STATE_MATCH_BACKWARDS) { + for (i = 0; i < num_matches; i++) { + if (match_lines[i] > line_pos) { + match_pos = i - 1; + buffer_line(match_lines[match_pos]); + break; + } + } + } + else + buffer_line(match_lines[0]); + } + else + buffer_init(); +} +#endif + +static void number_process(int first_digit) +{ + int i = 1; + int num; + char num_input[80]; + char keypress; + char *endptr; + + num_input[0] = first_digit; + + /* Clear the current line, print a prompt, and then print the digit */ + clear_line(); + printf(":%c", first_digit); + + /* Receive input until a letter is given (max 80 chars)*/ + while((i < 80) && (num_input[i] = tless_getch()) && isdigit(num_input[i])) { + putchar(num_input[i]); + i++; + } + + /* Take the final letter out of the digits string */ + keypress = num_input[i]; + num_input[i] = '\0'; + num = strtol(num_input, &endptr, 10); + if (endptr==num_input || *endptr!='\0' || num < 1 || num > MAXLINES) { + buffer_print(); + return; + } + + /* We now know the number and the letter entered, so we process them */ + switch (keypress) { + case KEY_DOWN: case 'z': case 'd': case 'e': case ' ': case '\015': + buffer_down(num); + break; + case KEY_UP: case 'b': case 'w': case 'y': case 'u': + buffer_up(num); + break; + case 'g': case '<': case 'G': case '>': + if (num_flines >= height - 2) + buffer_line(num - 1); + break; + case 'p': case '%': + buffer_line(((num / 100) * num_flines) - 1); + break; +#ifdef CONFIG_FEATURE_LESS_REGEXP + case 'n': + goto_match(match_pos + num); + break; + case '/': + flags &= ~LESS_STATE_MATCH_BACKWARDS; + regex_process(); + break; + case '?': + flags |= LESS_STATE_MATCH_BACKWARDS; + regex_process(); + break; +#endif + default: + break; + } +} + +#ifdef CONFIG_FEATURE_LESS_FLAGCS +static void flag_change(void) +{ + int keypress; + + clear_line(); + putchar('-'); + keypress = tless_getch(); + + switch (keypress) { + case 'M': + flags ^= FLAG_M; + break; + case 'm': + flags ^= FLAG_m; + break; + case 'E': + flags ^= FLAG_E; + break; + case '~': + flags ^= FLAG_TILDE; + break; + default: + break; + } +} + +static void show_flag_status(void) +{ + int keypress; + int flag_val; + + clear_line(); + putchar('_'); + keypress = tless_getch(); + + switch (keypress) { + case 'M': + flag_val = flags & FLAG_M; + break; + case 'm': + flag_val = flags & FLAG_m; + break; + case '~': + flag_val = flags & FLAG_TILDE; + break; + case 'N': + flag_val = flags & FLAG_N; + break; + case 'E': + flag_val = flags & FLAG_E; + break; + default: + flag_val = 0; + break; + } + + clear_line(); + printf("%s%s%i%s", HIGHLIGHT, "The status of the flag is: ", flag_val != 0, NORMAL); +} +#endif + +static void full_repaint(void) +{ + int temp_line_pos = line_pos; + data_readlines(); + buffer_init(); + buffer_line(temp_line_pos); +} + + +static void save_input_to_file(void) +{ + char current_line[256]; + int i; + FILE *fp; + + clear_line(); + printf("Log file: "); + fgets(current_line, 256, inp); + current_line[strlen(current_line) - 1] = '\0'; + if (strlen(current_line) > 1) { + fp = xfopen(current_line, "w"); + for (i = 0; i < num_flines; i++) + fprintf(fp, "%s", flines[i]); + fclose(fp); + buffer_print(); + } + else + printf("%s%s%s", HIGHLIGHT, "No log file", NORMAL); +} + +#ifdef CONFIG_FEATURE_LESS_MARKS +static void add_mark(void) +{ + int letter; + + clear_line(); + printf("Mark: "); + letter = tless_getch(); + + if (isalpha(letter)) { + + /* If we exceed 15 marks, start overwriting previous ones */ + if (num_marks == 14) + num_marks = 0; + + mark_lines[num_marks][0] = letter; + mark_lines[num_marks][1] = line_pos; + num_marks++; + } + else { + clear_line(); + printf("%s%s%s", HIGHLIGHT, "Invalid mark letter", NORMAL); + } +} + +static void goto_mark(void) +{ + int letter; + int i; + + clear_line(); + printf("Go to mark: "); + letter = tless_getch(); + clear_line(); + + if (isalpha(letter)) { + for (i = 0; i <= num_marks; i++) + if (letter == mark_lines[i][0]) { + buffer_line(mark_lines[i][1]); + break; + } + if ((num_marks == 14) && (letter != mark_lines[14][0])) + printf("%s%s%s", HIGHLIGHT, "Mark not set", NORMAL); + } + else + printf("%s%s%s", HIGHLIGHT, "Invalid mark letter", NORMAL); +} +#endif + + +#ifdef CONFIG_FEATURE_LESS_BRACKETS + +static char opp_bracket(char bracket) +{ + switch (bracket) { + case '{': case '[': + return bracket + 2; + case '(': + return ')'; + case '}': case ']': + return bracket - 2; + case ')': + return '('; + default: + return 0; + } +} + +static void match_right_bracket(char bracket) +{ + int bracket_line = -1; + int i; + + clear_line(); + + if (strchr(flines[line_pos], bracket) == NULL) + printf("%s%s%s", HIGHLIGHT, "No bracket in top line", NORMAL); + else { + for (i = line_pos + 1; i < num_flines; i++) { + if (strchr(flines[i], opp_bracket(bracket)) != NULL) { + bracket_line = i; + break; + } + } + + if (bracket_line == -1) + printf("%s%s%s", HIGHLIGHT, "No matching bracket found", NORMAL); + + buffer_line(bracket_line - height + 2); + } +} + +static void match_left_bracket(char bracket) +{ + int bracket_line = -1; + int i; + + clear_line(); + + if (strchr(flines[line_pos + height - 2], bracket) == NULL) { + printf("%s%s%s", HIGHLIGHT, "No bracket in bottom line", NORMAL); + printf("%s", flines[line_pos + height]); + sleep(4); + } + else { + for (i = line_pos + height - 2; i >= 0; i--) { + if (strchr(flines[i], opp_bracket(bracket)) != NULL) { + bracket_line = i; + break; + } + } + + if (bracket_line == -1) + printf("%s%s%s", HIGHLIGHT, "No matching bracket found", NORMAL); + + buffer_line(bracket_line); + } +} + +#endif /* CONFIG_FEATURE_LESS_BRACKETS */ + +static void keypress_process(int keypress) +{ + switch (keypress) { + case KEY_DOWN: case 'e': case 'j': case '\015': + buffer_down(1); + buffer_print(); + break; + case KEY_UP: case 'y': case 'k': + buffer_up(1); + buffer_print(); + break; + case PAGE_DOWN: case ' ': case 'z': + buffer_down(height - 1); + buffer_print(); + break; + case PAGE_UP: case 'w': case 'b': + buffer_up(height - 1); + buffer_print(); + break; + case 'd': + buffer_down((height - 1) / 2); + buffer_print(); + break; + case 'u': + buffer_up((height - 1) / 2); + buffer_print(); + break; + case KEY_HOME: case 'g': case 'p': case '<': case '%': + buffer_line(0); + break; + case KEY_END: case 'G': case '>': + buffer_line(num_flines - height + 2); + break; + case 'q': case 'Q': + tless_exit(0); + break; +#ifdef CONFIG_FEATURE_LESS_MARKS + case 'm': + add_mark(); + buffer_print(); + break; + case '\'': + goto_mark(); + buffer_print(); + break; +#endif + case 'r': + buffer_print(); + break; + case 'R': + full_repaint(); + break; + case 's': + if (flags & LESS_STATE_INP_STDIN) + save_input_to_file(); + break; + case 'E': + examine_file(); + break; +#ifdef CONFIG_FEATURE_LESS_FLAGS + case '=': + clear_line(); + m_status_print(); + break; +#endif +#ifdef CONFIG_FEATURE_LESS_REGEXP + case '/': + flags &= ~LESS_STATE_MATCH_BACKWARDS; + regex_process(); + break; + case 'n': + goto_match(match_pos + 1); + break; + case 'N': + goto_match(match_pos - 1); + break; + case '?': + flags |= LESS_STATE_MATCH_BACKWARDS; + regex_process(); + break; +#endif +#ifdef CONFIG_FEATURE_LESS_FLAGCS + case '-': + flag_change(); + buffer_print(); + break; + case '_': + show_flag_status(); + break; +#endif +#ifdef CONFIG_FEATURE_LESS_BRACKETS + case '{': case '(': case '[': + match_right_bracket(keypress); + break; + case '}': case ')': case ']': + match_left_bracket(keypress); + break; +#endif + case ':': + colon_process(); + break; + default: + break; + } + + if (isdigit(keypress)) + number_process(keypress); +} + +int less_main(int argc, char **argv) { + + int keypress; + + flags = getopt32(argc, argv, "EMmN~"); + + argc -= optind; + argv += optind; + files = argv; + num_files = argc; + + if (!num_files) { + if (ttyname(STDIN_FILENO) == NULL) + flags |= LESS_STATE_INP_STDIN; + else { + bb_error_msg("missing filename"); + bb_show_usage(); + } + } + + strcpy(filename, (flags & LESS_STATE_INP_STDIN) ? bb_msg_standard_input : files[0]); + get_terminal_width_height(0, &width, &height); + data_readlines(); + tcgetattr(fileno(inp), &term_orig); + term_vi = term_orig; + term_vi.c_lflag &= (~ICANON & ~ECHO); + term_vi.c_iflag &= (~IXON & ~ICRNL); + term_vi.c_oflag &= (~ONLCR); + term_vi.c_cc[VMIN] = 1; + term_vi.c_cc[VTIME] = 0; + buffer_init(); + buffer_print(); + + while (1) { + keypress = tless_getch(); + keypress_process(keypress); + } +} diff --git a/miscutils/makedevs.c b/miscutils/makedevs.c new file mode 100644 index 0000000..3bc1559 --- /dev/null +++ b/miscutils/makedevs.c @@ -0,0 +1,230 @@ +/* vi: set sw=4 ts=4: */ +/* + * public domain -- Dave 'Kill a Cop' Cinege <dcinege@psychosis.com> + * + * makedevs + * Make ranges of device files quickly. + * known bugs: can't deal with alpha ranges + */ + +#include "busybox.h" + +#ifdef CONFIG_FEATURE_MAKEDEVS_LEAF +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 = xatoi_u(argv[3]); + Sminor = xatoi_u(argv[4]); + S = xatoi_u(argv[5]); + E = xatoi_u(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; +} + +#elif defined CONFIG_FEATURE_MAKEDEVS_TABLE + +/* Licensed under the GPL v2 or later, see the file LICENSE in this tarball. */ + +int makedevs_main(int argc, char **argv) +{ + FILE *table = stdin; + char *rootdir = NULL; + char *line = NULL; + int linenum = 0; + int ret = EXIT_SUCCESS; + + getopt32(argc, argv, "d:", &line); + if (line) + table = xfopen(line, "r"); + + if (optind >= argc || (rootdir=argv[optind])==NULL) { + bb_error_msg_and_die("root directory not specified"); + } + + xchdir(rootdir); + + umask(0); + + printf("rootdir=%s\n", rootdir); + if (line) { + printf("table='%s'\n", line); + } else { + printf("table=<stdin>\n"); + } + + while ((line = xmalloc_getline(table))) { + char type; + unsigned int mode = 0755; + unsigned int major = 0; + unsigned int minor = 0; + unsigned int count = 0; + unsigned int increment = 0; + unsigned int start = 0; + char name[41]; + char user[41]; + char group[41]; + char *full_name; + uid_t uid; + gid_t gid; + + linenum++; + + if ((2 > sscanf(line, "%40s %c %o %40s %40s %u %u %u %u %u", name, + &type, &mode, user, group, &major, + &minor, &start, &increment, &count)) || + ((major | minor | start | count | increment) > 255)) + { + if (*line=='\0' || *line=='#' || isspace(*line)) + continue; + bb_error_msg("line %d invalid: '%s'", linenum, line); + ret = EXIT_FAILURE; + continue; + } + if (name[0] == '#') { + continue; + } + + gid = (*group) ? get_ug_id(group, bb_xgetgrnam) : getgid(); + uid = (*user) ? get_ug_id(user, bb_xgetpwnam) : getuid(); + full_name = concat_path_file(rootdir, name); + + if (type == 'd') { + bb_make_directory(full_name, mode | S_IFDIR, FILEUTILS_RECUR); + if (chown(full_name, uid, gid) == -1) { + bb_perror_msg("line %d: chown failed for %s", linenum, full_name); + ret = EXIT_FAILURE; + goto loop; + } + if ((mode != -1) && (chmod(full_name, mode) < 0)){ + bb_perror_msg("line %d: chmod failed for %s", linenum, full_name); + ret = EXIT_FAILURE; + goto loop; + } + } else if (type == 'f') { + struct stat st; + if ((stat(full_name, &st) < 0 || !S_ISREG(st.st_mode))) { + bb_perror_msg("line %d: regular file '%s' does not exist", linenum, full_name); + ret = EXIT_FAILURE; + goto loop; + } + if (chown(full_name, uid, gid) == -1) { + bb_perror_msg("line %d: chown failed for %s", linenum, full_name); + ret = EXIT_FAILURE; + goto loop; + } + if ((mode != -1) && (chmod(full_name, mode) < 0)){ + bb_perror_msg("line %d: chmod failed for %s", linenum, full_name); + ret = EXIT_FAILURE; + goto loop; + } + } else + { + dev_t rdev; + + if (type == 'p') { + mode |= S_IFIFO; + } + else if (type == 'c') { + mode |= S_IFCHR; + } + else if (type == 'b') { + mode |= S_IFBLK; + } else { + bb_error_msg("line %d: unsupported file type %c", linenum, type); + ret = EXIT_FAILURE; + goto loop; + } + + if (count > 0) { + int i; + char *full_name_inc; + + full_name_inc = xmalloc(strlen(full_name) + 4); + for (i = start; i < count; i++) { + sprintf(full_name_inc, "%s%d", full_name, i); + rdev = (major << 8) + minor + (i * increment - start); + if (mknod(full_name_inc, mode, rdev) == -1) { + bb_perror_msg("line %d: cannot create node %s", linenum, full_name_inc); + ret = EXIT_FAILURE; + } + else if (chown(full_name_inc, uid, gid) == -1) { + bb_perror_msg("line %d: chown failed for %s", linenum, full_name_inc); + ret = EXIT_FAILURE; + } + if ((mode != -1) && (chmod(full_name_inc, mode) < 0)){ + bb_perror_msg("line %d: chmod failed for %s", linenum, full_name_inc); + ret = EXIT_FAILURE; + } + } + free(full_name_inc); + } else { + rdev = (major << 8) + minor; + if (mknod(full_name, mode, rdev) == -1) { + bb_perror_msg("line %d: cannot create node %s", linenum, full_name); + ret = EXIT_FAILURE; + } + else if (chown(full_name, uid, gid) == -1) { + bb_perror_msg("line %d: chown failed for %s", linenum, full_name); + ret = EXIT_FAILURE; + } + if ((mode != -1) && (chmod(full_name, mode) < 0)){ + bb_perror_msg("line %d: chmod failed for %s", linenum, full_name); + ret = EXIT_FAILURE; + } + } + } +loop: + free(line); + free(full_name); + } + fclose(table); + + return ret; +} + +#else +# error makedevs configuration error, either leaf or table must be selected +#endif diff --git a/miscutils/mountpoint.c b/miscutils/mountpoint.c new file mode 100644 index 0000000..b1bcab6 --- /dev/null +++ b/miscutils/mountpoint.c @@ -0,0 +1,65 @@ +/* vi: set sw=4 ts=4: */ +/* + * mountpoint implementation for busybox + * + * Copyright (C) 2005 Bernhard Fischer + * + * Licensed under the GPL v2 or later, see the file LICENSE in this tarball. + * + * Based on sysvinit's mountpoint + */ + +#include "busybox.h" + +int mountpoint_main(int argc, char **argv) +{ + struct stat st; + char *arg; + int opt = getopt32(argc, argv, "qdx"); +#define OPT_q (1) +#define OPT_d (2) +#define OPT_x (4) + + if (optind != argc - 1) + bb_show_usage(); + + arg = argv[optind]; + + if ( (opt & OPT_x && stat(arg, &st) == 0) || (lstat(arg, &st) == 0) ) { + if (opt & OPT_x) { + if (S_ISBLK(st.st_mode)) { + printf("%u:%u\n", major(st.st_rdev), + minor(st.st_rdev)); + return EXIT_SUCCESS; + } else { + if (opt & OPT_q) + putchar('\n'); + else + bb_error_msg("%s: not a block device", arg); + } + return EXIT_FAILURE; + } else + if (S_ISDIR(st.st_mode)) { + dev_t st_dev = st.st_dev; + ino_t st_ino = st.st_ino; + char *p = xasprintf("%s/..", arg); + + if (stat(p, &st) == 0) { + int ret = (st_dev != st.st_dev) || + (st_dev == st.st_dev && st_ino == st.st_ino); + if (opt & OPT_d) + printf("%u:%u\n", major(st_dev), minor(st_dev)); + else if (!(opt & OPT_q)) + printf("%s is %sa mountpoint\n", arg, ret?"":"not "); + return !ret; + } + } else { + if (!(opt & OPT_q)) + bb_error_msg("%s: not a directory", arg); + return EXIT_FAILURE; + } + } + if (!(opt & OPT_q)) + bb_perror_msg("%s", arg); + return EXIT_FAILURE; +} diff --git a/miscutils/mt.c b/miscutils/mt.c new file mode 100644 index 0000000..9ecec82 --- /dev/null +++ b/miscutils/mt.c @@ -0,0 +1,120 @@ +/* vi: set sw=4 ts=4: */ +/* + * Licensed under GPLv2 or later, see file LICENSE in this tarball for details. + */ + +#include "busybox.h" +#include <sys/mtio.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} +}; + +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 = xatoi_u(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; + } + + fd = xopen(file, mode); + + 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/miscutils/nmeter.c b/miscutils/nmeter.c new file mode 100644 index 0000000..b098771 --- /dev/null +++ b/miscutils/nmeter.c @@ -0,0 +1,848 @@ +/* +** Licensed under the GPL v2, see the file LICENSE in this tarball +** +** Based on nanotop.c from floppyfw project +** +** Contact me: vda.linux@googlemail.com */ + +//TODO: +// simplify code +// /proc/locks +// /proc/stat: +// disk_io: (3,0):(22272,17897,410702,4375,54750) +// btime 1059401962 + +#include "busybox.h" +#include <time.h> + +typedef unsigned long long ullong; + +enum { proc_file_size = 4096 }; + +typedef struct proc_file { + char *name; + int gen; + char *file; +} proc_file; + +static proc_file proc_stat = { "/proc/stat", -1 }; +static proc_file proc_loadavg = { "/proc/loadavg", -1 }; +static proc_file proc_net_dev = { "/proc/net/dev", -1 }; +static proc_file proc_meminfo = { "/proc/meminfo", -1 }; +static proc_file proc_diskstats = { "/proc/diskstats", -1 }; +// Sample # +static int gen = -1; +// Linux 2.6? (otherwise assumes 2.4) +static int is26 = 0; +static struct timeval tv; +static int delta = 1000000; +static int deltanz = 1000000; +static int need_seconds = 0; +static char *final_str = "\n"; + +// We depend on this being a char[], not char* - we take sizeof() of it +#define outbuf bb_common_bufsiz1 +static char *cur_outbuf = outbuf; + + +static inline void reset_outbuf(void) +{ + cur_outbuf = outbuf; +} + +static inline int outbuf_count(void) +{ + return cur_outbuf - outbuf; +} + +static void print_outbuf(void) +{ + int sz = cur_outbuf - outbuf; + if (sz > 0) { + write(1, outbuf, sz); + cur_outbuf = outbuf; + } +} + +static void put(const char *s) +{ + int sz = strlen(s); + if (sz > outbuf + sizeof(outbuf) - cur_outbuf) + sz = outbuf + sizeof(outbuf) - cur_outbuf; + memcpy(cur_outbuf, s, sz); + cur_outbuf += sz; +} + +static void put_c(char c) +{ + if (cur_outbuf < outbuf + sizeof(outbuf)) + *cur_outbuf++ = c; +} + +static void put_question_marks(int count) +{ + while (count--) + put_c('?'); +} + +static int readfile_z(char *buf, int sz, const char* fname) +{ + sz = open_read_close(fname, buf, sz-1); + if (sz < 0) { + buf[0] = '\0'; + return 1; + } + buf[sz] = '\0'; + return 0; +} + +static const char* get_file(proc_file *pf) +{ + if (pf->gen != gen) { + pf->gen = gen; + // We allocate proc_file_size bytes. This wastes memory, + // but allows us to allocate only once (at first sample) + // per proc file, and reuse buffer for each sample + if (!pf->file) + pf->file = (char*)xmalloc(proc_file_size); + readfile_z(pf->file, proc_file_size, pf->name); + } + return pf->file; +} + +static inline ullong read_after_slash(const char *p) +{ + p = strchr(p, '/'); + if (!p) return 0; + return strtoull(p+1, NULL, 10); +} + +enum conv_type { conv_decimal, conv_slash }; + +// Reads decimal values from line. Values start after key, for example: +// "cpu 649369 0 341297 4336769..." - key is "cpu" here. +// Values are stored in vec[]. arg_ptr has list of positions +// we are interested in: for example: 1,2,5 - we want 1st, 2nd and 5th value. +static int vrdval(const char* p, const char* key, + enum conv_type conv, ullong *vec, va_list arg_ptr) +{ + int indexline; + int indexnext; + + p = strstr(p, key); + if (!p) return 1; + + p += strlen(key); + indexline = 1; + indexnext = va_arg(arg_ptr, int); + while (1) { + while (*p == ' ' || *p == '\t') p++; + if (*p == '\n' || *p == '\0') break; + + if (indexline == indexnext) { // read this value + *vec++ = conv==conv_decimal ? + strtoull(p, NULL, 10) : + read_after_slash(p); + indexnext = va_arg(arg_ptr, int); + } + while (*p > ' ') p++; // skip over value + indexline++; + } + return 0; +} + +// Parses files with lines like "cpu0 21727 0 15718 1813856 9461 10485 0 0": +// rdval(file_contents, "string_to_find", result_vector, value#, value#...) +// value# start with 1 +static int rdval(const char* p, const char* key, ullong *vec, ...) +{ + va_list arg_ptr; + int result; + + va_start(arg_ptr, vec); + result = vrdval(p, key, conv_decimal, vec, arg_ptr); + va_end(arg_ptr); + + return result; +} + +// Parses files with lines like "... ... ... 3/148 ...." +static int rdval_loadavg(const char* p, ullong *vec, ...) +{ + va_list arg_ptr; + int result; + + va_start(arg_ptr, vec); + result = vrdval(p, "", conv_slash, vec, arg_ptr); + va_end(arg_ptr); + + return result; +} + +// Parses /proc/diskstats +// 1 2 3 4 5 6(rd) 7 8 9 10(wr) 11 12 13 14 +// 3 0 hda 51292 14441 841783 926052 25717 79650 843256 3029804 0 148459 3956933 +// 3 1 hda1 0 0 0 0 <- ignore if only 4 fields +static int rdval_diskstats(const char* p, ullong *vec) +{ + ullong rd = 0; // to avoid "warning: 'rd' might be used uninitialized" + int indexline = 0; + vec[0] = 0; + vec[1] = 0; + while (1) { + indexline++; + while (*p == ' ' || *p == '\t') p++; + if (*p == '\0') break; + if (*p == '\n') { + indexline = 0; + p++; + continue; + } + if (indexline == 6) { + rd = strtoull(p, NULL, 10); + } else if (indexline == 10) { + vec[0] += rd; // TODO: *sectorsize (don't know how to find out sectorsize) + vec[1] += strtoull(p, NULL, 10); + while (*p != '\n' && *p != '\0') p++; + continue; + } + while (*p > ' ') p++; // skip over value + } + return 0; +} + +static void scale(ullong ul) +{ + char buf[5]; + smart_ulltoa5(ul, buf); + put(buf); +} + + +#define S_STAT(a) \ +typedef struct a { \ + struct s_stat *next; \ + void (*collect)(struct a *s); \ + const char *label; +#define S_STAT_END(a) } a; + +S_STAT(s_stat) +S_STAT_END(s_stat) + +static void collect_literal(s_stat *s) +{ +} + +static s_stat* init_literal(void) +{ + s_stat *s = xmalloc(sizeof(s_stat)); + s->collect = collect_literal; + return (s_stat*)s; +} + +static s_stat* init_delay(const char *param) +{ + delta = strtol(param, NULL, 0)*1000; + deltanz = delta > 0 ? delta : 1; + need_seconds = (1000000%deltanz) != 0; + return (s_stat*)0; +} + +static s_stat* init_cr(const char *param) +{ + final_str = "\r"; + return (s_stat*)0; +} + + +// user nice system idle iowait irq softirq (last 3 only in 2.6) +//cpu 649369 0 341297 4336769 11640 7122 1183 +//cpuN 649369 0 341297 4336769 11640 7122 1183 +enum { CPU_FIELDCNT = 7 }; +S_STAT(cpu_stat) + ullong old[CPU_FIELDCNT]; + int bar_sz; + char *bar; +S_STAT_END(cpu_stat) + + +static void collect_cpu(cpu_stat *s) +{ + ullong data[CPU_FIELDCNT] = { 0, 0, 0, 0, 0, 0, 0 }; + unsigned frac[CPU_FIELDCNT] = { 0, 0, 0, 0, 0, 0, 0 }; + ullong all = 0; + int norm_all = 0; + int bar_sz = s->bar_sz; + char *bar = s->bar; + int i; + + if (rdval(get_file(&proc_stat), "cpu ", data, 1, 2, 3, 4, 5, 6, 7)) { + put_question_marks(bar_sz); + return; + } + + for (i=0; i<CPU_FIELDCNT; i++) { + ullong old = s->old[i]; + if (data[i] < old) old = data[i]; //sanitize + s->old[i] = data[i]; + all += (data[i] -= old); + } + + if (all) { + for (i=0; i<CPU_FIELDCNT; i++) { + ullong t = bar_sz * data[i]; + norm_all += data[i] = t / all; + frac[i] = t % all; + } + + while (norm_all < bar_sz) { + unsigned max = frac[0]; + int pos = 0; + for (i=1; i<CPU_FIELDCNT; i++) { + if (frac[i] > max) max = frac[i], pos = i; + } + frac[pos] = 0; //avoid bumping up same value twice + data[pos]++; + norm_all++; + } + + memset(bar, '.', bar_sz); + memset(bar, 'S', data[2]); bar += data[2]; //sys + memset(bar, 'U', data[0]); bar += data[0]; //usr + memset(bar, 'N', data[1]); bar += data[1]; //nice + memset(bar, 'D', data[4]); bar += data[4]; //iowait + memset(bar, 'I', data[5]); bar += data[5]; //irq + memset(bar, 'i', data[6]); bar += data[6]; //softirq + } else { + memset(bar, '?', bar_sz); + } + put(s->bar); +} + + +static s_stat* init_cpu(const char *param) +{ + int sz; + cpu_stat *s = xmalloc(sizeof(cpu_stat)); + s->collect = collect_cpu; + sz = strtol(param, NULL, 0); + if (sz < 10) sz = 10; + if (sz > 1000) sz = 1000; + s->bar = xmalloc(sz+1); + s->bar[sz] = '\0'; + s->bar_sz = sz; + return (s_stat*)s; +} + + +S_STAT(int_stat) + ullong old; + int no; +S_STAT_END(int_stat) + +static void collect_int(int_stat *s) +{ + ullong data[1]; + ullong old; + + if (rdval(get_file(&proc_stat), "intr", data, s->no)) { + put_question_marks(4); + return; + } + + old = s->old; + if (data[0] < old) old = data[0]; //sanitize + s->old = data[0]; + scale(data[0] - old); +} + +static s_stat* init_int(const char *param) +{ + int_stat *s = xmalloc(sizeof(int_stat)); + s->collect = collect_int; + if (param[0]=='\0') { + s->no = 1; + } else { + int n = strtoul(param, NULL, 0); + s->no = n+2; + } + return (s_stat*)s; +} + + +S_STAT(ctx_stat) + ullong old; +S_STAT_END(ctx_stat) + +static void collect_ctx(ctx_stat *s) +{ + ullong data[1]; + ullong old; + + if (rdval(get_file(&proc_stat), "ctxt", data, 1)) { + put_question_marks(4); + return; + } + + old = s->old; + if (data[0] < old) old = data[0]; //sanitize + s->old = data[0]; + scale(data[0] - old); +} + +static s_stat* init_ctx(const char *param) +{ + ctx_stat *s = xmalloc(sizeof(ctx_stat)); + s->collect = collect_ctx; + return (s_stat*)s; +} + + +S_STAT(blk_stat) + const char* lookfor; + ullong old[2]; +S_STAT_END(blk_stat) + +static void collect_blk(blk_stat *s) +{ + ullong data[2]; + int i; + + if (is26) { + i = rdval_diskstats(get_file(&proc_diskstats), data); + } else { + i = rdval(get_file(&proc_stat), s->lookfor, data, 1, 2); + // Linux 2.4 reports bio in Kbytes, convert to sectors: + data[0] *= 2; + data[1] *= 2; + } + if (i) { + put_question_marks(9); + return; + } + + for (i=0; i<2; i++) { + ullong old = s->old[i]; + if (data[i] < old) old = data[i]; //sanitize + s->old[i] = data[i]; + data[i] -= old; + } + scale(data[0]*512); // TODO: *sectorsize + put_c(' '); + scale(data[1]*512); +} + +static s_stat* init_blk(const char *param) +{ + blk_stat *s = xmalloc(sizeof(blk_stat)); + s->collect = collect_blk; + s->lookfor = "page"; + return (s_stat*)s; +} + + +S_STAT(fork_stat) + ullong old; +S_STAT_END(fork_stat) + +static void collect_thread_nr(fork_stat *s) +{ + ullong data[1]; + + if (rdval_loadavg(get_file(&proc_loadavg), data, 4)) { + put_question_marks(4); + return; + } + scale(data[0]); +} + +static void collect_fork(fork_stat *s) +{ + ullong data[1]; + ullong old; + + if (rdval(get_file(&proc_stat), "processes", data, 1)) { + put_question_marks(4); + return; + } + + old = s->old; + if (data[0] < old) old = data[0]; //sanitize + s->old = data[0]; + scale(data[0] - old); +} + +static s_stat* init_fork(const char *param) +{ + fork_stat *s = xmalloc(sizeof(fork_stat)); + if (*param == 'n') { + s->collect = collect_thread_nr; + } else { + s->collect = collect_fork; + } + return (s_stat*)s; +} + + +S_STAT(if_stat) + ullong old[4]; + const char *device; + char *device_colon; +S_STAT_END(if_stat) + +static void collect_if(if_stat *s) +{ + ullong data[4]; + int i; + + if (rdval(get_file(&proc_net_dev), s->device_colon, data, 1, 3, 9, 11)) { + put_question_marks(10); + return; + } + + for (i=0; i<4; i++) { + ullong old = s->old[i]; + if (data[i] < old) old = data[i]; //sanitize + s->old[i] = data[i]; + data[i] -= old; + } + put_c(data[1] ? '*' : ' '); + scale(data[0]); + put_c(data[3] ? '*' : ' '); + scale(data[2]); +} + +static s_stat* init_if(const char *device) +{ + if_stat *s = xmalloc(sizeof(if_stat)); + + if (!device || !device[0]) + bb_show_usage(); + s->collect = collect_if; + + s->device = device; + s->device_colon = xmalloc(strlen(device)+2); + strcpy(s->device_colon, device); + strcat(s->device_colon, ":"); + return (s_stat*)s; +} + + +S_STAT(mem_stat) + char opt; +S_STAT_END(mem_stat) + +// "Memory" value should not include any caches. +// IOW: neither "ls -laR /" nor heavy read/write activity +// should affect it. We'd like to also include any +// long-term allocated kernel-side mem, but it is hard +// to figure out. For now, bufs, cached & slab are +// counted as "free" memory +//2.6.16: +//MemTotal: 773280 kB +//MemFree: 25912 kB - genuinely free +//Buffers: 320672 kB - cache +//Cached: 146396 kB - cache +//SwapCached: 0 kB +//Active: 183064 kB +//Inactive: 356892 kB +//HighTotal: 0 kB +//HighFree: 0 kB +//LowTotal: 773280 kB +//LowFree: 25912 kB +//SwapTotal: 131064 kB +//SwapFree: 131064 kB +//Dirty: 48 kB +//Writeback: 0 kB +//Mapped: 96620 kB +//Slab: 200668 kB - takes 7 Mb on my box fresh after boot, +// but includes dentries and inodes +// (== can take arbitrary amount of mem) +//CommitLimit: 517704 kB +//Committed_AS: 236776 kB +//PageTables: 1248 kB +//VmallocTotal: 516052 kB +//VmallocUsed: 3852 kB +//VmallocChunk: 512096 kB +//HugePages_Total: 0 +//HugePages_Free: 0 +//Hugepagesize: 4096 kB +static void collect_mem(mem_stat *s) +{ + ullong m_total = 0; + ullong m_free = 0; + ullong m_bufs = 0; + ullong m_cached = 0; + ullong m_slab = 0; + + if (rdval(get_file(&proc_meminfo), "MemTotal:", &m_total, 1)) { + put_question_marks(4); + return; + } + if (s->opt == 'f') { + scale(m_total << 10); + return; + } + + if (rdval(proc_meminfo.file, "MemFree:", &m_free , 1) + || rdval(proc_meminfo.file, "Buffers:", &m_bufs , 1) + || rdval(proc_meminfo.file, "Cached:", &m_cached, 1) + || rdval(proc_meminfo.file, "Slab:", &m_slab , 1) + ) { + put_question_marks(4); + return; + } + + m_free += m_bufs + m_cached + m_slab; + switch(s->opt) { + case 'f': + scale(m_free << 10); break; + default: + scale((m_total - m_free) << 10); break; + } +} + +static s_stat* init_mem(const char *param) +{ + mem_stat *s = xmalloc(sizeof(mem_stat)); + s->collect = collect_mem; + s->opt = param[0]; + return (s_stat*)s; +} + + +S_STAT(swp_stat) +S_STAT_END(swp_stat) + +static void collect_swp(swp_stat *s) +{ + ullong s_total[1]; + ullong s_free[1]; + if (rdval(get_file(&proc_meminfo), "SwapTotal:", s_total, 1) + || rdval(proc_meminfo.file, "SwapFree:" , s_free, 1) + ) { + put_question_marks(4); + return; + } + scale((s_total[0]-s_free[0]) << 10); +} + +static s_stat* init_swp(const char *param) +{ + swp_stat *s = xmalloc(sizeof(swp_stat)); + s->collect = collect_swp; + return (s_stat*)s; +} + + +S_STAT(fd_stat) +S_STAT_END(fd_stat) + +static void collect_fd(fd_stat *s) +{ + char file[4096]; + ullong data[2]; + + readfile_z(file, sizeof(file), "/proc/sys/fs/file-nr"); + if (rdval(file, "", data, 1, 2)) { + put_question_marks(4); + return; + } + + scale(data[0] - data[1]); +} + +static s_stat* init_fd(const char *param) +{ + fd_stat *s = xmalloc(sizeof(fd_stat)); + s->collect = collect_fd; + return (s_stat*)s; +} + + +S_STAT(time_stat) + int prec; + int scale; +S_STAT_END(time_stat) + +static void collect_time(time_stat *s) +{ + char buf[sizeof("12:34:56.123456")]; + struct tm* tm; + int us = tv.tv_usec + s->scale/2; + time_t t = tv.tv_sec; + + if (us >= 1000000) { + t++; + us -= 1000000; + } + tm = localtime(&t); + + sprintf(buf, "%02d:%02d:%02d", tm->tm_hour, tm->tm_min, tm->tm_sec); + if (s->prec) + sprintf(buf+8, ".%0*d", s->prec, us / s->scale); + put(buf); +} + +static s_stat* init_time(const char *param) +{ + int prec; + time_stat *s = xmalloc(sizeof(time_stat)); + + s->collect = collect_time; + prec = param[0]-'0'; + if (prec < 0) prec = 0; + else if (prec > 6) prec = 6; + s->prec = prec; + s->scale = 1; + while (prec++ < 6) + s->scale *= 10; + return (s_stat*)s; +} + +static void collect_info(s_stat *s) +{ + gen++; + while (s) { + put(s->label); + s->collect(s); + s = s->next; + } +} + + +typedef s_stat* init_func(const char *param); + +static const char options[] = "ncmsfixptbdr"; +static init_func* init_functions[] = { + init_if, + init_cpu, + init_mem, + init_swp, + init_fd, + init_int, + init_ctx, + init_fork, + init_time, + init_blk, + init_delay, + init_cr, +}; + +int nmeter_main(int argc, char* argv[]) +{ + char buf[32]; + s_stat *first = NULL; + s_stat *last = NULL; + s_stat *s; + char *cur, *prev; + + if (argc != 2) + bb_show_usage(); + + if (open_read_close("/proc/version", buf, sizeof(buf)) > 0) + is26 = (strstr(buf, " 2.4.")==NULL); + + // Can use argv[1] directly, but this will mess up + // parameters as seen by e.g. ps. Making a copy... + cur = xstrdup(argv[1]); + while (1) { + char *param, *p; + prev = cur; +again: + cur = strchr(cur, '%'); + if (!cur) + break; + if (cur[1]=='%') { // %% + strcpy(cur, cur+1); + cur++; + goto again; + } + *cur++ = '\0'; // overwrite % + if (cur[0] == '[') { + // format: %[foptstring] + cur++; + p = strchr(options, cur[0]); + param = cur+1; + while (cur[0] != ']') { + if (!cur[0]) + bb_show_usage(); + cur++; + } + *cur++ = '\0'; // overwrite [ + } else { + // format: %NNNNNNf + param = cur; + while (cur[0] >= '0' && cur[0] <= '9') + cur++; + if (!cur[0]) + bb_show_usage(); + p = strchr(options, cur[0]); + *cur++ = '\0'; // overwrite format char + } + if (!p) + bb_show_usage(); + s = init_functions[p-options](param); + if (s) { + s->label = prev; + s->next = 0; + if (!first) + first = s; + else + last->next = s; + last = s; + } else { + // %NNNNd or %r option. remove it from string + strcpy(prev + strlen(prev), cur); + cur = prev; + } + } + if (prev[0]) { + s = init_literal(); + s->label = prev; + s->next = 0; + if (!first) + first = s; + else + last->next = s; + last = s; + } + + // Generate first samples but do not print them, they're bogus + collect_info(first); + reset_outbuf(); + if (delta >= 0) { + gettimeofday(&tv, 0); + usleep(delta > 1000000 ? 1000000 : delta - tv.tv_usec%deltanz); + } + + while (1) { + gettimeofday(&tv, 0); + collect_info(first); + put(final_str); + print_outbuf(); + + // Negative delta -> no usleep at all + // This will hog the CPU but you can have REALLY GOOD + // time resolution ;) + // TODO: detect and avoid useless updates + // (like: nothing happens except time) + if (delta >= 0) { + int rem; + // can be commented out, will sacrifice sleep time precision a bit + gettimeofday(&tv, 0); + if (need_seconds) + rem = delta - ((ullong)tv.tv_sec*1000000+tv.tv_usec)%deltanz; + else + rem = delta - tv.tv_usec%deltanz; + // Sometimes kernel wakes us up just a tiny bit earlier than asked + // Do not go to very short sleep in this case + if (rem < delta/128) { + rem += delta; + } + usleep(rem); + } + } + + return 0; +} diff --git a/miscutils/raidautorun.c b/miscutils/raidautorun.c new file mode 100644 index 0000000..e5bce9a --- /dev/null +++ b/miscutils/raidautorun.c @@ -0,0 +1,26 @@ +/* vi: set sw=4 ts=4: */ +/* + * raidautorun implementation for busybox + * + * Copyright (C) 2006 Bernhard Fischer + * + * Licensed under the GPL v2 or later, see the file LICENSE in this tarball. + * + */ + +#include "busybox.h" + +#include <linux/major.h> +#include <linux/raid/md_u.h> + +int raidautorun_main(int argc, char **argv) +{ + if (argc != 2) + bb_show_usage(); + + if (ioctl(xopen(argv[1], O_RDONLY), RAID_AUTORUN, NULL) != 0) { + bb_perror_msg_and_die("ioctl"); + } + + return EXIT_SUCCESS; +} diff --git a/miscutils/readahead.c b/miscutils/readahead.c new file mode 100644 index 0000000..356c404 --- /dev/null +++ b/miscutils/readahead.c @@ -0,0 +1,34 @@ +/* vi: set sw=4 ts=4: */ +/* + * readahead implementation for busybox + * + * Preloads the given files in RAM, to reduce access time. + * Does this by calling the readahead(2) system call. + * + * Copyright (C) 2006 Michael Opdenacker <michael@free-electrons.com> + * + * Licensed under GPLv2 or later, see file License in this tarball for details. + */ + +#include "busybox.h" + +int readahead_main(int argc, char **argv) +{ + FILE *f; + int retval = EXIT_SUCCESS; + + if (argc == 1) bb_show_usage(); + + while (*++argv) { + if ((f = fopen_or_warn(*argv, "r")) != NULL) { + int r, fd=fileno(f); + + r = readahead(fd, 0, fdlength(fd)); + fclose(f); + if (r >= 0) continue; + } + retval = EXIT_FAILURE; + } + + return retval; +} diff --git a/miscutils/runlevel.c b/miscutils/runlevel.c new file mode 100644 index 0000000..91d49fa --- /dev/null +++ b/miscutils/runlevel.c @@ -0,0 +1,42 @@ +/* vi: set sw=4 ts=4: */ +/* + * runlevel Prints out the previous and the current runlevel. + * + * Version: @(#)runlevel 1.20 16-Apr-1997 MvS + * + * This file is part of the sysvinit suite, + * Copyright 1991-1997 Miquel van Smoorenburg. + * + * Licensed under the GPL v2 or later, see the file LICENSE in this tarball. + * + * initially busyboxified by Bernhard Fischer + */ + +#include "busybox.h" +#include <stdio.h> +#include <utmp.h> +#include <time.h> +#include <stdlib.h> + +int runlevel_main(int argc, char *argv[]) +{ + struct utmp *ut; + char prev; + + if (argc > 1) utmpname(argv[1]); + + setutent(); + while ((ut = getutent()) != NULL) { + if (ut->ut_type == RUN_LVL) { + prev = ut->ut_pid / 256; + if (prev == 0) prev = 'N'; + printf("%c %c\n", prev, ut->ut_pid % 256); + endutent(); + return 0; + } + } + + puts("unknown"); + endutent(); + return 1; +} diff --git a/miscutils/rx.c b/miscutils/rx.c new file mode 100644 index 0000000..9b9f6af --- /dev/null +++ b/miscutils/rx.c @@ -0,0 +1,290 @@ +/* vi: set sw=4 ts=4: */ +/*------------------------------------------------------------------------- + * 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 <ch@hpl.hp.com> + * 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 + * + * Licensed under GPLv2 or later, see file LICENSE in this tarball for details. + * + * This was originally written for blob and then adapted for busybox. + * + */ + +#include "busybox.h" + +#define SOH 0x01 +#define STX 0x02 +#define EOT 0x04 +#define ACK 0x06 +#define NAK 0x15 +#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 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) + + /* Flush pending input */ + tcflush(ttyfd, TCIFLUSH); + + /* Ask for CRC; if we get errors, we will go with checksum */ + write(ttyfd, &nak, 1); + + 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: + nak = ACK; + write(ttyfd, &nak, 1); + 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 (full_write(filefd, blockBuf, blockLength) < 0) { + note_error("write to file failed: %m"); + goto fatal; + } + + next: + errors = 0; + nak = ACK; + write(ttyfd, &nak, 1); + continue; + + error: + timeout: + errors++; + if (errors == MAXERRORS) { + /* Abort */ + + // 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: + /* 5 CAN followed by 5 BS */ + write(ttyfd, "\030\030\030\030\030\010\010\010\010\010", 10); + return -1; + } + + /* Flush pending input */ + tcflush(ttyfd, TCIFLUSH); + + write(ttyfd, &nak, 1); + } + + done: + return length; + +#undef note_error +} + +static void sigalrm_handler(int ATTRIBUTE_UNUSED 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 = xopen(CURRENT_TTY, O_RDWR); + filefd = xopen(fn, O_RDWR|O_CREAT|O_TRUNC); + + if (tcgetattr(ttyfd, &tty) < 0) + bb_perror_msg_and_die("tcgetattr"); + + 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("\nreceive failed:\n %s", error_buf); + + fflush_stdout_and_exit(EXIT_SUCCESS); +} diff --git a/miscutils/setsid.c b/miscutils/setsid.c new file mode 100644 index 0000000..347b2ba --- /dev/null +++ b/miscutils/setsid.c @@ -0,0 +1,44 @@ +/* vi: set sw=4 ts=4: */ +/* + * setsid.c -- execute a command in a new session + * Rick Sladkey <jrs@world.std.com> + * In the public domain. + * + * 1999-02-22 Arkadiusz Mi¶kiewicz <misiek@pld.ORG.PL> + * - added Native Language Support + * + * 2001-01-18 John Fremlin <vii@penguinpowered.com> + * - fork in case we are process group leader + * + * 2004-11-12 Paul Fox + * - busyboxed + */ + +#include "busybox.h" +#include <stdio.h> +#include <unistd.h> +#include <stdlib.h> + +int setsid_main(int argc, char *argv[]) +{ + if (argc < 2) + bb_show_usage(); + + if (getpgrp() == getpid()) { + switch (fork()){ + case -1: + bb_perror_msg_and_die("fork"); + case 0: + break; + default: /* parent */ + exit(0); + } + /* child falls through */ + } + + setsid(); /* no error possible */ + + execvp(argv[1], argv + 1); + + bb_perror_msg_and_die("%s", argv[1]); +} diff --git a/miscutils/strings.c b/miscutils/strings.c new file mode 100644 index 0000000..0d5576e --- /dev/null +++ b/miscutils/strings.c @@ -0,0 +1,88 @@ +/* vi: set sw=4 ts=4: */ +/* + * strings implementation for busybox + * + * Copyright Tito Ragusa <farmatito@tiscali.it> + * + * Licensed under the GPL v2 or later, see the file LICENSE in this tarball. + */ + +#include "busybox.h" +#include <stdio.h> +#include <stdlib.h> +#include <getopt.h> +#include <ctype.h> + +#define WHOLE_FILE 1 +#define PRINT_NAME 2 +#define PRINT_OFFSET 4 +#define SIZE 8 + +int strings_main(int argc, char **argv) +{ + int n, c, i = 0, status = EXIT_SUCCESS; + unsigned opt; + unsigned long count; + FILE *file = stdin; + char *string; + const char *fmt = "%s: "; + char *n_arg = "4"; + + opt = getopt32(argc, argv, "afon:", &n_arg); + /* -a is our default behaviour */ + + argc -= optind; + argv += optind; + + n = xatoul_range(n_arg, 1, INT_MAX); + string = xzalloc(n + 1); + n--; + + if (argc == 0) { + fmt = "{%s}: "; + *argv = (char *)bb_msg_standard_input; + goto PIPE; + } + + do { + file = fopen_or_warn(*argv, "r"); + if (file) { +PIPE: + count = 0; + do { + c = fgetc(file); + if (isprint(c) || c == '\t') { + if (i <= n) { + string[i] = c; + } else { + putchar(c); + } + if (i == n) { + if (opt & PRINT_NAME) { + printf(fmt, *argv); + } + if (opt & PRINT_OFFSET) { + printf("%7lo ", count - n); + } + printf("%s", string); + } + i++; + } else { + if (i > n) { + putchar('\n'); + } + i = 0; + } + count++; + } while (c != EOF); + fclose_if_not_stdin(file); + } else { + status = EXIT_FAILURE; + } + } while (--argc > 0); + + if (ENABLE_FEATURE_CLEAN_UP) + free(string); + + fflush_stdout_and_exit(status); +} diff --git a/miscutils/taskset.c b/miscutils/taskset.c new file mode 100644 index 0000000..4496aa5 --- /dev/null +++ b/miscutils/taskset.c @@ -0,0 +1,96 @@ +/* vi: set sw=4 ts=4: */ +/* + * taskset - retrieve or set a processes' CPU affinity + * Copyright (c) 2006 Bernhard Fischer + * + * Licensed under GPLv2 or later, see file LICENSE in this tarball for details. + */ + +#include "busybox.h" +#include <sched.h> +#include <unistd.h> +#include <getopt.h> /* optind */ + +#if ENABLE_FEATURE_TASKSET_FANCY +#define TASKSET_PRINTF_MASK "%s" +#define from_cpuset(x) __from_cpuset(&x) +/* craft a string from the mask */ +static char *__from_cpuset(cpu_set_t *mask) { + int i; + char *ret = 0, *str = xzalloc(9); + + for (i = CPU_SETSIZE - 4; i >= 0; i -= 4) { + char val = 0; + int off; + for (off = 0; off <= 3; ++off) + if (CPU_ISSET(i+off, mask)) + val |= 1<<off; + + if (!ret && val) + ret = str; + *str++ = (val-'0'<=9) ? (val+48) : (val+87); + } + return ret; +} +#else +#define TASKSET_PRINTF_MASK "%x" +#define from_cpuset(mask) mask +#endif + +#define TASKSET_OPT_p (1) + +int taskset_main(int argc, char** argv) +{ + cpu_set_t mask, new_mask; + pid_t pid = 0; + unsigned long ul; + const char *state = "current\0new"; + char *p_opt = NULL, *aff = NULL; + + ul = getopt32(argc, argv, "+p:", &p_opt); + + if (ul & TASKSET_OPT_p) { + if (argc == optind+1) { /* -p <aff> <pid> */ + aff = p_opt; + p_opt = argv[optind]; + } + argv += optind; /* me -p <arg> */ + pid = xatoul_range(p_opt, 1, ULONG_MAX); /* -p <pid> */ + } else + aff = *++argv; /* <aff> <cmd...> */ + if (aff) { + unsigned i = 0; + unsigned long l = xstrtol_range(aff, 16, 1, ULONG_MAX); + + CPU_ZERO(&new_mask); + while (i < CPU_SETSIZE && l >= (1<<i)) { + if ((1<<i) & l) + CPU_SET(i, &new_mask); + ++i; + } + } + + if (ul & TASKSET_OPT_p) { +print_aff: + if (sched_getaffinity(pid, sizeof (mask), &mask) < 0) + bb_perror_msg_and_die("Failed to %cet pid %d's affinity", 'g', pid); + printf("pid %d's %s affinity mask: "TASKSET_PRINTF_MASK"\n", + pid, state, from_cpuset(mask)); + if (!*argv) /* no new affinity given or we did print already, done. */ + return EXIT_SUCCESS; + } + + if (sched_setaffinity(pid, sizeof (new_mask), &new_mask)) + bb_perror_msg_and_die("Failed to %cet pid %d's affinity", 's', pid); + if (ul & TASKSET_OPT_p) { + state += 8; + ++argv; + goto print_aff; + } + ++argv; + execvp(*argv, argv); + bb_perror_msg_and_die("%s", *argv); +} +#undef TASKSET_OPT_p +#undef TASKSET_PRINTF_MASK +#undef from_cpuset diff --git a/miscutils/time.c b/miscutils/time.c new file mode 100644 index 0000000..3f1451c --- /dev/null +++ b/miscutils/time.c @@ -0,0 +1,467 @@ +/* vi: set sw=4 ts=4: */ +/* `time' utility to display resource usage of processes. + Copyright (C) 1990, 91, 92, 93, 96 Free Software Foundation, Inc. + + Licensed under GPL version 2, see file LICENSE in this tarball for details. +*/ +/* Originally written by David Keppel <pardo@cs.washington.edu>. + Heavily modified by David MacKenzie <djm@gnu.ai.mit.edu>. + Heavily modified for busybox by Erik Andersen <andersen@codepoet.org> +*/ + +#include "busybox.h" + +#define TV_MSEC tv_usec / 1000 + +/* 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(bb_msg_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(bb_msg_write_error); + } + putc('\n', fp); + + if (ferror(fp)) + bb_error_msg_and_die(bb_msg_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 = vfork(); /* 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); +} + +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/miscutils/watchdog.c b/miscutils/watchdog.c new file mode 100644 index 0000000..e342c13 --- /dev/null +++ b/miscutils/watchdog.c @@ -0,0 +1,65 @@ +/* vi: set sw=4 ts=4: */ +/* + * Mini watchdog implementation for busybox + * + * Copyright (C) 2003 Paul Mundt <lethal@linux-sh.org> + * Copyright (C) 2006 Bernhard Fischer <busybox@busybox.net> + * + * Licensed under the GPL v2 or later, see the file LICENSE in this tarball. + */ + +#include "busybox.h" + +#define OPT_FOREGROUND 0x01 +#define OPT_TIMER 0x02 + +/* Watchdog file descriptor */ +static int fd; + +static void watchdog_shutdown(int ATTRIBUTE_UNUSED unused) +{ + write(fd, "V", 1); /* Magic, see watchdog-api.txt in kernel */ + close(fd); + exit(0); +} + +int watchdog_main(int argc, char **argv) +{ + unsigned opts; + unsigned timer_duration = 30; /* Userspace timer duration, in seconds */ + char *t_arg; + + opts = getopt32(argc, argv, "Ft:", &t_arg); + + if (opts & OPT_TIMER) + timer_duration = xatou(t_arg); + + /* We're only interested in the watchdog device .. */ + if (optind < argc - 1 || argc == 1) + bb_show_usage(); + +#ifdef BB_NOMMU + if (!(opts & OPT_FOREGROUND)) + vfork_daemon_rexec(0, 1, argc, argv, "-F"); +#else + xdaemon(0, 1); +#endif + + signal(SIGHUP, watchdog_shutdown); + signal(SIGINT, watchdog_shutdown); + + fd = 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; +} |