Some formatting updates (ran the code through indent)

-Erik
This commit is contained in:
Erik Andersen 2000-02-08 19:58:47 +00:00
parent c0bf817bbc
commit e49d5ecbbe
163 changed files with 27109 additions and 26607 deletions

View File

@ -1,3 +1,4 @@
/* vi: set sw=4 ts=4: */
#include "internal.h"
#include <stdio.h>
#include <string.h>
@ -16,329 +17,342 @@ static int been_there_done_that = 0;
* replacement may be in order
*/
#if 0
void exit (int status) __attribute__ ((noreturn));
void exit (int status) { _exit(status); };
void abort (void) __attribute__ ((__noreturn__));
void abort (void) { _exit(0); };
int atexit (void (*__func) (void)) { _exit(0); };
void exit(int status) __attribute__ ((noreturn));
void exit(int status)
{
_exit(status);
};
void abort(void) __attribute__ ((__noreturn__));
void abort(void)
{
_exit(0);
};
int atexit(void (*__func) (void))
{
_exit(0);
};
void *__libc_stack_end;
#endif
static const struct Applet applets[] = {
#ifdef BB_BUSYBOX //bin
{"busybox", busybox_main},
#ifdef BB_BUSYBOX //bin
{"busybox", busybox_main},
#endif
#ifdef BB_BLOCK_DEVICE //sbin
{"block_device", block_device_main},
#ifdef BB_BLOCK_DEVICE //sbin
{"block_device", block_device_main},
#endif
#ifdef BB_CAT //bin
{"cat", cat_main},
#ifdef BB_CAT //bin
{"cat", cat_main},
#endif
#ifdef BB_CHMOD_CHOWN_CHGRP //bin
{"chmod", chmod_chown_chgrp_main},
{"chown", chmod_chown_chgrp_main},
{"chgrp", chmod_chown_chgrp_main},
#ifdef BB_CHMOD_CHOWN_CHGRP //bin
{"chmod", chmod_chown_chgrp_main},
{"chown", chmod_chown_chgrp_main},
{"chgrp", chmod_chown_chgrp_main},
#endif
#ifdef BB_CHROOT //sbin
{"chroot", chroot_main},
#ifdef BB_CHROOT //sbin
{"chroot", chroot_main},
#endif
#ifdef BB_CLEAR //usr/bin
{"clear", clear_main},
#ifdef BB_CLEAR //usr/bin
{"clear", clear_main},
#endif
#ifdef BB_CHVT //usr/bin
{"chvt", chvt_main},
#ifdef BB_CHVT //usr/bin
{"chvt", chvt_main},
#endif
#ifdef BB_CP_MV //bin
{"cp", cp_mv_main},
{"mv", cp_mv_main},
#ifdef BB_CP_MV //bin
{"cp", cp_mv_main},
{"mv", cp_mv_main},
#endif
#ifdef BB_DATE //bin
{"date", date_main},
#ifdef BB_DATE //bin
{"date", date_main},
#endif
#ifdef BB_DD //bin
{"dd", dd_main},
#ifdef BB_DD //bin
{"dd", dd_main},
#endif
#ifdef BB_DF //bin
{"df", df_main},
#ifdef BB_DF //bin
{"df", df_main},
#endif
#ifdef BB_DMESG //bin
{"dmesg", dmesg_main},
#ifdef BB_DMESG //bin
{"dmesg", dmesg_main},
#endif
#ifdef BB_DU //bin
{"du", du_main},
#ifdef BB_DU //bin
{"du", du_main},
#endif
#ifdef BB_DUTMP //usr/sbin
{"dutmp", dutmp_main},
#ifdef BB_DUTMP //usr/sbin
{"dutmp", dutmp_main},
#endif
#ifdef BB_FBSET //usr/sbin
{"fbset", fbset_main},
#ifdef BB_FBSET //usr/sbin
{"fbset", fbset_main},
#endif
#ifdef BB_FDFLUSH //bin
{"fdflush", fdflush_main},
#ifdef BB_FDFLUSH //bin
{"fdflush", fdflush_main},
#endif
#ifdef BB_FIND //usr/bin
{"find", find_main},
#ifdef BB_FIND //usr/bin
{"find", find_main},
#endif
#ifdef BB_FREE //usr/bin
{"free", free_main},
#ifdef BB_FREE //usr/bin
{"free", free_main},
#endif
#ifdef BB_DEALLOCVT //usr/bin
{"deallocvt", deallocvt_main},
#ifdef BB_DEALLOCVT //usr/bin
{"deallocvt", deallocvt_main},
#endif
#ifdef BB_FSCK_MINIX //sbin
{"fsck.minix", fsck_minix_main},
#ifdef BB_FSCK_MINIX //sbin
{"fsck.minix", fsck_minix_main},
#endif
#ifdef BB_MKFS_MINIX //sbin
{"mkfs.minix", mkfs_minix_main},
#ifdef BB_MKFS_MINIX //sbin
{"mkfs.minix", mkfs_minix_main},
#endif
#ifdef BB_GREP //bin
{"grep", grep_main},
#ifdef BB_GREP //bin
{"grep", grep_main},
#endif
#ifdef BB_HALT //sbin
{"halt", halt_main},
#ifdef BB_HALT //sbin
{"halt", halt_main},
#endif
#ifdef BB_HEAD //bin
{"head", head_main},
#ifdef BB_HEAD //bin
{"head", head_main},
#endif
#ifdef BB_HOSTID //usr/bin
{"hostid", hostid_main},
#ifdef BB_HOSTID //usr/bin
{"hostid", hostid_main},
#endif
#ifdef BB_HOSTNAME //bin
{"hostname", hostname_main},
#ifdef BB_HOSTNAME //bin
{"hostname", hostname_main},
#endif
#ifdef BB_INIT //sbin
{"init", init_main},
#ifdef BB_INIT //sbin
{"init", init_main},
#endif
#ifdef BB_INSMOD //sbin
{"insmod", insmod_main},
#ifdef BB_INSMOD //sbin
{"insmod", insmod_main},
#endif
#ifdef BB_FEATURE_LINUXRC //
{"linuxrc", init_main},
#ifdef BB_FEATURE_LINUXRC //
{"linuxrc", init_main},
#endif
#ifdef BB_KILL //bin
{"kill", kill_main},
#ifdef BB_KILL //bin
{"kill", kill_main},
#endif
#ifdef BB_LENGTH //usr/bin
{"length", length_main},
#ifdef BB_LENGTH //usr/bin
{"length", length_main},
#endif
#ifdef BB_LN //bin
{"ln", ln_main},
#ifdef BB_LN //bin
{"ln", ln_main},
#endif
#ifdef BB_LOADACM //usr/bin
{"loadacm", loadacm_main},
#endif
#ifdef BB_LOADFONT //usr/bin
{"loadfont", loadfont_main},
#ifdef BB_LOADACM //usr/bin
{"loadacm", loadacm_main},
#endif
#ifdef BB_LOADKMAP //sbin
{"loadkmap", loadkmap_main},
#ifdef BB_LOADFONT //usr/bin
{"loadfont", loadfont_main},
#endif
#ifdef BB_LS //bin
{"ls", ls_main},
#ifdef BB_LOADKMAP //sbin
{"loadkmap", loadkmap_main},
#endif
#ifdef BB_LSMOD //sbin
{"lsmod", lsmod_main},
#ifdef BB_LS //bin
{"ls", ls_main},
#endif
#ifdef BB_MAKEDEVS //sbin
{"makedevs", makedevs_main},
#ifdef BB_LSMOD //sbin
{"lsmod", lsmod_main},
#endif
#ifdef BB_MATH //usr/bin
{"math", math_main},
#ifdef BB_MAKEDEVS //sbin
{"makedevs", makedevs_main},
#endif
#ifdef BB_MKDIR //bin
{"mkdir", mkdir_main},
#ifdef BB_MATH //usr/bin
{"math", math_main},
#endif
#ifdef BB_MKFIFO //usr/bin
{"mkfifo", mkfifo_main},
#ifdef BB_MKDIR //bin
{"mkdir", mkdir_main},
#endif
#ifdef BB_MKNOD //bin
{"mknod", mknod_main},
#ifdef BB_MKFIFO //usr/bin
{"mkfifo", mkfifo_main},
#endif
#ifdef BB_MKSWAP //sbin
{"mkswap", mkswap_main},
#ifdef BB_MKNOD //bin
{"mknod", mknod_main},
#endif
#ifdef BB_MNC //usr/bin
{"mnc", mnc_main},
#ifdef BB_MKSWAP //sbin
{"mkswap", mkswap_main},
#endif
#ifdef BB_MORE //bin
{"more", more_main},
#ifdef BB_MNC //usr/bin
{"mnc", mnc_main},
#endif
#ifdef BB_MOUNT //bin
{"mount", mount_main},
#ifdef BB_MORE //bin
{"more", more_main},
#endif
#ifdef BB_MT //bin
{"mt", mt_main},
#ifdef BB_MOUNT //bin
{"mount", mount_main},
#endif
#ifdef BB_NSLOOKUP //usr/bin
{"nslookup", nslookup_main},
#ifdef BB_MT //bin
{"mt", mt_main},
#endif
#ifdef BB_PING //bin
{"ping", ping_main},
#ifdef BB_NSLOOKUP //usr/bin
{"nslookup", nslookup_main},
#endif
#ifdef BB_POWEROFF //sbin
{"poweroff", poweroff_main},
#ifdef BB_PING //bin
{"ping", ping_main},
#endif
#ifdef BB_PRINTF //usr/bin
{"printf", printf_main},
#ifdef BB_POWEROFF //sbin
{"poweroff", poweroff_main},
#endif
#ifdef BB_PS //bin
{"ps", ps_main},
#ifdef BB_PRINTF //usr/bin
{"printf", printf_main},
#endif
#ifdef BB_PWD //bin
{"pwd", pwd_main},
#ifdef BB_PS //bin
{"ps", ps_main},
#endif
#ifdef BB_REBOOT //sbin
{"reboot", reboot_main},
#ifdef BB_PWD //bin
{"pwd", pwd_main},
#endif
#ifdef BB_RM //bin
{"rm", rm_main},
#ifdef BB_REBOOT //sbin
{"reboot", reboot_main},
#endif
#ifdef BB_RMDIR //bin
{"rmdir", rmdir_main},
#ifdef BB_RM //bin
{"rm", rm_main},
#endif
#ifdef BB_RMMOD //sbin
{"rmmod", rmmod_main},
#ifdef BB_RMDIR //bin
{"rmdir", rmdir_main},
#endif
#ifdef BB_SFDISK //sbin
{"fdisk", sfdisk_main},
{"sfdisk", sfdisk_main},
#ifdef BB_RMMOD //sbin
{"rmmod", rmmod_main},
#endif
#ifdef BB_SED //bin
{"sed", sed_main},
#ifdef BB_SFDISK //sbin
{"fdisk", sfdisk_main},
{"sfdisk", sfdisk_main},
#endif
#ifdef BB_SLEEP //bin
{"sleep", sleep_main},
#ifdef BB_SED //bin
{"sed", sed_main},
#endif
#ifdef BB_SORT //bin
{"sort", sort_main},
#ifdef BB_SLEEP //bin
{"sleep", sleep_main},
#endif
#ifdef BB_SYNC //bin
{"sync", sync_main},
#ifdef BB_SORT //bin
{"sort", sort_main},
#endif
#ifdef BB_SYSLOGD //sbin
{"syslogd", syslogd_main},
#ifdef BB_SYNC //bin
{"sync", sync_main},
#endif
#ifdef BB_LOGGER //usr/bin
{"logger", logger_main},
#ifdef BB_SYSLOGD //sbin
{"syslogd", syslogd_main},
#endif
#ifdef BB_LOGNAME //usr/bin
{"logname", logname_main},
#ifdef BB_LOGGER //usr/bin
{"logger", logger_main},
#endif
#ifdef BB_SWAPONOFF //sbin
{"swapon", swap_on_off_main},
{"swapoff", swap_on_off_main},
#ifdef BB_LOGNAME //usr/bin
{"logname", logname_main},
#endif
#ifdef BB_TAIL //usr/bin
{"tail", tail_main},
#ifdef BB_SWAPONOFF //sbin
{"swapon", swap_on_off_main},
{"swapoff", swap_on_off_main},
#endif
#ifdef BB_TAR //bin
{"tar", tar_main},
#ifdef BB_TAIL //usr/bin
{"tail", tail_main},
#endif
#ifdef BB_TEE //bin
{"tee", tee_main},
#ifdef BB_TAR //bin
{"tar", tar_main},
#endif
#ifdef BB_TOUCH //usr/bin
{"touch", touch_main},
#ifdef BB_TEE //bin
{"tee", tee_main},
#endif
#ifdef BB_TRUE_FALSE //bin
{"true", true_main},
{"false", false_main},
#ifdef BB_TOUCH //usr/bin
{"touch", touch_main},
#endif
#ifdef BB_TTY //usr/bin
{"tty", tty_main},
#ifdef BB_TRUE_FALSE //bin
{"true", true_main},
{"false", false_main},
#endif
#ifdef BB_UNAME //bin
{"uname", uname_main},
#ifdef BB_TTY //usr/bin
{"tty", tty_main},
#endif
#ifdef BB_UMOUNT //bin
{"umount", umount_main},
#ifdef BB_UNAME //bin
{"uname", uname_main},
#endif
#ifdef BB_UNIQ //bin
{"uniq", uniq_main},
#ifdef BB_UMOUNT //bin
{"umount", umount_main},
#endif
#ifdef BB_UPDATE //sbin
{"update", update_main},
#ifdef BB_UNIQ //bin
{"uniq", uniq_main},
#endif
#ifdef BB_WC //usr/bin
{"wc", wc_main},
#ifdef BB_UPDATE //sbin
{"update", update_main},
#endif
#ifdef BB_WHOAMI //usr/bin
{"whoami", whoami_main},
#ifdef BB_WC //usr/bin
{"wc", wc_main},
#endif
#ifdef BB_YES //usr/bin
{"yes", yes_main},
#ifdef BB_WHOAMI //usr/bin
{"whoami", whoami_main},
#endif
#ifdef BB_GUNZIP //bin
{"zcat", gunzip_main},
{"gunzip", gunzip_main},
#ifdef BB_YES //usr/bin
{"yes", yes_main},
#endif
#ifdef BB_GZIP //bin
{"gzip", gzip_main},
#ifdef BB_GUNZIP //bin
{"zcat", gunzip_main},
{"gunzip", gunzip_main},
#endif
{0}
#ifdef BB_GZIP //bin
{"gzip", gzip_main},
#endif
{0}
};
int main(int argc, char **argv)
{
char *s = argv[0];
char *name = argv[0];
const struct Applet *a = applets;
char *s = argv[0];
char *name = argv[0];
const struct Applet *a = applets;
while (*s != '\0') {
if (*s++ == '/')
name = s;
}
while (a->name != 0) {
if (strcmp(name, a->name) == 0) {
int status;
status = ((*(a->main)) (argc, argv));
if (status < 0) {
fprintf(stderr, "%s: %s\n", a->name, strerror(errno));
}
fprintf(stderr, "\n");
exit(status);
while (*s != '\0') {
if (*s++ == '/')
name = s;
}
a++;
}
exit (busybox_main(argc, argv));
while (a->name != 0) {
if (strcmp(name, a->name) == 0) {
int status;
status = ((*(a->main)) (argc, argv));
if (status < 0) {
fprintf(stderr, "%s: %s\n", a->name, strerror(errno));
}
fprintf(stderr, "\n");
exit(status);
}
a++;
}
exit(busybox_main(argc, argv));
}
int busybox_main(int argc, char **argv)
{
int col=0;
argc--;
argv++;
int col = 0;
if (been_there_done_that == 1 || argc < 1) {
const struct Applet *a = applets;
fprintf(stderr, "BusyBox v%s (%s) multi-call binary -- GPL2\n\n",
BB_VER, BB_BT);
fprintf(stderr, "Usage: busybox [function] [arguments]...\n");
fprintf(stderr, " or: [function] [arguments]...\n\n");
fprintf(stderr,
"\tMost people will create a symlink to busybox for each\n"
"\tfunction name, and busybox will act like whatever you invoke it as.\n");
fprintf(stderr, "\nCurrently defined functions:\n");
argc--;
argv++;
while (a->name != 0) {
col+=fprintf(stderr, "%s%s", ((col==0)? "\t":", "), (a++)->name);
if (col>60 && a->name != 0) {
fprintf(stderr, ",\n");
col=0;
}
if (been_there_done_that == 1 || argc < 1) {
const struct Applet *a = applets;
fprintf(stderr, "BusyBox v%s (%s) multi-call binary -- GPL2\n\n",
BB_VER, BB_BT);
fprintf(stderr, "Usage: busybox [function] [arguments]...\n");
fprintf(stderr, " or: [function] [arguments]...\n\n");
fprintf(stderr,
"\tMost people will create a symlink to busybox for each\n"
"\tfunction name, and busybox will act like whatever you invoke it as.\n");
fprintf(stderr, "\nCurrently defined functions:\n");
while (a->name != 0) {
col +=
fprintf(stderr, "%s%s", ((col == 0) ? "\t" : ", "),
(a++)->name);
if (col > 60 && a->name != 0) {
fprintf(stderr, ",\n");
col = 0;
}
}
fprintf(stderr, "\n\n");
exit(-1);
} else {
/* If we've already been here once, exit now */
been_there_done_that = 1;
return (main(argc, argv));
}
fprintf(stderr, "\n\n");
exit(-1);
} else {
/* If we've already been here once, exit now */
been_there_done_that = 1;
return (main(argc, argv));
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

460
busybox.c
View File

@ -1,3 +1,4 @@
/* vi: set sw=4 ts=4: */
#include "internal.h"
#include <stdio.h>
#include <string.h>
@ -16,329 +17,342 @@ static int been_there_done_that = 0;
* replacement may be in order
*/
#if 0
void exit (int status) __attribute__ ((noreturn));
void exit (int status) { _exit(status); };
void abort (void) __attribute__ ((__noreturn__));
void abort (void) { _exit(0); };
int atexit (void (*__func) (void)) { _exit(0); };
void exit(int status) __attribute__ ((noreturn));
void exit(int status)
{
_exit(status);
};
void abort(void) __attribute__ ((__noreturn__));
void abort(void)
{
_exit(0);
};
int atexit(void (*__func) (void))
{
_exit(0);
};
void *__libc_stack_end;
#endif
static const struct Applet applets[] = {
#ifdef BB_BUSYBOX //bin
{"busybox", busybox_main},
#ifdef BB_BUSYBOX //bin
{"busybox", busybox_main},
#endif
#ifdef BB_BLOCK_DEVICE //sbin
{"block_device", block_device_main},
#ifdef BB_BLOCK_DEVICE //sbin
{"block_device", block_device_main},
#endif
#ifdef BB_CAT //bin
{"cat", cat_main},
#ifdef BB_CAT //bin
{"cat", cat_main},
#endif
#ifdef BB_CHMOD_CHOWN_CHGRP //bin
{"chmod", chmod_chown_chgrp_main},
{"chown", chmod_chown_chgrp_main},
{"chgrp", chmod_chown_chgrp_main},
#ifdef BB_CHMOD_CHOWN_CHGRP //bin
{"chmod", chmod_chown_chgrp_main},
{"chown", chmod_chown_chgrp_main},
{"chgrp", chmod_chown_chgrp_main},
#endif
#ifdef BB_CHROOT //sbin
{"chroot", chroot_main},
#ifdef BB_CHROOT //sbin
{"chroot", chroot_main},
#endif
#ifdef BB_CLEAR //usr/bin
{"clear", clear_main},
#ifdef BB_CLEAR //usr/bin
{"clear", clear_main},
#endif
#ifdef BB_CHVT //usr/bin
{"chvt", chvt_main},
#ifdef BB_CHVT //usr/bin
{"chvt", chvt_main},
#endif
#ifdef BB_CP_MV //bin
{"cp", cp_mv_main},
{"mv", cp_mv_main},
#ifdef BB_CP_MV //bin
{"cp", cp_mv_main},
{"mv", cp_mv_main},
#endif
#ifdef BB_DATE //bin
{"date", date_main},
#ifdef BB_DATE //bin
{"date", date_main},
#endif
#ifdef BB_DD //bin
{"dd", dd_main},
#ifdef BB_DD //bin
{"dd", dd_main},
#endif
#ifdef BB_DF //bin
{"df", df_main},
#ifdef BB_DF //bin
{"df", df_main},
#endif
#ifdef BB_DMESG //bin
{"dmesg", dmesg_main},
#ifdef BB_DMESG //bin
{"dmesg", dmesg_main},
#endif
#ifdef BB_DU //bin
{"du", du_main},
#ifdef BB_DU //bin
{"du", du_main},
#endif
#ifdef BB_DUTMP //usr/sbin
{"dutmp", dutmp_main},
#ifdef BB_DUTMP //usr/sbin
{"dutmp", dutmp_main},
#endif
#ifdef BB_FBSET //usr/sbin
{"fbset", fbset_main},
#ifdef BB_FBSET //usr/sbin
{"fbset", fbset_main},
#endif
#ifdef BB_FDFLUSH //bin
{"fdflush", fdflush_main},
#ifdef BB_FDFLUSH //bin
{"fdflush", fdflush_main},
#endif
#ifdef BB_FIND //usr/bin
{"find", find_main},
#ifdef BB_FIND //usr/bin
{"find", find_main},
#endif
#ifdef BB_FREE //usr/bin
{"free", free_main},
#ifdef BB_FREE //usr/bin
{"free", free_main},
#endif
#ifdef BB_DEALLOCVT //usr/bin
{"deallocvt", deallocvt_main},
#ifdef BB_DEALLOCVT //usr/bin
{"deallocvt", deallocvt_main},
#endif
#ifdef BB_FSCK_MINIX //sbin
{"fsck.minix", fsck_minix_main},
#ifdef BB_FSCK_MINIX //sbin
{"fsck.minix", fsck_minix_main},
#endif
#ifdef BB_MKFS_MINIX //sbin
{"mkfs.minix", mkfs_minix_main},
#ifdef BB_MKFS_MINIX //sbin
{"mkfs.minix", mkfs_minix_main},
#endif
#ifdef BB_GREP //bin
{"grep", grep_main},
#ifdef BB_GREP //bin
{"grep", grep_main},
#endif
#ifdef BB_HALT //sbin
{"halt", halt_main},
#ifdef BB_HALT //sbin
{"halt", halt_main},
#endif
#ifdef BB_HEAD //bin
{"head", head_main},
#ifdef BB_HEAD //bin
{"head", head_main},
#endif
#ifdef BB_HOSTID //usr/bin
{"hostid", hostid_main},
#ifdef BB_HOSTID //usr/bin
{"hostid", hostid_main},
#endif
#ifdef BB_HOSTNAME //bin
{"hostname", hostname_main},
#ifdef BB_HOSTNAME //bin
{"hostname", hostname_main},
#endif
#ifdef BB_INIT //sbin
{"init", init_main},
#ifdef BB_INIT //sbin
{"init", init_main},
#endif
#ifdef BB_INSMOD //sbin
{"insmod", insmod_main},
#ifdef BB_INSMOD //sbin
{"insmod", insmod_main},
#endif
#ifdef BB_FEATURE_LINUXRC //
{"linuxrc", init_main},
#ifdef BB_FEATURE_LINUXRC //
{"linuxrc", init_main},
#endif
#ifdef BB_KILL //bin
{"kill", kill_main},
#ifdef BB_KILL //bin
{"kill", kill_main},
#endif
#ifdef BB_LENGTH //usr/bin
{"length", length_main},
#ifdef BB_LENGTH //usr/bin
{"length", length_main},
#endif
#ifdef BB_LN //bin
{"ln", ln_main},
#ifdef BB_LN //bin
{"ln", ln_main},
#endif
#ifdef BB_LOADACM //usr/bin
{"loadacm", loadacm_main},
#endif
#ifdef BB_LOADFONT //usr/bin
{"loadfont", loadfont_main},
#ifdef BB_LOADACM //usr/bin
{"loadacm", loadacm_main},
#endif
#ifdef BB_LOADKMAP //sbin
{"loadkmap", loadkmap_main},
#ifdef BB_LOADFONT //usr/bin
{"loadfont", loadfont_main},
#endif
#ifdef BB_LS //bin
{"ls", ls_main},
#ifdef BB_LOADKMAP //sbin
{"loadkmap", loadkmap_main},
#endif
#ifdef BB_LSMOD //sbin
{"lsmod", lsmod_main},
#ifdef BB_LS //bin
{"ls", ls_main},
#endif
#ifdef BB_MAKEDEVS //sbin
{"makedevs", makedevs_main},
#ifdef BB_LSMOD //sbin
{"lsmod", lsmod_main},
#endif
#ifdef BB_MATH //usr/bin
{"math", math_main},
#ifdef BB_MAKEDEVS //sbin
{"makedevs", makedevs_main},
#endif
#ifdef BB_MKDIR //bin
{"mkdir", mkdir_main},
#ifdef BB_MATH //usr/bin
{"math", math_main},
#endif
#ifdef BB_MKFIFO //usr/bin
{"mkfifo", mkfifo_main},
#ifdef BB_MKDIR //bin
{"mkdir", mkdir_main},
#endif
#ifdef BB_MKNOD //bin
{"mknod", mknod_main},
#ifdef BB_MKFIFO //usr/bin
{"mkfifo", mkfifo_main},
#endif
#ifdef BB_MKSWAP //sbin
{"mkswap", mkswap_main},
#ifdef BB_MKNOD //bin
{"mknod", mknod_main},
#endif
#ifdef BB_MNC //usr/bin
{"mnc", mnc_main},
#ifdef BB_MKSWAP //sbin
{"mkswap", mkswap_main},
#endif
#ifdef BB_MORE //bin
{"more", more_main},
#ifdef BB_MNC //usr/bin
{"mnc", mnc_main},
#endif
#ifdef BB_MOUNT //bin
{"mount", mount_main},
#ifdef BB_MORE //bin
{"more", more_main},
#endif
#ifdef BB_MT //bin
{"mt", mt_main},
#ifdef BB_MOUNT //bin
{"mount", mount_main},
#endif
#ifdef BB_NSLOOKUP //usr/bin
{"nslookup", nslookup_main},
#ifdef BB_MT //bin
{"mt", mt_main},
#endif
#ifdef BB_PING //bin
{"ping", ping_main},
#ifdef BB_NSLOOKUP //usr/bin
{"nslookup", nslookup_main},
#endif
#ifdef BB_POWEROFF //sbin
{"poweroff", poweroff_main},
#ifdef BB_PING //bin
{"ping", ping_main},
#endif
#ifdef BB_PRINTF //usr/bin
{"printf", printf_main},
#ifdef BB_POWEROFF //sbin
{"poweroff", poweroff_main},
#endif
#ifdef BB_PS //bin
{"ps", ps_main},
#ifdef BB_PRINTF //usr/bin
{"printf", printf_main},
#endif
#ifdef BB_PWD //bin
{"pwd", pwd_main},
#ifdef BB_PS //bin
{"ps", ps_main},
#endif
#ifdef BB_REBOOT //sbin
{"reboot", reboot_main},
#ifdef BB_PWD //bin
{"pwd", pwd_main},
#endif
#ifdef BB_RM //bin
{"rm", rm_main},
#ifdef BB_REBOOT //sbin
{"reboot", reboot_main},
#endif
#ifdef BB_RMDIR //bin
{"rmdir", rmdir_main},
#ifdef BB_RM //bin
{"rm", rm_main},
#endif
#ifdef BB_RMMOD //sbin
{"rmmod", rmmod_main},
#ifdef BB_RMDIR //bin
{"rmdir", rmdir_main},
#endif
#ifdef BB_SFDISK //sbin
{"fdisk", sfdisk_main},
{"sfdisk", sfdisk_main},
#ifdef BB_RMMOD //sbin
{"rmmod", rmmod_main},
#endif
#ifdef BB_SED //bin
{"sed", sed_main},
#ifdef BB_SFDISK //sbin
{"fdisk", sfdisk_main},
{"sfdisk", sfdisk_main},
#endif
#ifdef BB_SLEEP //bin
{"sleep", sleep_main},
#ifdef BB_SED //bin
{"sed", sed_main},
#endif
#ifdef BB_SORT //bin
{"sort", sort_main},
#ifdef BB_SLEEP //bin
{"sleep", sleep_main},
#endif
#ifdef BB_SYNC //bin
{"sync", sync_main},
#ifdef BB_SORT //bin
{"sort", sort_main},
#endif
#ifdef BB_SYSLOGD //sbin
{"syslogd", syslogd_main},
#ifdef BB_SYNC //bin
{"sync", sync_main},
#endif
#ifdef BB_LOGGER //usr/bin
{"logger", logger_main},
#ifdef BB_SYSLOGD //sbin
{"syslogd", syslogd_main},
#endif
#ifdef BB_LOGNAME //usr/bin
{"logname", logname_main},
#ifdef BB_LOGGER //usr/bin
{"logger", logger_main},
#endif
#ifdef BB_SWAPONOFF //sbin
{"swapon", swap_on_off_main},
{"swapoff", swap_on_off_main},
#ifdef BB_LOGNAME //usr/bin
{"logname", logname_main},
#endif
#ifdef BB_TAIL //usr/bin
{"tail", tail_main},
#ifdef BB_SWAPONOFF //sbin
{"swapon", swap_on_off_main},
{"swapoff", swap_on_off_main},
#endif
#ifdef BB_TAR //bin
{"tar", tar_main},
#ifdef BB_TAIL //usr/bin
{"tail", tail_main},
#endif
#ifdef BB_TEE //bin
{"tee", tee_main},
#ifdef BB_TAR //bin
{"tar", tar_main},
#endif
#ifdef BB_TOUCH //usr/bin
{"touch", touch_main},
#ifdef BB_TEE //bin
{"tee", tee_main},
#endif
#ifdef BB_TRUE_FALSE //bin
{"true", true_main},
{"false", false_main},
#ifdef BB_TOUCH //usr/bin
{"touch", touch_main},
#endif
#ifdef BB_TTY //usr/bin
{"tty", tty_main},
#ifdef BB_TRUE_FALSE //bin
{"true", true_main},
{"false", false_main},
#endif
#ifdef BB_UNAME //bin
{"uname", uname_main},
#ifdef BB_TTY //usr/bin
{"tty", tty_main},
#endif
#ifdef BB_UMOUNT //bin
{"umount", umount_main},
#ifdef BB_UNAME //bin
{"uname", uname_main},
#endif
#ifdef BB_UNIQ //bin
{"uniq", uniq_main},
#ifdef BB_UMOUNT //bin
{"umount", umount_main},
#endif
#ifdef BB_UPDATE //sbin
{"update", update_main},
#ifdef BB_UNIQ //bin
{"uniq", uniq_main},
#endif
#ifdef BB_WC //usr/bin
{"wc", wc_main},
#ifdef BB_UPDATE //sbin
{"update", update_main},
#endif
#ifdef BB_WHOAMI //usr/bin
{"whoami", whoami_main},
#ifdef BB_WC //usr/bin
{"wc", wc_main},
#endif
#ifdef BB_YES //usr/bin
{"yes", yes_main},
#ifdef BB_WHOAMI //usr/bin
{"whoami", whoami_main},
#endif
#ifdef BB_GUNZIP //bin
{"zcat", gunzip_main},
{"gunzip", gunzip_main},
#ifdef BB_YES //usr/bin
{"yes", yes_main},
#endif
#ifdef BB_GZIP //bin
{"gzip", gzip_main},
#ifdef BB_GUNZIP //bin
{"zcat", gunzip_main},
{"gunzip", gunzip_main},
#endif
{0}
#ifdef BB_GZIP //bin
{"gzip", gzip_main},
#endif
{0}
};
int main(int argc, char **argv)
{
char *s = argv[0];
char *name = argv[0];
const struct Applet *a = applets;
char *s = argv[0];
char *name = argv[0];
const struct Applet *a = applets;
while (*s != '\0') {
if (*s++ == '/')
name = s;
}
while (a->name != 0) {
if (strcmp(name, a->name) == 0) {
int status;
status = ((*(a->main)) (argc, argv));
if (status < 0) {
fprintf(stderr, "%s: %s\n", a->name, strerror(errno));
}
fprintf(stderr, "\n");
exit(status);
while (*s != '\0') {
if (*s++ == '/')
name = s;
}
a++;
}
exit (busybox_main(argc, argv));
while (a->name != 0) {
if (strcmp(name, a->name) == 0) {
int status;
status = ((*(a->main)) (argc, argv));
if (status < 0) {
fprintf(stderr, "%s: %s\n", a->name, strerror(errno));
}
fprintf(stderr, "\n");
exit(status);
}
a++;
}
exit(busybox_main(argc, argv));
}
int busybox_main(int argc, char **argv)
{
int col=0;
argc--;
argv++;
int col = 0;
if (been_there_done_that == 1 || argc < 1) {
const struct Applet *a = applets;
fprintf(stderr, "BusyBox v%s (%s) multi-call binary -- GPL2\n\n",
BB_VER, BB_BT);
fprintf(stderr, "Usage: busybox [function] [arguments]...\n");
fprintf(stderr, " or: [function] [arguments]...\n\n");
fprintf(stderr,
"\tMost people will create a symlink to busybox for each\n"
"\tfunction name, and busybox will act like whatever you invoke it as.\n");
fprintf(stderr, "\nCurrently defined functions:\n");
argc--;
argv++;
while (a->name != 0) {
col+=fprintf(stderr, "%s%s", ((col==0)? "\t":", "), (a++)->name);
if (col>60 && a->name != 0) {
fprintf(stderr, ",\n");
col=0;
}
if (been_there_done_that == 1 || argc < 1) {
const struct Applet *a = applets;
fprintf(stderr, "BusyBox v%s (%s) multi-call binary -- GPL2\n\n",
BB_VER, BB_BT);
fprintf(stderr, "Usage: busybox [function] [arguments]...\n");
fprintf(stderr, " or: [function] [arguments]...\n\n");
fprintf(stderr,
"\tMost people will create a symlink to busybox for each\n"
"\tfunction name, and busybox will act like whatever you invoke it as.\n");
fprintf(stderr, "\nCurrently defined functions:\n");
while (a->name != 0) {
col +=
fprintf(stderr, "%s%s", ((col == 0) ? "\t" : ", "),
(a++)->name);
if (col > 60 && a->name != 0) {
fprintf(stderr, ",\n");
col = 0;
}
}
fprintf(stderr, "\n\n");
exit(-1);
} else {
/* If we've already been here once, exit now */
been_there_done_that = 1;
return (main(argc, argv));
}
fprintf(stderr, "\n\n");
exit(-1);
} else {
/* If we've already been here once, exit now */
been_there_done_that = 1;
return (main(argc, argv));
}
}

View File

@ -1,3 +1,4 @@
/* vi: set sw=4 ts=4: */
// This file defines the feature set to be compiled into busybox.
// When you turn things off here, they won't be compiled in at all.
//

52
cat.c
View File

@ -1,3 +1,4 @@
/* vi: set sw=4 ts=4: */
/*
* Mini Cat implementation for busybox
*
@ -24,36 +25,37 @@
#include <stdio.h>
static void print_file( FILE *file)
static void print_file(FILE * file)
{
int c;
while ((c = getc(file)) != EOF)
putc(c, stdout);
fclose(file);
fflush(stdout);
int c;
while ((c = getc(file)) != EOF)
putc(c, stdout);
fclose(file);
fflush(stdout);
}
extern int cat_main(int argc, char **argv)
{
FILE *file;
FILE *file;
if (argc==1) {
print_file( stdin);
exit( TRUE);
}
if ( **(argv+1) == '-' ) {
usage ("cat [file ...]\n");
}
argc--;
while (argc-- > 0 && *(argv++) != '\0' && strlen(*argv) ) {
file = fopen(*argv, "r");
if (file == NULL) {
perror(*argv);
exit(FALSE);
if (argc == 1) {
print_file(stdin);
exit(TRUE);
}
print_file( file);
}
exit(TRUE);
if (**(argv + 1) == '-') {
usage("cat [file ...]\n");
}
argc--;
while (argc-- > 0 && *(argv++) != '\0' && strlen(*argv)) {
file = fopen(*argv, "r");
if (file == NULL) {
perror(*argv);
exit(FALSE);
}
print_file(file);
}
exit(TRUE);
}

View File

@ -1,3 +1,4 @@
/* vi: set sw=4 ts=4: */
/*
* Mini chown/chmod/chgrp implementation for busybox
*
@ -34,8 +35,8 @@
static uid_t uid = -1;
static gid_t gid = -1;
static int whichApp;
static char* invocationName=NULL;
static char* theMode=NULL;
static char *invocationName = NULL;
static char *theMode = NULL;
#define CHGRP_APP 1
@ -43,130 +44,147 @@ static char* theMode=NULL;
#define CHMOD_APP 3
static const char chgrp_usage[] = "chgrp [OPTION]... GROUP FILE...\n\n"
"Change the group membership of each FILE to GROUP.\n"
"\nOptions:\n\t-R\tchange files and directories recursively\n";
static const char chown_usage[] = "chown [OPTION]... OWNER[.[GROUP] FILE...\n\n"
"Change the owner and/or group of each FILE to OWNER and/or GROUP.\n"
"\nOptions:\n\t-R\tchange files and directories recursively\n";
static const char chmod_usage[] = "chmod [-R] MODE[,MODE]... FILE...\n\n"
"Each MODE is one or more of the letters ugoa, one of the symbols +-= and\n"
"one or more of the letters rwxst.\n\n"
"\nOptions:\n\t-R\tchange files and directories recursively.\n";
"Change the group membership of each FILE to GROUP.\n"
"\nOptions:\n\t-R\tchange files and directories recursively\n";
static const char chown_usage[] =
"chown [OPTION]... OWNER[.[GROUP] FILE...\n\n"
"Change the owner and/or group of each FILE to OWNER and/or GROUP.\n"
"\nOptions:\n\t-R\tchange files and directories recursively\n";
static const char chmod_usage[] =
"chmod [-R] MODE[,MODE]... FILE...\n\n"
"Each MODE is one or more of the letters ugoa, one of the symbols +-= and\n"
"one or more of the letters rwxst.\n\n"
"\nOptions:\n\t-R\tchange files and directories recursively.\n";
static int fileAction(const char *fileName, struct stat* statbuf)
static int fileAction(const char *fileName, struct stat *statbuf)
{
switch (whichApp) {
switch (whichApp) {
case CHGRP_APP:
case CHOWN_APP:
#if (__GLIBC__ >= 2) && (__GLIBC_MINOR__ >= 1)
if (lchown(fileName, (whichApp==CHOWN_APP)? uid : statbuf->st_uid,
(gid==-1)? statbuf->st_gid : gid) == 0)
if (lchown
(fileName, (whichApp == CHOWN_APP) ? uid : statbuf->st_uid,
(gid == -1) ? statbuf->st_gid : gid) == 0)
#else
if (chown(fileName, (whichApp==CHOWN_APP)? uid : statbuf->st_uid,
(gid==-1)? statbuf->st_gid : gid) == 0)
if (chown
(fileName, (whichApp == CHOWN_APP) ? uid : statbuf->st_uid,
(gid == -1) ? statbuf->st_gid : gid) == 0)
#endif
{
return( TRUE);
}
break;
{
return (TRUE);
}
break;
case CHMOD_APP:
/* Parse the specified modes */
if ( parse_mode(theMode, &(statbuf->st_mode)) == FALSE ) {
fprintf(stderr, "%s: unknown mode: %s\n", invocationName, theMode);
exit( FALSE);
}
if (chmod(fileName, statbuf->st_mode) == 0)
return( TRUE);
break;
}
perror(fileName);
return( FALSE);
/* Parse the specified modes */
if (parse_mode(theMode, &(statbuf->st_mode)) == FALSE) {
fprintf(stderr, "%s: unknown mode: %s\n", invocationName,
theMode);
exit(FALSE);
}
if (chmod(fileName, statbuf->st_mode) == 0)
return (TRUE);
break;
}
perror(fileName);
return (FALSE);
}
int chmod_chown_chgrp_main(int argc, char **argv)
{
int recursiveFlag=FALSE;
char *groupName;
char *p;
const char *appUsage;
int recursiveFlag = FALSE;
char *groupName;
char *p;
const char *appUsage;
whichApp = (strcmp(*argv, "chown")==0)? CHOWN_APP : (strcmp(*argv, "chmod")==0)? CHMOD_APP : CHGRP_APP;
whichApp =
(strcmp(*argv, "chown") ==
0) ? CHOWN_APP : (strcmp(*argv,
"chmod") == 0) ? CHMOD_APP : CHGRP_APP;
appUsage = (whichApp==CHOWN_APP)? chown_usage : (whichApp==CHMOD_APP)? chmod_usage : chgrp_usage;
appUsage =
(whichApp == CHOWN_APP) ? chown_usage : (whichApp ==
CHMOD_APP) ? chmod_usage :
chgrp_usage;
if (argc < 2)
usage( appUsage);
invocationName = *argv;
argc--;
argv++;
/* Parse options */
while (**argv == '-') {
while (*++(*argv)) switch (**argv) {
case 'R':
recursiveFlag = TRUE;
break;
default:
fprintf(stderr, invalid_option, invocationName, **argv);
usage( appUsage);
}
if (argc < 2)
usage(appUsage);
invocationName = *argv;
argc--;
argv++;
}
if ( whichApp == CHMOD_APP ) {
theMode = *argv;
} else {
/* Find the selected group */
if ( whichApp==CHGRP_APP ) {
groupName = *argv;
gid = strtoul(groupName, &p, 10); /* maybe it's already numeric */
if (groupName == p)
gid = my_getgrnam(groupName);
if (gid == -1)
goto bad_group;
/* Parse options */
while (**argv == '-') {
while (*++(*argv))
switch (**argv) {
case 'R':
recursiveFlag = TRUE;
break;
default:
fprintf(stderr, invalid_option, invocationName, **argv);
usage(appUsage);
}
argc--;
argv++;
}
if (whichApp == CHMOD_APP) {
theMode = *argv;
} else {
groupName = strchr(*argv, '.');
if (groupName) {
*groupName++ = '\0';
gid = strtoul(groupName, &p, 10);
if (groupName == p)
gid = my_getgrnam(groupName);
if (gid == -1)
goto bad_group;
} else
gid = -1;
/* Find the selected group */
if (whichApp == CHGRP_APP) {
groupName = *argv;
gid = strtoul(groupName, &p, 10); /* maybe it's already numeric */
if (groupName == p)
gid = my_getgrnam(groupName);
if (gid == -1)
goto bad_group;
} else {
groupName = strchr(*argv, '.');
if (groupName) {
*groupName++ = '\0';
gid = strtoul(groupName, &p, 10);
if (groupName == p)
gid = my_getgrnam(groupName);
if (gid == -1)
goto bad_group;
} else
gid = -1;
}
/* Find the selected user (if appropriate) */
if (whichApp == CHOWN_APP) {
uid = strtoul(*argv, &p, 10); /* if numeric ... */
if (*argv == p)
uid = my_getpwnam(*argv);
if (uid == -1) {
fprintf(stderr, "%s: unknown user name: %s\n",
invocationName, *argv);
exit(FALSE);
}
}
}
/* Find the selected user (if appropriate) */
if (whichApp==CHOWN_APP) {
uid = strtoul(*argv, &p, 10); /* if numeric ...*/
if (*argv == p)
uid = my_getpwnam(*argv);
if (uid == -1) {
fprintf(stderr, "%s: unknown user name: %s\n", invocationName, *argv);
exit( FALSE);
}
/* Ok, ready to do the deed now */
if (argc <= 1) {
fprintf(stderr, "%s: too few arguments\n", invocationName);
exit(FALSE);
}
}
/* Ok, ready to do the deed now */
if (argc <= 1) {
fprintf(stderr, "%s: too few arguments\n", invocationName);
exit( FALSE);
}
while (argc-- > 1) {
if (recursiveAction( *(++argv), recursiveFlag, TRUE, FALSE, fileAction, fileAction)==FALSE)
exit( FALSE);
}
exit(TRUE);
while (argc-- > 1) {
if (recursiveAction
(*(++argv), recursiveFlag, TRUE, FALSE, fileAction,
fileAction) == FALSE)
exit(FALSE);
}
exit(TRUE);
bad_group:
fprintf(stderr, "%s: unknown group name: %s\n", invocationName, groupName);
exit( FALSE);
bad_group:
fprintf(stderr, "%s: unknown group name: %s\n", invocationName,
groupName);
exit(FALSE);
}

View File

@ -1,3 +1,4 @@
/* vi: set sw=4 ts=4: */
/*
* Mini chroot implementation for busybox
*
@ -28,39 +29,39 @@
static const char chroot_usage[] = "chroot NEWROOT [COMMAND...]\n\n"
"Run COMMAND with root directory set to NEWROOT.\n";
"Run COMMAND with root directory set to NEWROOT.\n";
int chroot_main(int argc, char **argv)
{
if ( (argc < 2) || (**(argv+1) == '-') ) {
usage( chroot_usage);
}
argc--;
argv++;
if ((argc < 2) || (**(argv + 1) == '-')) {
usage(chroot_usage);
}
argc--;
argv++;
if (chroot (*argv) || (chdir ("/"))) {
fprintf(stderr, "chroot: cannot change root directory to %s: %s\n",
*argv, strerror(errno));
exit( FALSE);
}
if (chroot(*argv) || (chdir("/"))) {
fprintf(stderr, "chroot: cannot change root directory to %s: %s\n",
*argv, strerror(errno));
exit(FALSE);
}
argc--;
argv++;
if (argc >= 1) {
fprintf(stderr, "command: %s\n", *argv);
execvp (*argv, argv);
}
else {
char *prog;
prog = getenv ("SHELL");
if (!prog)
prog = "/bin/sh";
execlp (prog, prog, NULL);
}
fprintf(stderr, "chroot: cannot execute %s: %s\n",
*argv, strerror(errno));
exit( FALSE);
argc--;
argv++;
if (argc >= 1) {
fprintf(stderr, "command: %s\n", *argv);
execvp(*argv, argv);
} else {
char *prog;
prog = getenv("SHELL");
if (!prog)
prog = "/bin/sh";
execlp(prog, prog, NULL);
}
fprintf(stderr, "chroot: cannot execute %s: %s\n",
*argv, strerror(errno));
exit(FALSE);
}

36
chvt.c
View File

@ -1,3 +1,4 @@
/* vi: set sw=4 ts=4: */
/*
* chvt.c - aeb - 940227 - Change virtual terminal
*
@ -13,24 +14,23 @@
extern int getfd(void);
int
chvt_main(int argc, char** argv)
int chvt_main(int argc, char **argv)
{
int fd, num;
int fd, num;
if ( ( argc != 2) || (**(argv+1) == '-' ) ) {
usage ("chvt N\n\nChange foreground virtual terminal to /dev/ttyN\n");
}
fd = get_console_fd("/dev/console");
num = atoi(argv[1]);
if (ioctl(fd,VT_ACTIVATE,num)) {
perror("VT_ACTIVATE");
exit(FALSE);
}
if (ioctl(fd,VT_WAITACTIVE,num)) {
perror("VT_WAITACTIVE");
exit(FALSE);
}
exit( TRUE);
if ((argc != 2) || (**(argv + 1) == '-')) {
usage
("chvt N\n\nChange foreground virtual terminal to /dev/ttyN\n");
}
fd = get_console_fd("/dev/console");
num = atoi(argv[1]);
if (ioctl(fd, VT_ACTIVATE, num)) {
perror("VT_ACTIVATE");
exit(FALSE);
}
if (ioctl(fd, VT_WAITACTIVE, num)) {
perror("VT_WAITACTIVE");
exit(FALSE);
}
exit(TRUE);
}

View File

@ -1,3 +1,4 @@
/* vi: set sw=4 ts=4: */
/*
* Mini clear implementation for busybox
*
@ -25,9 +26,8 @@
#include <stdio.h>
extern int
clear_main(int argc, char** argv)
extern int clear_main(int argc, char **argv)
{
printf("\033[H\033[J");
exit( TRUE);
exit(TRUE);
}

View File

@ -1,3 +1,4 @@
/* vi: set sw=4 ts=4: */
/*
* chvt.c - aeb - 940227 - Change virtual terminal
*
@ -13,24 +14,23 @@
extern int getfd(void);
int
chvt_main(int argc, char** argv)
int chvt_main(int argc, char **argv)
{
int fd, num;
int fd, num;
if ( ( argc != 2) || (**(argv+1) == '-' ) ) {
usage ("chvt N\n\nChange foreground virtual terminal to /dev/ttyN\n");
}
fd = get_console_fd("/dev/console");
num = atoi(argv[1]);
if (ioctl(fd,VT_ACTIVATE,num)) {
perror("VT_ACTIVATE");
exit(FALSE);
}
if (ioctl(fd,VT_WAITACTIVE,num)) {
perror("VT_WAITACTIVE");
exit(FALSE);
}
exit( TRUE);
if ((argc != 2) || (**(argv + 1) == '-')) {
usage
("chvt N\n\nChange foreground virtual terminal to /dev/ttyN\n");
}
fd = get_console_fd("/dev/console");
num = atoi(argv[1]);
if (ioctl(fd, VT_ACTIVATE, num)) {
perror("VT_ACTIVATE");
exit(FALSE);
}
if (ioctl(fd, VT_WAITACTIVE, num)) {
perror("VT_WAITACTIVE");
exit(FALSE);
}
exit(TRUE);
}

View File

@ -1,3 +1,4 @@
/* vi: set sw=4 ts=4: */
/*
* Mini clear implementation for busybox
*
@ -25,9 +26,8 @@
#include <stdio.h>
extern int
clear_main(int argc, char** argv)
extern int clear_main(int argc, char **argv)
{
printf("\033[H\033[J");
exit( TRUE);
exit(TRUE);
}

View File

@ -1,3 +1,4 @@
/* vi: set sw=4 ts=4: */
/*
* disalloc.c - aeb - 940501 - Disallocate virtual terminal(s)
* Renamed deallocvt.
@ -13,38 +14,39 @@
extern int getfd(void);
char *progname;
int
deallocvt_main(int argc, char *argv[]) {
int fd, num, i;
int deallocvt_main(int argc, char *argv[])
{
int fd, num, i;
if ( ( argc != 2) || (**(argv+1) == '-' ) ) {
usage ("deallocvt N\n\nDeallocate unused virtual terminal /dev/ttyN\n");
}
progname = argv[0];
fd = get_console_fd("/dev/console");
if (argc == 1) {
/* deallocate all unused consoles */
if (ioctl(fd,VT_DISALLOCATE,0)) {
perror("VT_DISALLOCATE");
exit(1);
if ((argc != 2) || (**(argv + 1) == '-')) {
usage
("deallocvt N\n\nDeallocate unused virtual terminal /dev/ttyN\n");
}
} else
for (i = 1; i < argc; i++) {
num = atoi(argv[i]);
if (num == 0)
fprintf(stderr, "%s: 0: illegal VT number\n", progname);
else if (num == 1)
fprintf(stderr, "%s: VT 1 cannot be deallocated\n", progname);
else
if (ioctl(fd,VT_DISALLOCATE,num)) {
perror("VT_DISALLOCATE");
fprintf(stderr, "%s: could not deallocate console %d\n",
progname, num);
exit(1);
}
}
exit(0);
progname = argv[0];
fd = get_console_fd("/dev/console");
if (argc == 1) {
/* deallocate all unused consoles */
if (ioctl(fd, VT_DISALLOCATE, 0)) {
perror("VT_DISALLOCATE");
exit(1);
}
} else
for (i = 1; i < argc; i++) {
num = atoi(argv[i]);
if (num == 0)
fprintf(stderr, "%s: 0: illegal VT number\n", progname);
else if (num == 1)
fprintf(stderr, "%s: VT 1 cannot be deallocated\n",
progname);
else if (ioctl(fd, VT_DISALLOCATE, num)) {
perror("VT_DISALLOCATE");
fprintf(stderr, "%s: could not deallocate console %d\n",
progname, num);
exit(1);
}
}
exit(0);
}

View File

@ -1,3 +1,4 @@
/* vi: set sw=4 ts=4: */
/*
* Derived from
* mapscrn.c - version 0.92
@ -23,120 +24,115 @@
typedef unsigned short unicode;
static long int ctoi(unsigned char *s, int *is_unicode);
int old_screen_map_read_ascii(FILE *fp, unsigned char buf[]);
int uni_screen_map_read_ascii(FILE *fp, unicode buf[], int* is_unicode);
unicode utf8_to_ucs2 (char* buf);
int screen_map_load(int fd, FILE *fp);
int old_screen_map_read_ascii(FILE * fp, unsigned char buf[]);
int uni_screen_map_read_ascii(FILE * fp, unicode buf[], int *is_unicode);
unicode utf8_to_ucs2(char *buf);
int screen_map_load(int fd, FILE * fp);
int loadacm_main(int argc, char **argv)
{
int fd;
fd = open("/dev/tty", O_RDWR);
if (fd < 0) {
fprintf(stderr, "Error opening /dev/tty1: %s\n", strerror(errno));
return 1;
}
if (screen_map_load(fd, stdin))
{
fprintf(stderr, "Error loading acm: %s\n", strerror(errno));
return 1;
}
write(fd, "\033(K", 3);
return 0;
int fd;
fd = open("/dev/tty", O_RDWR);
if (fd < 0) {
fprintf(stderr, "Error opening /dev/tty1: %s\n", strerror(errno));
return 1;
}
if (screen_map_load(fd, stdin)) {
fprintf(stderr, "Error loading acm: %s\n", strerror(errno));
return 1;
}
write(fd, "\033(K", 3);
return 0;
}
int screen_map_load(int fd, FILE *fp)
int screen_map_load(int fd, FILE * fp)
{
struct stat stbuf;
unicode wbuf[E_TABSZ];
unsigned char buf[E_TABSZ];
int parse_failed = 0;
int is_unicode;
struct stat stbuf;
unicode wbuf[E_TABSZ];
unsigned char buf[E_TABSZ];
int parse_failed = 0;
int is_unicode;
if (fstat(fp->_fileno, &stbuf))
perror("Cannot stat map file"), exit(1);
if (fstat(fp->_fileno, &stbuf))
perror("Cannot stat map file"), exit(1);
/* first try a UTF screen-map: either ASCII (no restriction) or binary (regular file) */
if (!(parse_failed = (-1 == uni_screen_map_read_ascii(fp,wbuf,&is_unicode))) ||
(S_ISREG(stbuf.st_mode) &&
(stbuf.st_size == (sizeof(unicode) * E_TABSZ)))) /* test for binary UTF map by size */
{
if (parse_failed)
{
if (-1 == fseek (fp, 0, SEEK_SET))
{
if (errno == ESPIPE)
fprintf (stderr, "16bit screen-map MUST be a regular file.\n"), exit (1);
else
perror ("fseek failed reading binary 16bit screen-map"), exit (1);
}
if (fread(wbuf, sizeof(unicode) * E_TABSZ, 1, fp) != 1)
perror("Cannot read [new] map from file"), exit(1);
/* first try a UTF screen-map: either ASCII (no restriction) or binary (regular file) */
if (!
(parse_failed =
(-1 == uni_screen_map_read_ascii(fp, wbuf, &is_unicode)))
|| (S_ISREG(stbuf.st_mode) && (stbuf.st_size == (sizeof(unicode) * E_TABSZ)))) { /* test for binary UTF map by size */
if (parse_failed) {
if (-1 == fseek(fp, 0, SEEK_SET)) {
if (errno == ESPIPE)
fprintf(stderr,
"16bit screen-map MUST be a regular file.\n"),
exit(1);
else
perror("fseek failed reading binary 16bit screen-map"),
exit(1);
}
if (fread(wbuf, sizeof(unicode) * E_TABSZ, 1, fp) != 1)
perror("Cannot read [new] map from file"), exit(1);
#if 0
else
fprintf(stderr, "Input screen-map is binary.\n");
else
fprintf(stderr, "Input screen-map is binary.\n");
#endif
}
/* if it was effectively a 16-bit ASCII, OK, else try to read as 8-bit map */
/* same if it was binary, ie. if parse_failed */
if (parse_failed || is_unicode) {
if (ioctl(fd, PIO_UNISCRNMAP, wbuf))
perror("PIO_UNISCRNMAP ioctl"), exit(1);
else
return 0;
}
}
/* if it was effectively a 16-bit ASCII, OK, else try to read as 8-bit map */
/* same if it was binary, ie. if parse_failed */
if (parse_failed || is_unicode)
{
if (ioctl(fd,PIO_UNISCRNMAP,wbuf))
perror("PIO_UNISCRNMAP ioctl"), exit(1);
else
return 0;
/* rewind... */
if (-1 == fseek(fp, 0, SEEK_SET)) {
if (errno == ESPIPE)
fprintf(stderr,
"Assuming 8bit screen-map - MUST be a regular file.\n"),
exit(1);
else
perror("fseek failed assuming 8bit screen-map"), exit(1);
}
}
/* rewind... */
if (-1 == fseek (fp, 0, SEEK_SET))
{
if (errno == ESPIPE)
fprintf (stderr, "Assuming 8bit screen-map - MUST be a regular file.\n"), exit (1);
else
perror ("fseek failed assuming 8bit screen-map"), exit (1);
}
/* ... and try an old 8-bit screen-map */
if (!(parse_failed = (-1 == old_screen_map_read_ascii(fp,buf))) ||
(S_ISREG(stbuf.st_mode) &&
(stbuf.st_size == E_TABSZ))) /* test for binary old 8-bit map by size */
{
if (parse_failed)
{
if (-1 == fseek (fp, 0, SEEK_SET))
{
if (errno == ESPIPE)
/* should not - it succedeed above */
fprintf (stderr, "fseek() returned ESPIPE !\n"), exit (1);
else
perror ("fseek for binary 8bit screen-map"), exit (1);
}
if (fread(buf,E_TABSZ,1,fp) != 1)
perror("Cannot read [old] map from file"), exit(1);
/* ... and try an old 8-bit screen-map */
if (!(parse_failed = (-1 == old_screen_map_read_ascii(fp, buf))) ||
(S_ISREG(stbuf.st_mode) && (stbuf.st_size == E_TABSZ))) { /* test for binary old 8-bit map by size */
if (parse_failed) {
if (-1 == fseek(fp, 0, SEEK_SET)) {
if (errno == ESPIPE)
/* should not - it succedeed above */
fprintf(stderr, "fseek() returned ESPIPE !\n"),
exit(1);
else
perror("fseek for binary 8bit screen-map"), exit(1);
}
if (fread(buf, E_TABSZ, 1, fp) != 1)
perror("Cannot read [old] map from file"), exit(1);
#if 0
else
fprintf(stderr, "Input screen-map is binary.\n");
else
fprintf(stderr, "Input screen-map is binary.\n");
#endif
}
if (ioctl(fd, PIO_SCRNMAP, buf))
perror("PIO_SCRNMAP ioctl"), exit(1);
else
return 0;
} else {
fprintf(stderr, "Error parsing symbolic map\n");
exit(1);
}
if (ioctl(fd,PIO_SCRNMAP,buf))
perror("PIO_SCRNMAP ioctl"), exit(1);
else
return 0;
}
else
{
fprintf(stderr, "Error parsing symbolic map\n");
exit(1);
}
}
@ -149,116 +145,111 @@ int screen_map_load(int fd, FILE *fp)
*
* FIXME: ignores everything after second word
*/
int uni_screen_map_read_ascii(FILE *fp, unicode buf[], int *is_unicode)
int uni_screen_map_read_ascii(FILE * fp, unicode buf[], int *is_unicode)
{
char buffer[256]; /* line buffer reading file */
char *p, *q; /* 1st + 2nd words in line */
int in, on; /* the same, as numbers */
int tmp_is_unicode; /* tmp for is_unicode calculation */
int i; /* loop index - result holder */
int ret_code = 0; /* return code */
sigset_t sigset, old_sigset;
assert (is_unicode);
*is_unicode = 0;
/* first 128 codes defaults to ASCII */
for (i=0; i<128; i++) buf[i] = i;
/* remaining defaults to replacement char (usually E_TABSZ = 256) */
for ( ; i<E_TABSZ; i++) buf[i] = 0xfffd;
/* block SIGCHLD */
sigemptyset (&sigset);
sigaddset (&sigset, SIGCHLD);
sigprocmask (SIG_BLOCK, &sigset, &old_sigset);
char buffer[256]; /* line buffer reading file */
char *p, *q; /* 1st + 2nd words in line */
int in, on; /* the same, as numbers */
int tmp_is_unicode; /* tmp for is_unicode calculation */
int i; /* loop index - result holder */
int ret_code = 0; /* return code */
sigset_t sigset, old_sigset;
do
{
if (NULL == fgets(buffer, sizeof(buffer),fp))
{
if (feof (fp))
break;
else
{
perror ("uni_screen_map_read_ascii() can't read line");
exit (2);
}
assert(is_unicode);
*is_unicode = 0;
/* first 128 codes defaults to ASCII */
for (i = 0; i < 128; i++)
buf[i] = i;
/* remaining defaults to replacement char (usually E_TABSZ = 256) */
for (; i < E_TABSZ; i++)
buf[i] = 0xfffd;
/* block SIGCHLD */
sigemptyset(&sigset);
sigaddset(&sigset, SIGCHLD);
sigprocmask(SIG_BLOCK, &sigset, &old_sigset);
do {
if (NULL == fgets(buffer, sizeof(buffer), fp)) {
if (feof(fp))
break;
else {
perror("uni_screen_map_read_ascii() can't read line");
exit(2);
}
}
/* get "charset-relative charcode", stripping leading spaces */
p = strtok(buffer, " \t\n");
/* skip empty lines and comments */
if (!p || *p == '#')
continue;
/* get unicode mapping */
q = strtok(NULL, " \t\n");
if (q) {
in = ctoi(p, NULL);
if (in < 0 || in > 255) {
ret_code = -1;
break;
}
on = ctoi(q, &tmp_is_unicode);
if (in < 0 && on > 65535) {
ret_code = -1;
break;
}
*is_unicode |= tmp_is_unicode;
buf[in] = on;
} else {
ret_code = -1;
break;
}
}
/* get "charset-relative charcode", stripping leading spaces */
p = strtok(buffer," \t\n");
while (1); /* terminated by break on feof() */
/* skip empty lines and comments */
if (!p || *p == '#')
continue;
/* restore sig mask */
sigprocmask(SIG_SETMASK, &old_sigset, NULL);
/* get unicode mapping */
q = strtok(NULL," \t\n");
if (q)
{
in = ctoi(p, NULL);
if (in < 0 || in > 255)
{
ret_code = -1;
break;
}
on = ctoi(q, &tmp_is_unicode);
if (in < 0 && on > 65535)
{
ret_code = -1;
break;
}
*is_unicode |= tmp_is_unicode;
buf[in] = on;
}
else
{
ret_code = -1;
break;
}
}
while (1); /* terminated by break on feof() */
/* restore sig mask */
sigprocmask (SIG_SETMASK, &old_sigset, NULL);
return ret_code;
return ret_code;
}
int old_screen_map_read_ascii(FILE *fp, unsigned char buf[])
int old_screen_map_read_ascii(FILE * fp, unsigned char buf[])
{
char buffer[256];
int in, on;
char *p, *q;
for (in=0; in<256; in++) buf[in]=in;
while (fgets(buffer,sizeof(buffer)-1,fp))
{
p = strtok(buffer," \t\n");
if (!p || *p == '#')
continue;
char buffer[256];
int in, on;
char *p, *q;
q = strtok(NULL," \t\n#");
if (q)
{
in = ctoi(p, NULL);
if (in < 0 || in > 255) return -1;
on = ctoi(q, NULL);
if (in < 0 && on > 255) return -1;
buf[in] = on;
for (in = 0; in < 256; in++)
buf[in] = in;
while (fgets(buffer, sizeof(buffer) - 1, fp)) {
p = strtok(buffer, " \t\n");
if (!p || *p == '#')
continue;
q = strtok(NULL, " \t\n#");
if (q) {
in = ctoi(p, NULL);
if (in < 0 || in > 255)
return -1;
on = ctoi(q, NULL);
if (in < 0 && on > 255)
return -1;
buf[in] = on;
} else
return -1;
}
else return -1;
}
return(0);
return (0);
}
@ -270,172 +261,145 @@ int old_screen_map_read_ascii(FILE *fp, unsigned char buf[])
*
* CAVEAT: will report valid UTF mappings using only 1 byte as 8-bit ones.
*/
long int ctoi(unsigned char *s, int *is_unicode)
long int ctoi(unsigned char *s, int *is_unicode)
{
int i;
size_t ls;
ls = strlen(s);
if (is_unicode) *is_unicode = 0;
/* hex-specified UCS2 */
if ((strncmp(s,"U+",2) == 0) &&
(strspn(s+2,"0123456789abcdefABCDEF") == ls-2))
{
sscanf(s+2,"%x",&i);
if (is_unicode) *is_unicode = 1;
}
int i;
size_t ls;
/* hex-specified byte */
else if ((ls <= 4) && (strncmp(s,"0x",2) == 0) &&
(strspn(s+2,"0123456789abcdefABCDEF") == ls-2))
sscanf(s+2,"%x",&i);
ls = strlen(s);
if (is_unicode)
*is_unicode = 0;
/* oct-specified number (byte) */
else if ((*s == '0') &&
(strspn(s,"01234567") == ls))
sscanf(s,"%o",&i);
/* dec-specified number (byte) */
else if (strspn(s,"0123456789") == ls)
sscanf(s,"%d",&i);
/* single-byte quoted char */
else if ((strlen(s) == 3) && (s[0] == '\'') && (s[2] == '\''))
i=s[1];
/* multi-byte UTF8 quoted char */
else if ((s[0] == '\'') && (s[ls-1] == '\''))
{
s[ls-1] = 0; /* ensure we'll not "parse UTF too far" */
i = utf8_to_ucs2(s+1);
if (is_unicode) *is_unicode = 1;
}
else
return(-1);
return(i);
/* hex-specified UCS2 */
if ((strncmp(s, "U+", 2) == 0) &&
(strspn(s + 2, "0123456789abcdefABCDEF") == ls - 2)) {
sscanf(s + 2, "%x", &i);
if (is_unicode)
*is_unicode = 1;
}
/* hex-specified byte */
else if ((ls <= 4) && (strncmp(s, "0x", 2) == 0) &&
(strspn(s + 2, "0123456789abcdefABCDEF") == ls - 2))
sscanf(s + 2, "%x", &i);
/* oct-specified number (byte) */
else if ((*s == '0') && (strspn(s, "01234567") == ls))
sscanf(s, "%o", &i);
/* dec-specified number (byte) */
else if (strspn(s, "0123456789") == ls)
sscanf(s, "%d", &i);
/* single-byte quoted char */
else if ((strlen(s) == 3) && (s[0] == '\'') && (s[2] == '\''))
i = s[1];
/* multi-byte UTF8 quoted char */
else if ((s[0] == '\'') && (s[ls - 1] == '\'')) {
s[ls - 1] = 0; /* ensure we'll not "parse UTF too far" */
i = utf8_to_ucs2(s + 1);
if (is_unicode)
*is_unicode = 1;
} else
return (-1);
return (i);
}
void saveoldmap(int fd, char *omfil)
void saveoldmap(int fd, char *omfil)
{
FILE *fp;
char buf[E_TABSZ];
#ifdef GIO_UNISCRNMAP
unicode xbuf[E_TABSZ];
int is_old_map = 0;
if (ioctl(fd,GIO_UNISCRNMAP,xbuf))
{
perror("GIO_UNISCRNMAP ioctl error");
#endif
if (ioctl(fd,GIO_SCRNMAP,buf))
{
perror("GIO_SCRNMAP ioctl error");
exit(1);
}
else
is_old_map = 1;
#ifdef GIO_UNISCRNMAP
}
#endif
if ((fp = fopen(omfil, "w")) == NULL)
{
perror(omfil);
exit(1);
}
FILE *fp;
char buf[E_TABSZ];
#ifdef GIO_UNISCRNMAP
if (is_old_map)
{
unicode xbuf[E_TABSZ];
int is_old_map = 0;
if (ioctl(fd, GIO_UNISCRNMAP, xbuf)) {
perror("GIO_UNISCRNMAP ioctl error");
#endif
if (fwrite(buf,E_TABSZ,1,fp) != 1)
{
perror("Error writing map to file");
exit(1);
if (ioctl(fd, GIO_SCRNMAP, buf)) {
perror("GIO_SCRNMAP ioctl error");
exit(1);
} else
is_old_map = 1;
#ifdef GIO_UNISCRNMAP
}
#endif
if ((fp = fopen(omfil, "w")) == NULL) {
perror(omfil);
exit(1);
}
#ifdef GIO_UNISCRNMAP
}
else
if (fwrite(xbuf, sizeof(unicode) * E_TABSZ,1,fp) != 1)
{
perror("Error writing map to file");
exit(1);
if (is_old_map) {
#endif
if (fwrite(buf, E_TABSZ, 1, fp) != 1) {
perror("Error writing map to file");
exit(1);
}
#ifdef GIO_UNISCRNMAP
} else if (fwrite(xbuf, sizeof(unicode) * E_TABSZ, 1, fp) != 1) {
perror("Error writing map to file");
exit(1);
}
#endif
fclose(fp);
fclose(fp);
}
unicode utf8_to_ucs2 (char* buf)
unicode utf8_to_ucs2(char *buf)
{
int utf_count = 0;
long utf_char;
unicode tc;
unsigned char c;
int utf_count = 0;
long utf_char;
unicode tc;
unsigned char c;
do
{
c = *buf;
buf++;
do {
c = *buf;
buf++;
/* if byte should be part of multi-byte sequence */
if(c & 0x80)
{
/* if we have already started to parse a UTF8 sequence */
if (utf_count > 0 && (c & 0xc0) == 0x80)
{
utf_char = (utf_char << 6) | (c & 0x3f);
utf_count--;
if (utf_count == 0)
tc = utf_char;
else
continue;
}
else /* Possibly 1st char of a UTF8 sequence */
{
if ((c & 0xe0) == 0xc0)
{
utf_count = 1;
utf_char = (c & 0x1f);
}
else if ((c & 0xf0) == 0xe0)
{
utf_count = 2;
utf_char = (c & 0x0f);
}
else if ((c & 0xf8) == 0xf0)
{
utf_count = 3;
utf_char = (c & 0x07);
}
else if ((c & 0xfc) == 0xf8)
{
utf_count = 4;
utf_char = (c & 0x03);
}
else if ((c & 0xfe) == 0xfc)
{
utf_count = 5;
utf_char = (c & 0x01);
}
else
utf_count = 0;
continue;
}
}
else /* not part of multi-byte sequence - treat as ASCII
* this makes incomplete sequences to be ignored
*/
{
tc = c;
utf_count = 0;
}
}
while (utf_count);
/* if byte should be part of multi-byte sequence */
if (c & 0x80) {
/* if we have already started to parse a UTF8 sequence */
if (utf_count > 0 && (c & 0xc0) == 0x80) {
utf_char = (utf_char << 6) | (c & 0x3f);
utf_count--;
if (utf_count == 0)
tc = utf_char;
else
continue;
} else { /* Possibly 1st char of a UTF8 sequence */
return tc;
if ((c & 0xe0) == 0xc0) {
utf_count = 1;
utf_char = (c & 0x1f);
} else if ((c & 0xf0) == 0xe0) {
utf_count = 2;
utf_char = (c & 0x0f);
} else if ((c & 0xf8) == 0xf0) {
utf_count = 3;
utf_char = (c & 0x07);
} else if ((c & 0xfc) == 0xf8) {
utf_count = 4;
utf_char = (c & 0x03);
} else if ((c & 0xfe) == 0xfc) {
utf_count = 5;
utf_char = (c & 0x01);
} else
utf_count = 0;
continue;
}
} else { /* not part of multi-byte sequence - treat as ASCII
* this makes incomplete sequences to be ignored
*/
tc = c;
utf_count = 0;
}
}
while (utf_count);
return tc;
}

View File

@ -1,3 +1,4 @@
/* vi: set sw=4 ts=4: */
/*
* loadfont.c - Eugene Crosser & Andries Brouwer
*
@ -30,72 +31,69 @@
#define PSF_SEPARATOR 0xFFFF
static const char loadfont_usage[] = "loadfont\n"
"\n"
"\tLoad a console font from standard input.\n"
"\n";
"\n" "\tLoad a console font from standard input.\n" "\n";
struct psf_header
{
unsigned char magic1, magic2; /* Magic number */
unsigned char mode; /* PSF font mode */
unsigned char charsize; /* Character size */
struct psf_header {
unsigned char magic1, magic2; /* Magic number */
unsigned char mode; /* PSF font mode */
unsigned char charsize; /* Character size */
};
#define PSF_MAGIC_OK(x) ((x).magic1 == PSF_MAGIC1 && (x).magic2 == PSF_MAGIC2)
static void loadnewfont(int fd);
extern int
loadfont_main(int argc, char **argv)
extern int loadfont_main(int argc, char **argv)
{
int fd;
fd = open("/dev/tty0", O_RDWR);
if (fd < 0) {
fprintf(stderr, "Error opening /dev/tty0: %s\n", strerror(errno));
return 1;
fprintf(stderr, "Error opening /dev/tty0: %s\n", strerror(errno));
return 1;
}
loadnewfont(fd);
return 0;
}
static void
do_loadfont(int fd, char *inbuf, int unit, int fontsize) {
static void do_loadfont(int fd, char *inbuf, int unit, int fontsize)
{
char buf[16384];
int i;
memset(buf,0,sizeof(buf));
memset(buf, 0, sizeof(buf));
if (unit < 1 || unit > 32) {
fprintf(stderr, "Bad character size %d\n", unit);
exit(1);
fprintf(stderr, "Bad character size %d\n", unit);
exit(1);
}
for (i = 0; i < fontsize; i++)
memcpy(buf+(32*i), inbuf+(unit*i), unit);
memcpy(buf + (32 * i), inbuf + (unit * i), unit);
#if defined( PIO_FONTX ) && !defined( __sparc__ )
{
struct consolefontdesc cfd;
struct consolefontdesc cfd;
cfd.charcount = fontsize;
cfd.charheight = unit;
cfd.chardata = buf;
cfd.charcount = fontsize;
cfd.charheight = unit;
cfd.chardata = buf;
if (ioctl(fd, PIO_FONTX, &cfd) == 0)
return; /* success */
perror("PIO_FONTX ioctl error (trying PIO_FONT)");
if (ioctl(fd, PIO_FONTX, &cfd) == 0)
return; /* success */
perror("PIO_FONTX ioctl error (trying PIO_FONT)");
}
#endif
if (ioctl(fd, PIO_FONT, buf)) {
perror("PIO_FONT ioctl error");
exit(1);
perror("PIO_FONT ioctl error");
exit(1);
}
}
static void
do_loadtable(int fd, unsigned char *inbuf, int tailsz, int fontsize) {
do_loadtable(int fd, unsigned char *inbuf, int tailsz, int fontsize)
{
struct unimapinit advice;
struct unimapdesc ud;
struct unipair *up;
@ -103,23 +101,24 @@ do_loadtable(int fd, unsigned char *inbuf, int tailsz, int fontsize) {
int glyph;
u_short unicode;
maxct = tailsz; /* more than enough */
maxct = tailsz; /* more than enough */
up = (struct unipair *) malloc(maxct * sizeof(struct unipair));
if (!up) {
fprintf(stderr, "Out of memory?\n");
exit(1);
fprintf(stderr, "Out of memory?\n");
exit(1);
}
for (glyph = 0; glyph < fontsize; glyph++) {
while (tailsz >= 2) {
unicode = (((u_short) inbuf[1]) << 8) + inbuf[0];
tailsz -= 2;
inbuf += 2;
if (unicode == PSF_SEPARATOR)
break;
up[ct].unicode = unicode;
up[ct].fontpos = glyph;
ct++;
}
while (tailsz >= 2) {
unicode = (((u_short) inbuf[1]) << 8) + inbuf[0];
tailsz -= 2;
inbuf += 2;
if (unicode == PSF_SEPARATOR)
break;
up[ct].unicode = unicode;
up[ct].fontpos = glyph;
ct++;
}
}
/* Note: after PIO_UNIMAPCLR and before PIO_UNIMAP
@ -128,33 +127,33 @@ do_loadtable(int fd, unsigned char *inbuf, int tailsz, int fontsize) {
advice.advised_hashsize = 0;
advice.advised_hashstep = 0;
advice.advised_hashlevel = 0;
if(ioctl(fd, PIO_UNIMAPCLR, &advice)) {
if (ioctl(fd, PIO_UNIMAPCLR, &advice)) {
#ifdef ENOIOCTLCMD
if (errno == ENOIOCTLCMD) {
fprintf(stderr, "It seems this kernel is older than 1.1.92\n");
fprintf(stderr, "No Unicode mapping table loaded.\n");
} else
if (errno == ENOIOCTLCMD) {
fprintf(stderr, "It seems this kernel is older than 1.1.92\n");
fprintf(stderr, "No Unicode mapping table loaded.\n");
} else
#endif
perror("PIO_UNIMAPCLR");
exit(1);
perror("PIO_UNIMAPCLR");
exit(1);
}
ud.entry_ct = ct;
ud.entries = up;
if(ioctl(fd, PIO_UNIMAP, &ud)) {
if (ioctl(fd, PIO_UNIMAP, &ud)) {
#if 0
if (errno == ENOMEM) {
/* change advice parameters */
}
if (errno == ENOMEM) {
/* change advice parameters */
}
#endif
perror("PIO_UNIMAP");
exit(1);
perror("PIO_UNIMAP");
exit(1);
}
}
static void
loadnewfont(int fd) {
static void loadnewfont(int fd)
{
int unit;
char inbuf[32768]; /* primitive */
char inbuf[32768]; /* primitive */
int inputlth, offset;
/*
@ -178,57 +177,58 @@ loadnewfont(int fd) {
/* test for psf first */
{
struct psf_header psfhdr;
int fontsize;
int hastable;
int head0, head;
struct psf_header psfhdr;
int fontsize;
int hastable;
int head0, head;
if (inputlth < sizeof(struct psf_header))
goto no_psf;
if (inputlth < sizeof(struct psf_header))
goto no_psf;
psfhdr = * (struct psf_header *) &inbuf[0];
psfhdr = *(struct psf_header *) &inbuf[0];
if (!PSF_MAGIC_OK(psfhdr))
goto no_psf;
if (!PSF_MAGIC_OK(psfhdr))
goto no_psf;
if (psfhdr.mode > PSF_MAXMODE) {
fprintf(stderr, "Unsupported psf file mode\n");
exit(1);
}
fontsize = ((psfhdr.mode & PSF_MODE512) ? 512 : 256);
if (psfhdr.mode > PSF_MAXMODE) {
fprintf(stderr, "Unsupported psf file mode\n");
exit(1);
}
fontsize = ((psfhdr.mode & PSF_MODE512) ? 512 : 256);
#if !defined( PIO_FONTX ) || defined( __sparc__ )
if (fontsize != 256) {
fprintf(stderr, "Only fontsize 256 supported\n");
exit(1);
}
if (fontsize != 256) {
fprintf(stderr, "Only fontsize 256 supported\n");
exit(1);
}
#endif
hastable = (psfhdr.mode & PSF_MODEHASTAB);
unit = psfhdr.charsize;
head0 = sizeof(struct psf_header);
head = head0 + fontsize*unit;
if (head > inputlth || (!hastable && head != inputlth)) {
fprintf(stderr, "Input file: bad length\n");
exit(1);
}
do_loadfont(fd, inbuf + head0, unit, fontsize);
if (hastable)
do_loadtable(fd, inbuf + head, inputlth-head, fontsize);
return;
hastable = (psfhdr.mode & PSF_MODEHASTAB);
unit = psfhdr.charsize;
head0 = sizeof(struct psf_header);
head = head0 + fontsize * unit;
if (head > inputlth || (!hastable && head != inputlth)) {
fprintf(stderr, "Input file: bad length\n");
exit(1);
}
do_loadfont(fd, inbuf + head0, unit, fontsize);
if (hastable)
do_loadtable(fd, inbuf + head, inputlth - head, fontsize);
return;
}
no_psf:
no_psf:
/* file with three code pages? */
if (inputlth == 9780) {
offset = 40;
unit = 16;
offset = 40;
unit = 16;
} else {
/* bare font */
if (inputlth & 0377) {
fprintf(stderr, "Bad input file size\n");
exit(1);
}
offset = 0;
unit = inputlth/256;
/* bare font */
if (inputlth & 0377) {
fprintf(stderr, "Bad input file size\n");
exit(1);
}
offset = 0;
unit = inputlth / 256;
}
do_loadfont(fd, inbuf+offset, unit, 256);
do_loadfont(fd, inbuf + offset, unit, 256);
}

View File

@ -1,3 +1,4 @@
/* vi: set sw=4 ts=4: */
/*
* Mini loadkmap implementation for busybox
*
@ -29,61 +30,63 @@
static const char loadkmap_usage[] = "loadkmap\n"
"\n"
"\tLoad a binary keyboard translation table from standard input.\n"
"\n";
"\n"
"\tLoad a binary keyboard translation table from standard input.\n"
"\n";
int
loadkmap_main(int argc, char * * argv)
{
struct kbentry ke;
u_short *ibuff;
int i,j,fd,readsz,pos,ibuffsz=NR_KEYS * sizeof(u_short);
char flags[MAX_NR_KEYMAPS],magic[]="bkeymap",buff[7];
int loadkmap_main(int argc, char **argv)
{
struct kbentry ke;
u_short *ibuff;
int i, j, fd, readsz, pos, ibuffsz = NR_KEYS * sizeof(u_short);
char flags[MAX_NR_KEYMAPS], magic[] = "bkeymap", buff[7];
fd = open("/dev/tty0", O_RDWR);
if (fd < 0) {
fprintf(stderr, "Error opening /dev/tty0: %s\n", strerror(errno));
return 1;
}
read(0,buff,7);
if (0 != strncmp(buff,magic,7)) {
fprintf(stderr, "This is not a valid binary keymap.\n");
return 1;
}
if ( MAX_NR_KEYMAPS != read(0,flags,MAX_NR_KEYMAPS) ) {
fprintf(stderr, "Error reading keymap flags: %s\n", strerror(errno));
return 1;
}
ibuff=(u_short *) malloc(ibuffsz);
if (!ibuff) {
fprintf(stderr, "Out of memory.\n");
return 1;
}
for(i=0; i<MAX_NR_KEYMAPS; i++) {
if (flags[i]==1){
pos=0;
while (pos < ibuffsz) {
if ( (readsz = read(0,(char *)ibuff+pos,ibuffsz-pos)) < 0 ) {
fprintf(stderr, "Error reading keymap: %s\n",
strerror(errno));
return 1;
}
pos += readsz;
}
for(j=0; j<NR_KEYS; j++) {
ke.kb_index = j;
ke.kb_table = i;
ke.kb_value = ibuff[j];
ioctl(fd, KDSKBENT, &ke);
}
fd = open("/dev/tty0", O_RDWR);
if (fd < 0) {
fprintf(stderr, "Error opening /dev/tty0: %s\n", strerror(errno));
return 1;
}
}
close (fd);
return 0;
read(0, buff, 7);
if (0 != strncmp(buff, magic, 7)) {
fprintf(stderr, "This is not a valid binary keymap.\n");
return 1;
}
if (MAX_NR_KEYMAPS != read(0, flags, MAX_NR_KEYMAPS)) {
fprintf(stderr, "Error reading keymap flags: %s\n",
strerror(errno));
return 1;
}
ibuff = (u_short *) malloc(ibuffsz);
if (!ibuff) {
fprintf(stderr, "Out of memory.\n");
return 1;
}
for (i = 0; i < MAX_NR_KEYMAPS; i++) {
if (flags[i] == 1) {
pos = 0;
while (pos < ibuffsz) {
if ((readsz = read(0, (char *) ibuff + pos, ibuffsz - pos))
< 0) {
fprintf(stderr, "Error reading keymap: %s\n",
strerror(errno));
return 1;
}
pos += readsz;
}
for (j = 0; j < NR_KEYS; j++) {
ke.kb_index = j;
ke.kb_table = i;
ke.kb_value = ibuff[j];
ioctl(fd, KDSKBENT, &ke);
}
}
}
close(fd);
return 0;
}

View File

@ -1,3 +1,4 @@
/* vi: set sw=4 ts=4: */
/*
* Mini Cat implementation for busybox
*
@ -24,36 +25,37 @@
#include <stdio.h>
static void print_file( FILE *file)
static void print_file(FILE * file)
{
int c;
while ((c = getc(file)) != EOF)
putc(c, stdout);
fclose(file);
fflush(stdout);
int c;
while ((c = getc(file)) != EOF)
putc(c, stdout);
fclose(file);
fflush(stdout);
}
extern int cat_main(int argc, char **argv)
{
FILE *file;
FILE *file;
if (argc==1) {
print_file( stdin);
exit( TRUE);
}
if ( **(argv+1) == '-' ) {
usage ("cat [file ...]\n");
}
argc--;
while (argc-- > 0 && *(argv++) != '\0' && strlen(*argv) ) {
file = fopen(*argv, "r");
if (file == NULL) {
perror(*argv);
exit(FALSE);
if (argc == 1) {
print_file(stdin);
exit(TRUE);
}
print_file( file);
}
exit(TRUE);
if (**(argv + 1) == '-') {
usage("cat [file ...]\n");
}
argc--;
while (argc-- > 0 && *(argv++) != '\0' && strlen(*argv)) {
file = fopen(*argv, "r");
if (file == NULL) {
perror(*argv);
exit(FALSE);
}
print_file(file);
}
exit(TRUE);
}

View File

@ -1,3 +1,4 @@
/* vi: set sw=4 ts=4: */
/*
* Mini chroot implementation for busybox
*
@ -28,39 +29,39 @@
static const char chroot_usage[] = "chroot NEWROOT [COMMAND...]\n\n"
"Run COMMAND with root directory set to NEWROOT.\n";
"Run COMMAND with root directory set to NEWROOT.\n";
int chroot_main(int argc, char **argv)
{
if ( (argc < 2) || (**(argv+1) == '-') ) {
usage( chroot_usage);
}
argc--;
argv++;
if ((argc < 2) || (**(argv + 1) == '-')) {
usage(chroot_usage);
}
argc--;
argv++;
if (chroot (*argv) || (chdir ("/"))) {
fprintf(stderr, "chroot: cannot change root directory to %s: %s\n",
*argv, strerror(errno));
exit( FALSE);
}
if (chroot(*argv) || (chdir("/"))) {
fprintf(stderr, "chroot: cannot change root directory to %s: %s\n",
*argv, strerror(errno));
exit(FALSE);
}
argc--;
argv++;
if (argc >= 1) {
fprintf(stderr, "command: %s\n", *argv);
execvp (*argv, argv);
}
else {
char *prog;
prog = getenv ("SHELL");
if (!prog)
prog = "/bin/sh";
execlp (prog, prog, NULL);
}
fprintf(stderr, "chroot: cannot execute %s: %s\n",
*argv, strerror(errno));
exit( FALSE);
argc--;
argv++;
if (argc >= 1) {
fprintf(stderr, "command: %s\n", *argv);
execvp(*argv, argv);
} else {
char *prog;
prog = getenv("SHELL");
if (!prog)
prog = "/bin/sh";
execlp(prog, prog, NULL);
}
fprintf(stderr, "chroot: cannot execute %s: %s\n",
*argv, strerror(errno));
exit(FALSE);
}

View File

@ -1,3 +1,4 @@
/* vi: set sw=4 ts=4: */
/*
* Mini date implementation for busybox
*
@ -38,12 +39,13 @@
an RFC 822 complient date output for shell scripting
mail commands */
static const char date_usage[] = "date [OPTION]... [+FORMAT]\n"
" or: date [OPTION] [MMDDhhmm[[CC]YY][.ss]]\n\n"
"Display the current time in the given FORMAT, or set the system date.\n"
"\nOptions:\n\t-R\t\toutput RFC-822 compliant date string\n"
"\t-s\t\tset time described by STRING\n"
"\t-u\t\tprint or set Coordinated Universal Time\n";
static const char date_usage[] = "date [OPTION]... [+FORMAT]\n"
" or: date [OPTION] [MMDDhhmm[[CC]YY][.ss]]\n\n"
"Display the current time in the given FORMAT, or set the system date.\n"
"\nOptions:\n\t-R\t\toutput RFC-822 compliant date string\n"
"\t-s\t\tset time described by STRING\n"
"\t-u\t\tprint or set Coordinated Universal Time\n";
/* Input parsing code is always bulky - used heavy duty libc stuff as
@ -51,240 +53,233 @@ static const char date_usage[] = "date [OPTION]... [+FORMAT]\n"
/* Default input handling to save suprising some people */
struct tm *
date_conv_time(struct tm *tm_time, const char *t_string) {
int nr;
struct tm *date_conv_time(struct tm *tm_time, const char *t_string)
{
int nr;
nr = sscanf(t_string, "%2d%2d%2d%2d%d",
&(tm_time->tm_mon),
&(tm_time->tm_mday),
&(tm_time->tm_hour),
&(tm_time->tm_min),
&(tm_time->tm_year));
nr = sscanf(t_string, "%2d%2d%2d%2d%d",
&(tm_time->tm_mon),
&(tm_time->tm_mday),
&(tm_time->tm_hour),
&(tm_time->tm_min), &(tm_time->tm_year));
if(nr < 4 || nr > 5) {
fprintf(stderr, invalid_date, "date", t_string);
exit( FALSE);
}
if (nr < 4 || nr > 5) {
fprintf(stderr, invalid_date, "date", t_string);
exit(FALSE);
}
/* correct for century - minor Y2K problem here? */
if(tm_time->tm_year >= 1900)
tm_time->tm_year -= 1900;
/* adjust date */
tm_time->tm_mon -= 1;
return(tm_time);
/* correct for century - minor Y2K problem here? */
if (tm_time->tm_year >= 1900)
tm_time->tm_year -= 1900;
/* adjust date */
tm_time->tm_mon -= 1;
return (tm_time);
}
/* The new stuff for LRP */
struct tm *
date_conv_ftime(struct tm *tm_time, const char *t_string) {
struct tm itm_time, jtm_time, ktm_time, \
ltm_time, mtm_time, ntm_time;
itm_time = *tm_time;
jtm_time = *tm_time;
ktm_time = *tm_time;
ltm_time = *tm_time;
mtm_time = *tm_time;
ntm_time = *tm_time;
/* Parse input and assign appropriately to tm_time */
if(sscanf(t_string, "%d:%d:%d",
&itm_time.tm_hour,
&itm_time.tm_min,
&itm_time.tm_sec) == 3 ) {
*tm_time = itm_time;
return(tm_time);
} else if (sscanf(t_string, "%d:%d",
&jtm_time.tm_hour,
&jtm_time.tm_min) == 2) {
*tm_time = jtm_time;
return(tm_time);
} else if (sscanf(t_string, "%d.%d-%d:%d:%d",
&ktm_time.tm_mon,
&ktm_time.tm_mday,
&ktm_time.tm_hour,
&ktm_time.tm_min,
&ktm_time.tm_sec) == 5) {
ktm_time.tm_mon -= 1; /* Adjust dates from 1-12 to 0-11 */
*tm_time = ktm_time;
return(tm_time);
} else if (sscanf(t_string, "%d.%d-%d:%d",
&ltm_time.tm_mon,
&ltm_time.tm_mday,
&ltm_time.tm_hour,
&ltm_time.tm_min) == 4) {
ltm_time.tm_mon -= 1; /* Adjust dates from 1-12 to 0-11 */
*tm_time = ltm_time;
return(tm_time);
} else if (sscanf(t_string, "%d.%d.%d-%d:%d:%d",
&mtm_time.tm_year,
&mtm_time.tm_mon,
&mtm_time.tm_mday,
&mtm_time.tm_hour,
&mtm_time.tm_min,
&mtm_time.tm_sec) == 6) {
mtm_time.tm_year -= 1900; /* Adjust years */
mtm_time.tm_mon -= 1; /* Adjust dates from 1-12 to 0-11 */
*tm_time = mtm_time;
return(tm_time);
} else if (sscanf(t_string, "%d.%d.%d-%d:%d",
&ntm_time.tm_year,
&ntm_time.tm_mon,
&ntm_time.tm_mday,
&ntm_time.tm_hour,
&ntm_time.tm_min) == 5) {
ntm_time.tm_year -= 1900; /* Adjust years */
ntm_time.tm_mon -= 1; /* Adjust dates from 1-12 to 0-11 */
*tm_time = ntm_time;
return(tm_time);
}
fprintf(stderr, invalid_date, "date", t_string);
exit( FALSE);
}
int
date_main(int argc, char * * argv)
struct tm *date_conv_ftime(struct tm *tm_time, const char *t_string)
{
char *date_str = NULL;
char *date_fmt = NULL;
char *t_buff;
int i;
int set_time = 0;
int rfc822 = 0;
int utc = 0;
int use_arg = 0;
time_t tm;
struct tm tm_time;
/* Interpret command line args */
i = --argc;
argv++;
while (i > 0 && **argv) {
if (**argv == '-') {
while (i>0 && *++(*argv)) switch (**argv) {
case 'R':
rfc822 = 1;
break;
case 's':
set_time = 1;
if(date_str != NULL) usage ( date_usage);
date_str = optarg;
break;
case 'u':
utc = 1;
if (putenv ("TZ=UTC0") != 0) {
fprintf(stderr, memory_exhausted, "date");
exit( FALSE);
}
/* Look ma, no break. Don't fix it either. */
case 'd':
use_arg = 1;
if(date_str != NULL) usage ( date_usage);
date_str = optarg;
break;
case '-':
usage ( date_usage);
}
} else {
if ( (date_fmt == NULL) && (strcmp(*argv, "+")==0) )
date_fmt=*argv;
else if (date_str == NULL) {
set_time = 1;
date_str=*argv;
} else {
usage ( date_usage);
}
struct tm itm_time, jtm_time, ktm_time, ltm_time, mtm_time, ntm_time;
itm_time = *tm_time;
jtm_time = *tm_time;
ktm_time = *tm_time;
ltm_time = *tm_time;
mtm_time = *tm_time;
ntm_time = *tm_time;
/* Parse input and assign appropriately to tm_time */
if (sscanf(t_string, "%d:%d:%d",
&itm_time.tm_hour, &itm_time.tm_min, &itm_time.tm_sec) == 3) {
*tm_time = itm_time;
return (tm_time);
} else if (sscanf(t_string, "%d:%d",
&jtm_time.tm_hour, &jtm_time.tm_min) == 2) {
*tm_time = jtm_time;
return (tm_time);
} else if (sscanf(t_string, "%d.%d-%d:%d:%d",
&ktm_time.tm_mon,
&ktm_time.tm_mday,
&ktm_time.tm_hour,
&ktm_time.tm_min, &ktm_time.tm_sec) == 5) {
ktm_time.tm_mon -= 1; /* Adjust dates from 1-12 to 0-11 */
*tm_time = ktm_time;
return (tm_time);
} else if (sscanf(t_string, "%d.%d-%d:%d",
&ltm_time.tm_mon,
&ltm_time.tm_mday,
&ltm_time.tm_hour, &ltm_time.tm_min) == 4) {
ltm_time.tm_mon -= 1; /* Adjust dates from 1-12 to 0-11 */
*tm_time = ltm_time;
return (tm_time);
} else if (sscanf(t_string, "%d.%d.%d-%d:%d:%d",
&mtm_time.tm_year,
&mtm_time.tm_mon,
&mtm_time.tm_mday,
&mtm_time.tm_hour,
&mtm_time.tm_min, &mtm_time.tm_sec) == 6) {
mtm_time.tm_year -= 1900; /* Adjust years */
mtm_time.tm_mon -= 1; /* Adjust dates from 1-12 to 0-11 */
*tm_time = mtm_time;
return (tm_time);
} else if (sscanf(t_string, "%d.%d.%d-%d:%d",
&ntm_time.tm_year,
&ntm_time.tm_mon,
&ntm_time.tm_mday,
&ntm_time.tm_hour, &ntm_time.tm_min) == 5) {
ntm_time.tm_year -= 1900; /* Adjust years */
ntm_time.tm_mon -= 1; /* Adjust dates from 1-12 to 0-11 */
*tm_time = ntm_time;
return (tm_time);
}
i--;
argv++;
}
fprintf(stderr, invalid_date, "date", t_string);
/* Now we have parsed all the information except the date format
which depends on whether the clock is being set or read */
time(&tm);
memcpy(&tm_time, localtime(&tm), sizeof(tm_time));
/* Zero out fields - take her back to midnight!*/
if(date_str != NULL) {
tm_time.tm_sec = 0;
tm_time.tm_min = 0;
tm_time.tm_hour = 0;
}
/* Process any date input to UNIX time since 1 Jan 1970 */
if(date_str != NULL) {
if(strchr(date_str, ':') != NULL) {
date_conv_ftime(&tm_time, date_str);
} else {
date_conv_time(&tm_time, date_str);
}
/* Correct any day of week and day of year etc fields */
tm = mktime(&tm_time);
if (tm < 0 ) {
fprintf(stderr, invalid_date, "date", date_str);
exit( FALSE);
}
/* if setting time, set it */
if(set_time) {
if( stime(&tm) < 0) {
fprintf(stderr, "date: can't set date.\n");
exit( FALSE);
}
}
}
/* Display output */
/* Deal with format string */
if(date_fmt == NULL) {
date_fmt = (rfc822
? (utc
? "%a, %_d %b %Y %H:%M:%S GMT"
: "%a, %_d %b %Y %H:%M:%S %z")
: "%a %b %e %H:%M:%S %Z %Y");
} else if ( *date_fmt == '\0' ) {
/* Imitate what GNU 'date' does with NO format string! */
printf ("\n");
exit( TRUE);
}
/* Handle special conversions */
if( strncmp( date_fmt, "%f", 2) == 0 ) {
date_fmt = "%Y.%m.%d-%H:%M:%S";
}
/* Print OUTPUT (after ALL that!) */
t_buff = malloc(201);
strftime(t_buff, 200, date_fmt, &tm_time);
printf("%s\n", t_buff);
exit( TRUE);
exit(FALSE);
}
int date_main(int argc, char **argv)
{
char *date_str = NULL;
char *date_fmt = NULL;
char *t_buff;
int i;
int set_time = 0;
int rfc822 = 0;
int utc = 0;
int use_arg = 0;
time_t tm;
struct tm tm_time;
/* Interpret command line args */
i = --argc;
argv++;
while (i > 0 && **argv) {
if (**argv == '-') {
while (i > 0 && *++(*argv))
switch (**argv) {
case 'R':
rfc822 = 1;
break;
case 's':
set_time = 1;
if (date_str != NULL)
usage(date_usage);
date_str = optarg;
break;
case 'u':
utc = 1;
if (putenv("TZ=UTC0") != 0) {
fprintf(stderr, memory_exhausted, "date");
exit(FALSE);
}
/* Look ma, no break. Don't fix it either. */
case 'd':
use_arg = 1;
if (date_str != NULL)
usage(date_usage);
date_str = optarg;
break;
case '-':
usage(date_usage);
}
} else {
if ((date_fmt == NULL) && (strcmp(*argv, "+") == 0))
date_fmt = *argv;
else if (date_str == NULL) {
set_time = 1;
date_str = *argv;
} else {
usage(date_usage);
}
}
i--;
argv++;
}
/* Now we have parsed all the information except the date format
which depends on whether the clock is being set or read */
time(&tm);
memcpy(&tm_time, localtime(&tm), sizeof(tm_time));
/* Zero out fields - take her back to midnight! */
if (date_str != NULL) {
tm_time.tm_sec = 0;
tm_time.tm_min = 0;
tm_time.tm_hour = 0;
}
/* Process any date input to UNIX time since 1 Jan 1970 */
if (date_str != NULL) {
if (strchr(date_str, ':') != NULL) {
date_conv_ftime(&tm_time, date_str);
} else {
date_conv_time(&tm_time, date_str);
}
/* Correct any day of week and day of year etc fields */
tm = mktime(&tm_time);
if (tm < 0) {
fprintf(stderr, invalid_date, "date", date_str);
exit(FALSE);
}
/* if setting time, set it */
if (set_time) {
if (stime(&tm) < 0) {
fprintf(stderr, "date: can't set date.\n");
exit(FALSE);
}
}
}
/* Display output */
/* Deal with format string */
if (date_fmt == NULL) {
date_fmt = (rfc822
? (utc
? "%a, %_d %b %Y %H:%M:%S GMT"
: "%a, %_d %b %Y %H:%M:%S %z")
: "%a %b %e %H:%M:%S %Z %Y");
} else if (*date_fmt == '\0') {
/* Imitate what GNU 'date' does with NO format string! */
printf("\n");
exit(TRUE);
}
/* Handle special conversions */
if (strncmp(date_fmt, "%f", 2) == 0) {
date_fmt = "%Y.%m.%d-%H:%M:%S";
}
/* Print OUTPUT (after ALL that!) */
t_buff = malloc(201);
strftime(t_buff, 200, date_fmt, &tm_time);
printf("%s\n", t_buff);
exit(TRUE);
}

View File

@ -1,3 +1,4 @@
/* vi: set sw=4 ts=4: */
/*
* Mini dd implementation for busybox
*
@ -40,164 +41,159 @@ typedef unsigned long long int uintmax_t;
#endif
static const char dd_usage[] =
"dd [if=name] [of=name] [bs=n] [count=n] [skip=n] [seek=n]\n\n"
"Copy a file, converting and formatting according to options\n\n"
"\tif=FILE\tread from FILE instead of stdin\n"
"\tof=FILE\twrite to FILE instead of stdout\n"
"\tbs=n\tread and write n bytes at a time\n"
"\tcount=n\tcopy only n input blocks\n"
"\tskip=n\tskip n input blocks\n"
"\tseek=n\tskip n output blocks\n"
"\n"
"Numbers may be suffixed by w (x2), k (x1024), b (x512), or M (x1024^2)\n";
"dd [if=name] [of=name] [bs=n] [count=n] [skip=n] [seek=n]\n\n"
"Copy a file, converting and formatting according to options\n\n"
"\tif=FILE\tread from FILE instead of stdin\n"
"\tof=FILE\twrite to FILE instead of stdout\n"
"\tbs=n\tread and write n bytes at a time\n"
"\tcount=n\tcopy only n input blocks\n"
"\tskip=n\tskip n input blocks\n"
"\tseek=n\tskip n output blocks\n"
"\n"
"Numbers may be suffixed by w (x2), k (x1024), b (x512), or M (x1024^2)\n";
extern int dd_main (int argc, char **argv)
extern int dd_main(int argc, char **argv)
{
const char *inFile = NULL;
const char *outFile = NULL;
char *cp;
int inFd;
int outFd;
int inCc = 0;
int outCc;
long blockSize = 512;
uintmax_t skipBlocks = 0;
uintmax_t seekBlocks = 0;
uintmax_t count = (uintmax_t)-1;
uintmax_t intotal;
uintmax_t outTotal;
unsigned char *buf;
const char *inFile = NULL;
const char *outFile = NULL;
char *cp;
int inFd;
int outFd;
int inCc = 0;
int outCc;
long blockSize = 512;
uintmax_t skipBlocks = 0;
uintmax_t seekBlocks = 0;
uintmax_t count = (uintmax_t) - 1;
uintmax_t intotal;
uintmax_t outTotal;
unsigned char *buf;
argc--;
argv++;
/* Parse any options */
while (argc) {
if (inFile == NULL && (strncmp(*argv, "if", 2) == 0))
inFile=((strchr(*argv, '='))+1);
else if (outFile == NULL && (strncmp(*argv, "of", 2) == 0))
outFile=((strchr(*argv, '='))+1);
else if (strncmp("count", *argv, 5) == 0) {
count = getNum ((strchr(*argv, '='))+1);
if (count <= 0) {
fprintf (stderr, "Bad count value %s\n", *argv);
goto usage;
}
}
else if (strncmp(*argv, "bs", 2) == 0) {
blockSize = getNum ((strchr(*argv, '='))+1);
if (blockSize <= 0) {
fprintf (stderr, "Bad block size value %s\n", *argv);
goto usage;
}
}
else if (strncmp(*argv, "skip", 4) == 0) {
skipBlocks = getNum ((strchr(*argv, '='))+1);
if (skipBlocks <= 0) {
fprintf (stderr, "Bad skip value %s\n", *argv);
goto usage;
}
}
else if (strncmp(*argv, "seek", 4) == 0) {
seekBlocks = getNum ((strchr(*argv, '='))+1);
if (seekBlocks <= 0) {
fprintf (stderr, "Bad seek value %s\n", *argv);
goto usage;
}
}
else {
goto usage;
}
argc--;
argv++;
}
buf = malloc (blockSize);
if (buf == NULL) {
fprintf (stderr, "Cannot allocate buffer\n");
exit( FALSE);
}
/* Parse any options */
while (argc) {
if (inFile == NULL && (strncmp(*argv, "if", 2) == 0))
inFile = ((strchr(*argv, '=')) + 1);
else if (outFile == NULL && (strncmp(*argv, "of", 2) == 0))
outFile = ((strchr(*argv, '=')) + 1);
else if (strncmp("count", *argv, 5) == 0) {
count = getNum((strchr(*argv, '=')) + 1);
if (count <= 0) {
fprintf(stderr, "Bad count value %s\n", *argv);
goto usage;
}
} else if (strncmp(*argv, "bs", 2) == 0) {
blockSize = getNum((strchr(*argv, '=')) + 1);
if (blockSize <= 0) {
fprintf(stderr, "Bad block size value %s\n", *argv);
goto usage;
}
} else if (strncmp(*argv, "skip", 4) == 0) {
skipBlocks = getNum((strchr(*argv, '=')) + 1);
if (skipBlocks <= 0) {
fprintf(stderr, "Bad skip value %s\n", *argv);
goto usage;
}
intotal = 0;
outTotal = 0;
} else if (strncmp(*argv, "seek", 4) == 0) {
seekBlocks = getNum((strchr(*argv, '=')) + 1);
if (seekBlocks <= 0) {
fprintf(stderr, "Bad seek value %s\n", *argv);
goto usage;
}
if (inFile == NULL)
inFd = fileno(stdin);
else
inFd = open (inFile, 0);
if (inFd < 0) {
perror (inFile);
free (buf);
exit( FALSE);
}
if (outFile == NULL)
outFd = fileno(stdout);
else
outFd = open(outFile, O_WRONLY | O_CREAT | O_TRUNC, 0666);
if (outFd < 0) {
perror (outFile);
close (inFd);
free (buf);
exit( FALSE);
}
lseek(inFd, skipBlocks*blockSize, SEEK_SET);
lseek(outFd, seekBlocks*blockSize, SEEK_SET);
//
//TODO: Convert to using fullRead & fullWrite
// from utility.c
// -Erik
while (outTotal < count * blockSize) {
inCc = read (inFd, buf, blockSize);
if (inCc < 0) {
perror (inFile);
goto cleanup;
} else if (inCc == 0) {
goto cleanup;
} else {
goto usage;
}
argc--;
argv++;
}
intotal += inCc;
cp = buf;
while (intotal > outTotal) {
if (outTotal + inCc > count * blockSize)
inCc = count * blockSize - outTotal;
outCc = write (outFd, cp, inCc);
if (outCc < 0) {
perror (outFile);
goto cleanup;
} else if (outCc == 0) {
goto cleanup;
}
inCc -= outCc;
cp += outCc;
outTotal += outCc;
buf = malloc(blockSize);
if (buf == NULL) {
fprintf(stderr, "Cannot allocate buffer\n");
exit(FALSE);
}
}
if (inCc < 0)
perror (inFile);
intotal = 0;
outTotal = 0;
if (inFile == NULL)
inFd = fileno(stdin);
else
inFd = open(inFile, 0);
if (inFd < 0) {
perror(inFile);
free(buf);
exit(FALSE);
}
if (outFile == NULL)
outFd = fileno(stdout);
else
outFd = open(outFile, O_WRONLY | O_CREAT | O_TRUNC, 0666);
if (outFd < 0) {
perror(outFile);
close(inFd);
free(buf);
exit(FALSE);
}
lseek(inFd, skipBlocks * blockSize, SEEK_SET);
lseek(outFd, seekBlocks * blockSize, SEEK_SET);
//
//TODO: Convert to using fullRead & fullWrite
// from utility.c
// -Erik
while (outTotal < count * blockSize) {
inCc = read(inFd, buf, blockSize);
if (inCc < 0) {
perror(inFile);
goto cleanup;
} else if (inCc == 0) {
goto cleanup;
}
intotal += inCc;
cp = buf;
while (intotal > outTotal) {
if (outTotal + inCc > count * blockSize)
inCc = count * blockSize - outTotal;
outCc = write(outFd, cp, inCc);
if (outCc < 0) {
perror(outFile);
goto cleanup;
} else if (outCc == 0) {
goto cleanup;
}
inCc -= outCc;
cp += outCc;
outTotal += outCc;
}
}
if (inCc < 0)
perror(inFile);
cleanup:
close (inFd);
close (outFd);
free (buf);
close(inFd);
close(outFd);
free(buf);
printf ("%ld+%d records in\n", (long)(intotal / blockSize),
(intotal % blockSize) != 0);
printf ("%ld+%d records out\n", (long)(outTotal / blockSize),
(outTotal % blockSize) != 0);
exit( TRUE);
printf("%ld+%d records in\n", (long) (intotal / blockSize),
(intotal % blockSize) != 0);
printf("%ld+%d records out\n", (long) (outTotal / blockSize),
(outTotal % blockSize) != 0);
exit(TRUE);
usage:
usage( dd_usage);
usage(dd_usage);
}

View File

@ -1,3 +1,4 @@
/* vi: set sw=4 ts=4: */
/*
* Mini df implementation for busybox
*
@ -29,81 +30,81 @@
#include <fstab.h>
static const char df_usage[] = "df [filesystem ...]\n"
"\n" "\tPrint the filesystem space used and space available.\n";
extern const char mtab_file[]; /* Defined in utility.c */
"\n" "\tPrint the filesystem space used and space available.\n";
extern const char mtab_file[]; /* Defined in utility.c */
static int df(char *device, const char *mountPoint)
{
struct statfs s;
long blocks_used;
long blocks_percent_used;
struct fstab* fstabItem;
struct statfs s;
long blocks_used;
long blocks_percent_used;
struct fstab *fstabItem;
if (statfs(mountPoint, &s) != 0) {
perror(mountPoint);
return FALSE;
}
if (s.f_blocks > 0) {
blocks_used = s.f_blocks - s.f_bfree;
blocks_percent_used = (long)
(blocks_used * 100.0 / (blocks_used + s.f_bavail) + 0.5);
/* Note that if /etc/fstab is missing, libc can't fix up /dev/root for us */
if (strcmp (device, "/dev/root") == 0) {
fstabItem = getfsfile ("/");
if (fstabItem != NULL)
device = fstabItem->fs_spec;
if (statfs(mountPoint, &s) != 0) {
perror(mountPoint);
return FALSE;
}
printf("%-20s %9ld %9ld %9ld %3ld%% %s\n",
device,
(long) (s.f_blocks * (s.f_bsize / 1024.0)),
(long) ((s.f_blocks - s.f_bfree) * (s.f_bsize / 1024.0)),
(long) (s.f_bavail * (s.f_bsize / 1024.0)),
blocks_percent_used, mountPoint);
}
if (s.f_blocks > 0) {
blocks_used = s.f_blocks - s.f_bfree;
blocks_percent_used = (long)
(blocks_used * 100.0 / (blocks_used + s.f_bavail) + 0.5);
/* Note that if /etc/fstab is missing, libc can't fix up /dev/root for us */
if (strcmp(device, "/dev/root") == 0) {
fstabItem = getfsfile("/");
if (fstabItem != NULL)
device = fstabItem->fs_spec;
}
printf("%-20s %9ld %9ld %9ld %3ld%% %s\n",
device,
(long) (s.f_blocks * (s.f_bsize / 1024.0)),
(long) ((s.f_blocks - s.f_bfree) * (s.f_bsize / 1024.0)),
(long) (s.f_bavail * (s.f_bsize / 1024.0)),
blocks_percent_used, mountPoint);
return TRUE;
}
return TRUE;
}
extern int df_main(int argc, char **argv)
{
printf("%-20s %-14s %s %s %s %s\n", "Filesystem",
"1k-blocks", "Used", "Available", "Use%", "Mounted on");
printf("%-20s %-14s %s %s %s %s\n", "Filesystem",
"1k-blocks", "Used", "Available", "Use%", "Mounted on");
if (argc > 1) {
struct mntent *mountEntry;
int status;
if (argc > 1) {
struct mntent *mountEntry;
int status;
while (argc > 1) {
if ((mountEntry = findMountPoint(argv[1], mtab_file)) ==
0) {
fprintf(stderr, "%s: can't find mount point.\n", argv[1]);
exit( FALSE);
}
status = df(mountEntry->mnt_fsname, mountEntry->mnt_dir);
if (status != 0)
exit( status);
argc--;
argv++;
}
exit( TRUE);
} else {
FILE *mountTable;
struct mntent *mountEntry;
while (argc > 1) {
if ((mountEntry = findMountPoint(argv[1], mtab_file)) == 0) {
fprintf(stderr, "%s: can't find mount point.\n", argv[1]);
exit(FALSE);
}
status = df(mountEntry->mnt_fsname, mountEntry->mnt_dir);
if (status != 0)
exit(status);
argc--;
argv++;
}
exit(TRUE);
} else {
FILE *mountTable;
struct mntent *mountEntry;
mountTable = setmntent(mtab_file, "r");
if (mountTable == 0) {
perror(mtab_file);
exit(FALSE);
mountTable = setmntent(mtab_file, "r");
if (mountTable == 0) {
perror(mtab_file);
exit(FALSE);
}
while ((mountEntry = getmntent(mountTable))) {
df(mountEntry->mnt_fsname, mountEntry->mnt_dir);
}
endmntent(mountTable);
}
while ((mountEntry = getmntent(mountTable))) {
df(mountEntry->mnt_fsname, mountEntry->mnt_dir);
}
endmntent(mountTable);
}
exit( TRUE);
exit(TRUE);
}

View File

@ -1,3 +1,4 @@
/* vi: set sw=4 ts=4: */
/*
* Mini du implementation for busybox
*
@ -31,119 +32,121 @@
#include <dirent.h>
#include <stdio.h>
#include <errno.h>
#include <sys/param.h> /* for PATH_MAX */
#include <sys/param.h> /* for PATH_MAX */
typedef void (Display)(long, char *);
typedef void (Display) (long, char *);
static const char du_usage[] =
"du [OPTION]... [FILE]...\n\n"
"\t-s\tdisplay only a total for each argument\n"
;
static int du_depth = 0;
"du [OPTION]... [FILE]...\n\n"
"\t-s\tdisplay only a total for each argument\n";
static Display *print;
static int du_depth = 0;
static void
print_normal(long size, char *filename)
static Display *print;
static void print_normal(long size, char *filename)
{
fprintf(stdout, "%-7ld %s\n", size, filename);
fprintf(stdout, "%-7ld %s\n", size, filename);
}
static void
print_summary(long size, char *filename)
static void print_summary(long size, char *filename)
{
if (du_depth == 1) {
print_normal(size, filename);
}
if (du_depth == 1) {
print_normal(size, filename);
}
}
/* tiny recursive du */
static long
du(char *filename)
static long du(char *filename)
{
struct stat statbuf;
long sum;
if ((lstat(filename, &statbuf)) != 0) {
fprintf(stdout, "du: %s: %s\n", filename, strerror(errno));
return 0;
}
du_depth++;
sum = statbuf.st_blocks;
if (S_ISDIR(statbuf.st_mode)) {
DIR *dir;
struct dirent *entry;
dir = opendir(filename);
if (!dir) { return 0; }
while ((entry = readdir(dir))) {
char newfile[PATH_MAX + 1];
char *name = entry->d_name;
if ( (strcmp(name, "..") == 0)
|| (strcmp(name, ".") == 0))
{ continue; }
if (strlen(filename) + strlen(name) + 1 > PATH_MAX) {
fprintf(stderr, name_too_long, "du");
return 0;
}
sprintf(newfile, "%s/%s", filename, name);
sum += du(newfile);
}
closedir(dir);
print(sum, filename);
}
du_depth--;
return sum;
}
int
du_main(int argc, char **argv)
{
int i;
char opt;
/* default behaviour */
print = print_normal;
/* parse argv[] */
for (i = 1; i < argc; i++) {
if (argv[i][0] == '-') {
opt = argv[i][1];
switch (opt) {
case 's':
print = print_summary;
break;
case 'h':
usage(du_usage);
break;
default:
fprintf(stderr, "du: invalid option -- %c\n", opt);
usage(du_usage);
}
} else {
break;
}
}
/* go through remaining args (if any) */
if (i >= argc) {
du(".");
} else {
struct stat statbuf;
long sum;
for ( ; i < argc; i++) {
sum = du(argv[i]);
if ((sum) && (isDirectory(argv[i], FALSE))) { print_normal(sum, argv[i]); }
}
}
exit(0);
if ((lstat(filename, &statbuf)) != 0) {
fprintf(stdout, "du: %s: %s\n", filename, strerror(errno));
return 0;
}
du_depth++;
sum = statbuf.st_blocks;
if (S_ISDIR(statbuf.st_mode)) {
DIR *dir;
struct dirent *entry;
dir = opendir(filename);
if (!dir) {
return 0;
}
while ((entry = readdir(dir))) {
char newfile[PATH_MAX + 1];
char *name = entry->d_name;
if ((strcmp(name, "..") == 0)
|| (strcmp(name, ".") == 0)) {
continue;
}
if (strlen(filename) + strlen(name) + 1 > PATH_MAX) {
fprintf(stderr, name_too_long, "du");
return 0;
}
sprintf(newfile, "%s/%s", filename, name);
sum += du(newfile);
}
closedir(dir);
print(sum, filename);
}
du_depth--;
return sum;
}
/* $Id: du.c,v 1.10 2000/02/07 05:29:42 erik Exp $ */
int du_main(int argc, char **argv)
{
int i;
char opt;
/* default behaviour */
print = print_normal;
/* parse argv[] */
for (i = 1; i < argc; i++) {
if (argv[i][0] == '-') {
opt = argv[i][1];
switch (opt) {
case 's':
print = print_summary;
break;
case 'h':
usage(du_usage);
break;
default:
fprintf(stderr, "du: invalid option -- %c\n", opt);
usage(du_usage);
}
} else {
break;
}
}
/* go through remaining args (if any) */
if (i >= argc) {
du(".");
} else {
long sum;
for (; i < argc; i++) {
sum = du(argv[i]);
if ((sum) && (isDirectory(argv[i], FALSE))) {
print_normal(sum, argv[i]);
}
}
}
exit(0);
}
/* $Id: du.c,v 1.11 2000/02/08 19:58:47 erik Exp $ */

View File

@ -1,3 +1,4 @@
/* vi: set sw=4 ts=4: */
/*
* Mini head implementation for busybox
*
@ -26,83 +27,86 @@
#include <stdio.h>
const char head_usage[] =
"head [OPTION] [FILE]...\n\n"
"Print first 10 lines of each FILE to standard output.\n"
"With more than one FILE, precede each with a header giving the\n"
"file name. With no FILE, or when FILE is -, read standard input.\n\n"
"Options:\n"
"\t-n NUM\t\tPrint first NUM lines instead of first 10\n";
"head [OPTION] [FILE]...\n\n"
"Print first 10 lines of each FILE to standard output.\n"
"With more than one FILE, precede each with a header giving the\n"
"file name. With no FILE, or when FILE is -, read standard input.\n\n"
int
head(int len, FILE *src)
"Options:\n" "\t-n NUM\t\tPrint first NUM lines instead of first 10\n";
int head(int len, FILE * src)
{
int i;
char buffer[1024];
int i;
char buffer[1024];
for (i = 0; i < len; i++) {
fgets(buffer, 1024, src);
if (feof(src)) { break; }
fputs(buffer, stdout);
}
return 0;
for (i = 0; i < len; i++) {
fgets(buffer, 1024, src);
if (feof(src)) {
break;
}
fputs(buffer, stdout);
}
return 0;
}
/* BusyBoxed head(1) */
int
head_main(int argc, char **argv)
int head_main(int argc, char **argv)
{
char opt;
int len = 10, tmplen, i;
char opt;
int len = 10, tmplen, i;
/* parse argv[] */
for (i = 1; i < argc; i++) {
if (argv[i][0] == '-') {
opt = argv[i][1];
switch (opt) {
case 'n':
tmplen = 0;
if (++i < argc)
tmplen = atoi(argv[i]);
if (tmplen < 1)
usage(head_usage);
len = tmplen;
break;
case '-':
case 'h':
usage(head_usage);
default:
fprintf(stderr, "head: invalid option -- %c\n", opt);
usage(head_usage);
}
} else {
break;
}
}
/* get rest of argv[] or stdin if nothing's left */
if (i >= argc) {
head(len, stdin);
/* parse argv[] */
for (i = 1; i < argc; i++) {
if (argv[i][0] == '-') {
opt = argv[i][1];
switch (opt) {
case 'n':
tmplen = 0;
if (++i < argc)
tmplen = atoi(argv[i]);
if (tmplen < 1)
usage(head_usage);
len = tmplen;
break;
case '-':
case 'h':
usage(head_usage);
default:
fprintf(stderr, "head: invalid option -- %c\n", opt);
usage(head_usage);
}
} else {
break;
}
}
int need_headers = ((argc - i) > 1);
/* get rest of argv[] or stdin if nothing's left */
if (i >= argc) {
head(len, stdin);
for (; i < argc; i++) {
FILE *src;
} else {
int need_headers = ((argc - i) > 1);
for ( ; i < argc; i++) {
FILE *src;
src = fopen(argv[i], "r");
if (!src) {
fprintf(stderr,"head: %s: %s\n", argv[i], strerror(errno));
} else {
/* emulating GNU behaviour */
if (need_headers) {
fprintf(stdout, "==> %s <==\n", argv[i]);
src = fopen(argv[i], "r");
if (!src) {
fprintf(stderr, "head: %s: %s\n", argv[i],
strerror(errno));
} else {
/* emulating GNU behaviour */
if (need_headers) {
fprintf(stdout, "==> %s <==\n", argv[i]);
}
head(len, src);
if (i < argc - 1) {
fprintf(stdout, "\n");
}
}
}
head(len, src);
if (i < argc - 1) {
fprintf(stdout, "\n");
}
}
}
}
exit(0);
exit(0);
}
/* $Id: head.c,v 1.7 2000/02/07 05:29:42 erik Exp $ */
/* $Id: head.c,v 1.8 2000/02/08 19:58:47 erik Exp $ */

View File

@ -1,3 +1,4 @@
/* vi: set sw=4 ts=4: */
/*
* Mini hostid implementation for busybox
*
@ -22,7 +23,8 @@
#include "internal.h"
#include <stdio.h>
extern int hostid_main(int argc, char **argv) {
printf ("%lx\n", gethostid());
exit( TRUE);
extern int hostid_main(int argc, char **argv)
{
printf("%lx\n", gethostid());
exit(TRUE);
}

View File

@ -1,14 +1,14 @@
/* vi: set sw=4 ts=4: */
#include "internal.h"
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
extern int
length_main(int argc, char * * argv)
extern int length_main(int argc, char **argv)
{
if ( argc != 2 || **(argv+1) == '-' ) {
usage("length string\n");
}
printf("%d\n", strlen(argv[1]));
return( TRUE);
if (argc != 2 || **(argv + 1) == '-') {
usage("length string\n");
}
printf("%d\n", strlen(argv[1]));
return (TRUE);
}

View File

@ -1,3 +1,4 @@
/* vi: set sw=4 ts=4: */
/*
* Mini ln implementation for busybox
*
@ -30,15 +31,16 @@
#include <stdio.h>
#include <dirent.h>
#include <errno.h>
#include <sys/param.h> /* for PATH_MAX */
#include <sys/param.h> /* for PATH_MAX */
static const char ln_usage[] =
"ln [OPTION] TARGET... LINK_NAME|DIRECTORY\n\n"
"Create a link named LINK_NAME or DIRECTORY to the specified TARGET\n\n"
"Options:\n"
"\t-s\tmake symbolic links instead of hard links\n"
"\t-f\tremove existing destination files\n"
"\t-n\tno dereference symlinks - treat like normal file\n";
"ln [OPTION] TARGET... LINK_NAME|DIRECTORY\n\n"
"Create a link named LINK_NAME or DIRECTORY to the specified TARGET\n\n"
"Options:\n"
"\t-s\tmake symbolic links instead of hard links\n"
"\t-f\tremove existing destination files\n"
"\t-n\tno dereference symlinks - treat like normal file\n";
static int symlinkFlag = FALSE;
static int removeoldFlag = FALSE;
@ -46,83 +48,83 @@ static int followLinks = TRUE;
extern int ln_main(int argc, char **argv)
{
char *linkName;
int linkIntoDirFlag;
char *linkName;
int linkIntoDirFlag;
if (argc < 3) {
usage (ln_usage);
}
argc--;
argv++;
/* Parse any options */
while (**argv == '-') {
while (*++(*argv))
switch (**argv) {
case 's':
symlinkFlag = TRUE;
break;
case 'f':
removeoldFlag = TRUE;
break;
case 'n':
followLinks = FALSE;
break;
default:
usage (ln_usage);
}
if (argc < 3) {
usage(ln_usage);
}
argc--;
argv++;
}
linkName = argv[argc - 1];
if (strlen(linkName) > PATH_MAX) {
fprintf(stderr, name_too_long, "ln");
exit FALSE;
}
linkIntoDirFlag = isDirectory(linkName, TRUE);
if ((argc > 3) && !linkIntoDirFlag) {
fprintf(stderr, not_a_directory, "ln", linkName);
exit FALSE;
}
while (argc-- >= 2) {
char srcName[PATH_MAX + 1];
int nChars, status;
if (strlen(*argv) > PATH_MAX) {
fprintf(stderr, name_too_long, "ln");
exit FALSE;
/* Parse any options */
while (**argv == '-') {
while (*++(*argv))
switch (**argv) {
case 's':
symlinkFlag = TRUE;
break;
case 'f':
removeoldFlag = TRUE;
break;
case 'n':
followLinks = FALSE;
break;
default:
usage(ln_usage);
}
argc--;
argv++;
}
if (followLinks == FALSE) {
strcpy(srcName, *argv);
} else {
/* Warning! This can silently truncate if > PATH_MAX, but
I don't think that there can be one > PATH_MAX anyway. */
nChars = readlink(*argv, srcName, PATH_MAX);
srcName[nChars] = '\0';
}
linkName = argv[argc - 1];
if (removeoldFlag == TRUE) {
status = ( unlink(linkName) && errno != ENOENT );
if (status != 0) {
perror(linkName);
if (strlen(linkName) > PATH_MAX) {
fprintf(stderr, name_too_long, "ln");
exit FALSE;
}
}
if (symlinkFlag == TRUE)
status = symlink(*argv, linkName);
else
status = link(*argv, linkName);
if (status != 0) {
perror(linkName);
exit FALSE;
linkIntoDirFlag = isDirectory(linkName, TRUE);
if ((argc > 3) && !linkIntoDirFlag) {
fprintf(stderr, not_a_directory, "ln", linkName);
exit FALSE;
}
}
exit TRUE;
while (argc-- >= 2) {
char srcName[PATH_MAX + 1];
int nChars, status;
if (strlen(*argv) > PATH_MAX) {
fprintf(stderr, name_too_long, "ln");
exit FALSE;
}
if (followLinks == FALSE) {
strcpy(srcName, *argv);
} else {
/* Warning! This can silently truncate if > PATH_MAX, but
I don't think that there can be one > PATH_MAX anyway. */
nChars = readlink(*argv, srcName, PATH_MAX);
srcName[nChars] = '\0';
}
if (removeoldFlag == TRUE) {
status = (unlink(linkName) && errno != ENOENT);
if (status != 0) {
perror(linkName);
exit FALSE;
}
}
if (symlinkFlag == TRUE)
status = symlink(*argv, linkName);
else
status = link(*argv, linkName);
if (status != 0) {
perror(linkName);
exit FALSE;
}
}
exit TRUE;
}

View File

@ -1,3 +1,4 @@
/* vi: set sw=4 ts=4: */
/*
* Mini logname implementation for busybox
*
@ -23,18 +24,21 @@
#include <stdio.h>
static const char logname_usage[] = "logname\n\n"
"Print the name of the current user.\n";
extern int logname_main(int argc, char **argv) {
"Print the name of the current user.\n";
extern int logname_main(int argc, char **argv)
{
char *cp;
if (argc > 1) usage (logname_usage);
if (argc > 1)
usage(logname_usage);
cp = getlogin ();
cp = getlogin();
if (cp) {
puts (cp);
exit (TRUE);
}
fprintf (stderr, "%s: no login name\n", argv[0]);
exit (FALSE);
puts(cp);
exit(TRUE);
}
fprintf(stderr, "%s: no login name\n", argv[0]);
exit(FALSE);
}

View File

@ -1,3 +1,4 @@
/* vi: set sw=4 ts=4: */
/*
* tiny-ls.c version 0.1.0: A minimalist 'ls'
* Copyright (C) 1996 Brian Candler <B.Candler@pobox.com>
@ -40,18 +41,18 @@
* 1. requires lstat (BSD) - how do you do it without?
*/
#define TERMINAL_WIDTH 80 /* use 79 if your terminal has linefold bug */
#define COLUMN_WIDTH 14 /* default if AUTOWIDTH not defined */
#define COLUMN_GAP 2 /* includes the file type char, if present */
#define TERMINAL_WIDTH 80 /* use 79 if your terminal has linefold bug */
#define COLUMN_WIDTH 14 /* default if AUTOWIDTH not defined */
#define COLUMN_GAP 2 /* includes the file type char, if present */
#define HAS_REWINDDIR
/************************************************************************/
#include "internal.h"
#if !defined(__GLIBC__) && (__GLIBC__ >= 2) && (__GLIBC_MINOR__ >= 1)
# include <linux/types.h>
# include <linux/types.h>
#else
# include <sys/types.h>
# include <sys/types.h>
#endif
#include <sys/stat.h>
#include <stdio.h>
@ -75,28 +76,28 @@
#endif
#define FMT_AUTO 0
#define FMT_LONG 1 /* one record per line, extended info */
#define FMT_SINGLE 2 /* one record per line */
#define FMT_ROWS 3 /* print across rows */
#define FMT_COLUMNS 3 /* fill columns (same, since we don't sort) */
#define FMT_LONG 1 /* one record per line, extended info */
#define FMT_SINGLE 2 /* one record per line */
#define FMT_ROWS 3 /* print across rows */
#define FMT_COLUMNS 3 /* fill columns (same, since we don't sort) */
#define TIME_MOD 0
#define TIME_CHANGE 1
#define TIME_ACCESS 2
#define DISP_FTYPE 1 /* show character for file type */
#define DISP_EXEC 2 /* show '*' if regular executable file */
#define DISP_HIDDEN 4 /* show files starting . (except . and ..) */
#define DISP_DOT 8 /* show . and .. */
#define DISP_NUMERIC 16 /* numeric uid and gid */
#define DISP_FULLTIME 32 /* show extended time display */
#define DIR_NOLIST 64 /* show directory as itself, not contents */
#define DISP_DIRNAME 128 /* show directory name (for internal use) */
#define DIR_RECURSE 256 /* -R (not yet implemented) */
#define DISP_FTYPE 1 /* show character for file type */
#define DISP_EXEC 2 /* show '*' if regular executable file */
#define DISP_HIDDEN 4 /* show files starting . (except . and ..) */
#define DISP_DOT 8 /* show . and .. */
#define DISP_NUMERIC 16 /* numeric uid and gid */
#define DISP_FULLTIME 32 /* show extended time display */
#define DIR_NOLIST 64 /* show directory as itself, not contents */
#define DISP_DIRNAME 128 /* show directory name (for internal use) */
#define DIR_RECURSE 256 /* -R (not yet implemented) */
static unsigned char display_fmt = FMT_AUTO;
static unsigned short opts = 0;
static unsigned short column = 0;
static unsigned char display_fmt = FMT_AUTO;
static unsigned short opts = 0;
static unsigned short column = 0;
#ifdef BB_FEATURE_AUTOWIDTH
static unsigned short terminal_width = 0, column_width = 0;
@ -113,13 +114,14 @@ static unsigned char time_fmt = TIME_MOD;
static void writenum(long val, short minwidth)
{
char scratch[128];
char scratch[128];
char *p = scratch + sizeof(scratch);
short len = 0;
short neg = (val < 0);
if (neg) val = -val;
if (neg)
val = -val;
do
*--p = (val % 10) + '0', len++, val /= 10;
while (val);
@ -142,8 +144,9 @@ static void newline(void)
static void tab(short col)
{
static const char spaces[] = " ";
#define nspaces ((sizeof spaces)-1) /* null terminator! */
#define nspaces ((sizeof spaces)-1) /* null terminator! */
short n = col - column;
if (n > 0) {
@ -155,7 +158,7 @@ static void tab(short col)
/* must be 1...(sizeof spaces) left */
wr(spaces, n);
}
#undef nspaces
#undef nspaces
}
#ifdef BB_FEATURE_LS_FILETYPES
@ -163,8 +166,8 @@ static char append_char(mode_t mode)
{
if (!(opts & DISP_FTYPE))
return '\0';
if ((opts & DISP_EXEC) && S_ISREG(mode) && (mode & (S_IXUSR|S_IXGRP|S_IXOTH)))
return '*';
if ((opts & DISP_EXEC) && S_ISREG(mode)
&& (mode & (S_IXUSR | S_IXGRP | S_IXOTH))) return '*';
return APPCHAR(mode);
}
#endif
@ -176,89 +179,93 @@ static char append_char(mode_t mode)
**
**/
static void list_single(const char *name, struct stat *info, const char *fullname)
static void list_single(const char *name, struct stat *info,
const char *fullname)
{
char scratch[PATH_MAX + 1];
short len = strlen(name);
#ifdef BB_FEATURE_LS_FILETYPES
char append = append_char(info->st_mode);
#endif
if (display_fmt == FMT_LONG) {
mode_t mode = info->st_mode;
mode_t mode = info->st_mode;
newline();
wr(modeString(mode), 10);
column=10;
writenum((long)info->st_nlink,(short)5);
column = 10;
writenum((long) info->st_nlink, (short) 5);
fputs(" ", stdout);
#ifdef BB_FEATURE_LS_USERNAME
if (!(opts & DISP_NUMERIC)) {
memset ( scratch, 0, sizeof (scratch));
my_getpwuid( scratch, info->st_uid);
memset(scratch, 0, sizeof(scratch));
my_getpwuid(scratch, info->st_uid);
if (*scratch) {
fputs(scratch, stdout);
if ( strlen( scratch) <= 8 )
wr(" ", 9-strlen( scratch));
}
else {
writenum((long) info->st_uid,(short)8);
fputs(scratch, stdout);
if (strlen(scratch) <= 8)
wr(" ", 9 - strlen(scratch));
} else {
writenum((long) info->st_uid, (short) 8);
fputs(" ", stdout);
}
} else
#endif
{
writenum((long) info->st_uid,(short)8);
fputs(" ", stdout);
writenum((long) info->st_uid, (short) 8);
fputs(" ", stdout);
}
#ifdef BB_FEATURE_LS_USERNAME
if (!(opts & DISP_NUMERIC)) {
memset ( scratch, 0, sizeof (scratch));
my_getgrgid( scratch, info->st_gid);
memset(scratch, 0, sizeof(scratch));
my_getgrgid(scratch, info->st_gid);
if (*scratch) {
fputs(scratch, stdout);
if ( strlen( scratch) <= 8 )
wr(" ", 8-strlen( scratch));
}
else
writenum((long) info->st_gid,(short)8);
fputs(scratch, stdout);
if (strlen(scratch) <= 8)
wr(" ", 8 - strlen(scratch));
} else
writenum((long) info->st_gid, (short) 8);
} else
#endif
writenum((long) info->st_gid,(short)8);
writenum((long) info->st_gid, (short) 8);
//tab(26);
if (S_ISBLK(mode) || S_ISCHR(mode)) {
writenum((long)MAJOR(info->st_rdev),(short)3);
writenum((long) MAJOR(info->st_rdev), (short) 3);
fputs(", ", stdout);
writenum((long)MINOR(info->st_rdev),(short)3);
}
else
writenum((long)info->st_size,(short)8);
writenum((long) MINOR(info->st_rdev), (short) 3);
} else
writenum((long) info->st_size, (short) 8);
fputs(" ", stdout);
//tab(32);
#ifdef BB_FEATURE_LS_TIMESTAMPS
{
time_t cal;
char *string;
switch(time_fmt) {
switch (time_fmt) {
case TIME_CHANGE:
cal=info->st_ctime; break;
cal = info->st_ctime;
break;
case TIME_ACCESS:
cal=info->st_atime; break;
cal = info->st_atime;
break;
default:
cal=info->st_mtime; break;
cal = info->st_mtime;
break;
}
string=ctime(&cal);
string = ctime(&cal);
if (opts & DISP_FULLTIME)
wr(string,24);
wr(string, 24);
else {
time_t age = time(NULL) - cal;
wr(string+4,7); /* mmm_dd_ */
if(age < 3600L*24*365/2 && age > -15*60)
wr(string + 4, 7); /* mmm_dd_ */
if (age < 3600L * 24 * 365 / 2 && age > -15 * 60)
/* hh:mm if less than 6 months old */
wr(string+11,5);
wr(string + 11, 5);
else
/* _yyyy otherwise */
wr(string+19,5);
wr(string + 19, 5);
}
wr(" ", 1);
}
@ -269,7 +276,8 @@ static void list_single(const char *name, struct stat *info, const char *fullnam
if (S_ISLNK(mode)) {
wr(" -> ", 4);
len = readlink(fullname, scratch, sizeof scratch);
if (len > 0) fwrite(scratch, 1, len, stdout);
if (len > 0)
fwrite(scratch, 1, len, stdout);
#ifdef BB_FEATURE_LS_FILETYPES
/* show type of destination */
if (opts & DISP_FTYPE) {
@ -287,18 +295,17 @@ static void list_single(const char *name, struct stat *info, const char *fullnam
#endif
} else {
static short nexttab = 0;
/* sort out column alignment */
if (column == 0)
; /* nothing to do */
if (column == 0); /* nothing to do */
else if (display_fmt == FMT_SINGLE)
newline();
else {
if (nexttab + column_width > terminal_width
#ifndef BB_FEATURE_AUTOWIDTH
|| nexttab + len >= terminal_width
|| nexttab + len >= terminal_width
#endif
)
)
newline();
else
tab(nexttab);
@ -336,32 +343,33 @@ static int list_item(const char *name)
struct stat info;
DIR *dir;
struct dirent *entry;
char fullname[MAXNAMLEN+1], *fnend;
char fullname[MAXNAMLEN + 1], *fnend;
if (lstat(name, &info))
goto listerr;
if (!S_ISDIR(info.st_mode) ||
(opts & DIR_NOLIST)) {
if (!S_ISDIR(info.st_mode) || (opts & DIR_NOLIST)) {
list_single(name, &info, name);
return 0;
}
/* Otherwise, it's a directory we want to list the contents of */
if (opts & DISP_DIRNAME) { /* identify the directory */
if (opts & DISP_DIRNAME) { /* identify the directory */
if (column)
wr("\n\n", 2), column = 0;
wr(name, strlen(name));
wr(":\n", 2);
}
dir = opendir(name);
if (!dir) goto listerr;
if (!dir)
goto listerr;
#ifdef BB_FEATURE_AUTOWIDTH
column_width = 0;
while ((entry = readdir(dir)) != NULL) {
short w = strlen(entry->d_name);
if (column_width < w)
column_width = w;
}
@ -370,39 +378,40 @@ static int list_item(const char *name)
#else
closedir(dir);
dir = opendir(name);
if (!dir) goto listerr;
if (!dir)
goto listerr;
#endif
#endif
/* List the contents */
strcpy(fullname,name); /* *** ignore '.' by itself */
fnend=fullname+strlen(fullname);
strcpy(fullname, name); /* *** ignore '.' by itself */
fnend = fullname + strlen(fullname);
if (fnend[-1] != '/')
*fnend++ = '/';
while ((entry = readdir(dir)) != NULL) {
const char *en=entry->d_name;
const char *en = entry->d_name;
if (en[0] == '.') {
if (!en[1] || (en[1] == '.' && !en[2])) { /* . or .. */
if (!en[1] || (en[1] == '.' && !en[2])) { /* . or .. */
if (!(opts & DISP_DOT))
continue;
}
else if (!(opts & DISP_HIDDEN))
} else if (!(opts & DISP_HIDDEN))
continue;
}
/* FIXME: avoid stat if not required */
strcpy(fnend, entry->d_name);
if (lstat(fullname, &info))
goto direrr; /* (shouldn't fail) */
goto direrr; /* (shouldn't fail) */
list_single(entry->d_name, &info, fullname);
}
closedir(dir);
return 0;
direrr:
closedir(dir);
listerr:
direrr:
closedir(dir);
listerr:
newline();
perror(name);
return 1;
@ -432,50 +441,79 @@ static const char ls_usage[] = "ls [-1a"
#endif
"] [filenames...]\n";
extern int
ls_main(int argc, char * * argv)
extern int ls_main(int argc, char **argv)
{
int argi=1, i;
int argi = 1, i;
/* process options */
while (argi < argc && argv[argi][0] == '-') {
const char *p = &argv[argi][1];
if (!*p) goto print_usage_message; /* "-" by itself not allowed */
if (!*p)
goto print_usage_message; /* "-" by itself not allowed */
if (*p == '-') {
if (!p[1]) { /* "--" forces end of options */
if (!p[1]) { /* "--" forces end of options */
argi++;
break;
}
/* it's a long option name - we don't support them */
goto print_usage_message;
}
while (*p)
switch (*p++) {
case 'l': display_fmt = FMT_LONG; break;
case '1': display_fmt = FMT_SINGLE; break;
case 'x': display_fmt = FMT_ROWS; break;
case 'C': display_fmt = FMT_COLUMNS; break;
case 'l':
display_fmt = FMT_LONG;
break;
case '1':
display_fmt = FMT_SINGLE;
break;
case 'x':
display_fmt = FMT_ROWS;
break;
case 'C':
display_fmt = FMT_COLUMNS;
break;
#ifdef BB_FEATURE_LS_FILETYPES
case 'p': opts |= DISP_FTYPE; break;
case 'F': opts |= DISP_FTYPE|DISP_EXEC; break;
case 'p':
opts |= DISP_FTYPE;
break;
case 'F':
opts |= DISP_FTYPE | DISP_EXEC;
break;
#endif
case 'A': opts |= DISP_HIDDEN; break;
case 'a': opts |= DISP_HIDDEN|DISP_DOT; break;
case 'n': opts |= DISP_NUMERIC; break;
case 'd': opts |= DIR_NOLIST; break;
case 'A':
opts |= DISP_HIDDEN;
break;
case 'a':
opts |= DISP_HIDDEN | DISP_DOT;
break;
case 'n':
opts |= DISP_NUMERIC;
break;
case 'd':
opts |= DIR_NOLIST;
break;
#ifdef FEATURE_RECURSIVE
case 'R': opts |= DIR_RECURSE; break;
case 'R':
opts |= DIR_RECURSE;
break;
#endif
#ifdef BB_FEATURE_LS_TIMESTAMPS
case 'u': time_fmt = TIME_ACCESS; break;
case 'c': time_fmt = TIME_CHANGE; break;
case 'e': opts |= DISP_FULLTIME; break;
case 'u':
time_fmt = TIME_ACCESS;
break;
case 'c':
time_fmt = TIME_CHANGE;
break;
case 'e':
opts |= DISP_FULLTIME;
break;
#endif
default: goto print_usage_message;
default:
goto print_usage_message;
}
argi++;
}
@ -483,29 +521,30 @@ ls_main(int argc, char * * argv)
if (display_fmt == FMT_AUTO)
display_fmt = isatty(fileno(stdout)) ? FMT_COLUMNS : FMT_SINGLE;
if (argi < argc - 1)
opts |= DISP_DIRNAME; /* 2 or more items? label directories */
opts |= DISP_DIRNAME; /* 2 or more items? label directories */
#ifdef BB_FEATURE_AUTOWIDTH
/* could add a -w option and/or TIOCGWINSZ call */
if (terminal_width < 1) terminal_width = TERMINAL_WIDTH;
if (terminal_width < 1)
terminal_width = TERMINAL_WIDTH;
for (i = argi; i < argc; i++) {
int len = strlen(argv[i]);
if (column_width < len)
column_width = len;
}
#endif
/* process files specified, or current directory if none */
i=0;
i = 0;
if (argi == argc)
i = list_item(".");
while (argi < argc)
i |= list_item(argv[argi++]);
newline();
exit( i);
exit(i);
print_usage_message:
usage (ls_usage);
exit( FALSE);
print_usage_message:
usage(ls_usage);
exit(FALSE);
}

View File

@ -1,3 +1,4 @@
/* vi: set sw=4 ts=4: */
/*
* Mini mkdir implementation for busybox
*
@ -28,14 +29,15 @@
#include <stdio.h>
#include <errno.h>
#include <sys/param.h> /* for PATH_MAX */
#include <sys/param.h> /* for PATH_MAX */
static const char mkdir_usage[] =
"mkdir [OPTION] DIRECTORY...\n\n"
"Create the DIRECTORY(ies), if they do not already exist\n\n"
"Options:\n"
"\t-m\tset permission mode (as in chmod), not rwxrwxrwx - umask\n"
"\t-p\tno error if existing, make parent directories as needed\n";
"mkdir [OPTION] DIRECTORY...\n\n"
"Create the DIRECTORY(ies), if they do not already exist\n\n"
"Options:\n"
"\t-m\tset permission mode (as in chmod), not rwxrwxrwx - umask\n"
"\t-p\tno error if existing, make parent directories as needed\n";
static int parentFlag = FALSE;
@ -44,71 +46,70 @@ static mode_t mode = 0777;
extern int mkdir_main(int argc, char **argv)
{
int i = FALSE;
argc--;
argv++;
int i = FALSE;
/* Parse any options */
while (argc > 0 && **argv == '-') {
while (i == FALSE && *++(*argv)) {
switch (**argv) {
case 'm':
if (--argc == 0)
usage( mkdir_usage);
/* Find the specified modes */
mode = 0;
if (parse_mode(*(++argv), &mode) == FALSE ) {
fprintf(stderr, "Unknown mode: %s\n", *argv);
exit FALSE;
argc--;
argv++;
/* Parse any options */
while (argc > 0 && **argv == '-') {
while (i == FALSE && *++(*argv)) {
switch (**argv) {
case 'm':
if (--argc == 0)
usage(mkdir_usage);
/* Find the specified modes */
mode = 0;
if (parse_mode(*(++argv), &mode) == FALSE) {
fprintf(stderr, "Unknown mode: %s\n", *argv);
exit FALSE;
}
/* Set the umask for this process so it doesn't
* screw up whatever the user just entered. */
umask(0);
i = TRUE;
break;
case 'p':
parentFlag = TRUE;
break;
default:
usage(mkdir_usage);
}
}
/* Set the umask for this process so it doesn't
* screw up whatever the user just entered. */
umask(0);
i = TRUE;
break;
case 'p':
parentFlag = TRUE;
break;
default:
usage( mkdir_usage);
}
argc--;
argv++;
}
argc--;
argv++;
}
if (argc < 1) {
usage( mkdir_usage);
}
if (argc < 1) {
usage(mkdir_usage);
}
while (argc > 0) {
int status;
struct stat statBuf;
char buf[PATH_MAX + 1];
if (strlen(*argv) > PATH_MAX - 1) {
fprintf(stderr, name_too_long, "mkdir");
exit FALSE;
while (argc > 0) {
int status;
struct stat statBuf;
char buf[PATH_MAX + 1];
if (strlen(*argv) > PATH_MAX - 1) {
fprintf(stderr, name_too_long, "mkdir");
exit FALSE;
}
strcpy(buf, *argv);
status = stat(buf, &statBuf);
if (parentFlag == FALSE && status != -1 && errno != ENOENT) {
fprintf(stderr, "%s: File exists\n", buf);
exit FALSE;
}
if (parentFlag == TRUE) {
strcat(buf, "/");
createPath(buf, mode);
} else {
if (mkdir(buf, mode) != 0 && parentFlag == FALSE) {
perror(buf);
exit FALSE;
}
}
argc--;
argv++;
}
strcpy (buf, *argv);
status = stat(buf, &statBuf);
if (parentFlag == FALSE && status != -1 && errno != ENOENT) {
fprintf(stderr, "%s: File exists\n", buf);
exit FALSE;
}
if (parentFlag == TRUE) {
strcat( buf, "/");
createPath(buf, mode);
}
else {
if (mkdir (buf, mode) != 0 && parentFlag == FALSE) {
perror(buf);
exit FALSE;
}
}
argc--;
argv++;
}
exit TRUE;
exit TRUE;
}

View File

@ -1,3 +1,4 @@
/* vi: set sw=4 ts=4: */
/*
* Mini mkfifo implementation for busybox
*
@ -26,36 +27,43 @@
#include <errno.h>
static const char mkfifo_usage[] = "mkfifo [OPTIONS] name\n\n"
"Create the named fifo\n\n"
"Options:\n"
"\t-m\tcreate the fifo with the specified mode; default = a=rw-umask\n";
"Create the named fifo\n\n"
"Options:\n"
"\t-m\tcreate the fifo with the specified mode; default = a=rw-umask\n";
extern int mkfifo_main(int argc, char **argv)
{
char *thisarg;
mode_t mode = 0666;
argc--;
argv++;
char *thisarg;
mode_t mode = 0666;
/* Parse any options */
while (argc > 1) {
if (**argv != '-') usage(mkfifo_usage);
thisarg = *argv; thisarg++;
switch (*thisarg) {
case 'm':
argc--; argv++;
parse_mode(*argv, &mode);
break;
default:
usage (mkfifo_usage);
}
argc--; argv++;
}
if (argc < 1) usage (mkfifo_usage);
if (mkfifo(*argv, mode) < 0) {
perror("mkfifo");
exit(255);
} else {
exit(TRUE);
}
argc--;
argv++;
/* Parse any options */
while (argc > 1) {
if (**argv != '-')
usage(mkfifo_usage);
thisarg = *argv;
thisarg++;
switch (*thisarg) {
case 'm':
argc--;
argv++;
parse_mode(*argv, &mode);
break;
default:
usage(mkfifo_usage);
}
argc--;
argv++;
}
if (argc < 1)
usage(mkfifo_usage);
if (mkfifo(*argv, mode) < 0) {
perror("mkfifo");
exit(255);
} else {
exit(TRUE);
}
}

View File

@ -1,3 +1,4 @@
/* vi: set sw=4 ts=4: */
/*
* Mini mknod implementation for busybox
*
@ -28,22 +29,22 @@
#include <unistd.h>
static const char mknod_usage[] = "mknod NAME TYPE MAJOR MINOR\n\n"
"Make block or character special files.\n\n"
"TYPEs include:\n"
"\tb:\tMake a block (buffered) device.\n"
"\tc or u:\tMake a character (un-buffered) device.\n"
"\tp:\tMake a named pipe. Major and minor are ignored for named pipes.\n";
"Make block or character special files.\n\n"
"TYPEs include:\n"
"\tb:\tMake a block (buffered) device.\n"
int
mknod_main(int argc, char** argv)
"\tc or u:\tMake a character (un-buffered) device.\n"
"\tp:\tMake a named pipe. Major and minor are ignored for named pipes.\n";
int mknod_main(int argc, char **argv)
{
mode_t mode = 0;
dev_t dev = 0;
mode_t mode = 0;
dev_t dev = 0;
if ( argc != 5 || **(argv+1) == '-' ) {
usage (mknod_usage);
if (argc != 5 || **(argv + 1) == '-') {
usage(mknod_usage);
}
switch(argv[2][0]) {
switch (argv[2][0]) {
case 'c':
case 'u':
mode = S_IFCHR;
@ -55,21 +56,21 @@ mknod_main(int argc, char** argv)
mode = S_IFIFO;
break;
default:
usage (mknod_usage);
usage(mknod_usage);
}
if ( mode == S_IFCHR || mode == S_IFBLK ) {
if (mode == S_IFCHR || mode == S_IFBLK) {
dev = (atoi(argv[3]) << 8) | atoi(argv[4]);
if ( argc != 5 ) {
usage (mknod_usage);
if (argc != 5) {
usage(mknod_usage);
}
}
mode |= 0666;
if ( mknod(argv[1], mode, dev) != 0 ) {
if (mknod(argv[1], mode, dev) != 0) {
perror(argv[1]);
return( FALSE);
return (FALSE);
}
return( TRUE);
return (TRUE);
}

View File

@ -1,3 +1,4 @@
/* vi: set sw=4 ts=4: */
/* printf - format and print data
Copyright (C) 90, 91, 92, 93, 94, 95, 1996 Free Software Foundation, Inc.
@ -42,7 +43,7 @@
to convert all of the given arguments.
David MacKenzie <djm@gnu.ai.mit.edu> */
// 19990508 Busy Boxed! Dave Cinege
@ -84,11 +85,11 @@
#if !defined(S_ISSOCK) && defined(S_IFSOCK)
# define S_ISSOCK(m) (((m) & S_IFMT) == S_IFSOCK)
#endif
#if !defined(S_ISMPB) && defined(S_IFMPB) /* V7 */
#if !defined(S_ISMPB) && defined(S_IFMPB) /* V7 */
# define S_ISMPB(m) (((m) & S_IFMT) == S_IFMPB)
# define S_ISMPC(m) (((m) & S_IFMT) == S_IFMPC)
#endif
#if !defined(S_ISNWK) && defined(S_IFNWK) /* HP/UX */
#if !defined(S_ISNWK) && defined(S_IFNWK) /* HP/UX */
# define S_ISNWK(m) (((m) & S_IFMT) == S_IFNWK)
#endif
@ -121,407 +122,358 @@
#define hextobin(c) ((c)>='a'&&(c)<='f' ? (c)-'a'+10 : (c)>='A'&&(c)<='F' ? (c)-'A'+10 : (c)-'0')
#define octtobin(c) ((c) - '0')
static double xstrtod __P ((char *s));
static int print_esc __P ((char *escstart));
static int print_formatted __P ((char *format, int argc, char **argv));
static long xstrtol __P ((char *s));
static unsigned long xstrtoul __P ((char *s));
static void print_direc __P ((char *start, size_t length, int field_width, int precision, char *argument));
static void print_esc_char __P ((int c));
static void print_esc_string __P ((char *str));
static void verify __P ((char *s, char *end));
static double xstrtod __P((char *s));
static int print_esc __P((char *escstart));
static int print_formatted __P((char *format, int argc, char **argv));
static long xstrtol __P((char *s));
static unsigned long xstrtoul __P((char *s));
static void print_direc
__P(
(char *start, size_t length, int field_width, int precision,
char *argument));
static void print_esc_char __P((int c));
static void print_esc_string __P((char *str));
static void verify __P((char *s, char *end));
/* The value to return to the calling program. */
static int exit_status;
static const char printf_usage[] = "printf format [argument...]\n";
static const char printf_usage[] = "printf format [argument...]\n";
int
printf_main(int argc, char** argv)
int printf_main(int argc, char **argv)
{
char *format;
int args_used;
char *format;
int args_used;
exit_status = 0;
if ( argc <= 1 || **(argv+1) == '-' ) {
usage (printf_usage);
}
exit_status = 0;
if (argc <= 1 || **(argv + 1) == '-') {
usage(printf_usage);
}
format = argv[1];
argc -= 2;
argv += 2;
format = argv[1];
argc -= 2;
argv += 2;
do
{
args_used = print_formatted (format, argc, argv);
argc -= args_used;
argv += args_used;
}
while (args_used > 0 && argc > 0);
do {
args_used = print_formatted(format, argc, argv);
argc -= args_used;
argv += args_used;
}
while (args_used > 0 && argc > 0);
/*
if (argc > 0)
fprintf(stderr, "excess args ignored");
*/
exit (exit_status);
exit(exit_status);
}
/* Print the text in FORMAT, using ARGV (with ARGC elements) for
arguments to any `%' directives.
Return the number of elements of ARGV used. */
static int
print_formatted (char *format, int argc, char **argv)
static int print_formatted(char *format, int argc, char **argv)
{
int save_argc = argc; /* Preserve original value. */
char *f; /* Pointer into `format'. */
char *direc_start; /* Start of % directive. */
size_t direc_length; /* Length of % directive. */
int field_width; /* Arg to first '*', or -1 if none. */
int precision; /* Arg to second '*', or -1 if none. */
int save_argc = argc; /* Preserve original value. */
char *f; /* Pointer into `format'. */
char *direc_start; /* Start of % directive. */
size_t direc_length; /* Length of % directive. */
int field_width; /* Arg to first '*', or -1 if none. */
int precision; /* Arg to second '*', or -1 if none. */
for (f = format; *f; ++f)
{
switch (*f)
{
case '%':
direc_start = f++;
direc_length = 1;
field_width = precision = -1;
if (*f == '%')
{
putchar ('%');
break;
}
if (*f == 'b')
{
if (argc > 0)
{
print_esc_string (*argv);
++argv;
--argc;
}
break;
}
if (strchr ("-+ #", *f))
{
++f;
++direc_length;
}
if (*f == '*')
{
++f;
++direc_length;
if (argc > 0)
{
field_width = xstrtoul (*argv);
++argv;
--argc;
}
else
field_width = 0;
}
else
while (ISDIGIT (*f))
{
++f;
++direc_length;
}
if (*f == '.')
{
++f;
++direc_length;
if (*f == '*')
{
++f;
++direc_length;
if (argc > 0)
{
precision = xstrtoul (*argv);
++argv;
--argc;
}
else
precision = 0;
}
else
while (ISDIGIT (*f))
{
++f;
++direc_length;
}
}
if (*f == 'l' || *f == 'L' || *f == 'h')
{
++f;
++direc_length;
}
/*
if (!strchr ("diouxXfeEgGcs", *f))
fprintf(stderr, "%%%c: invalid directive", *f);
*/
++direc_length;
if (argc > 0)
{
print_direc (direc_start, direc_length, field_width,
precision, *argv);
++argv;
--argc;
}
else
print_direc (direc_start, direc_length, field_width,
precision, "");
break;
for (f = format; *f; ++f) {
switch (*f) {
case '%':
direc_start = f++;
direc_length = 1;
field_width = precision = -1;
if (*f == '%') {
putchar('%');
break;
}
if (*f == 'b') {
if (argc > 0) {
print_esc_string(*argv);
++argv;
--argc;
}
break;
}
if (strchr("-+ #", *f)) {
++f;
++direc_length;
}
if (*f == '*') {
++f;
++direc_length;
if (argc > 0) {
field_width = xstrtoul(*argv);
++argv;
--argc;
} else
field_width = 0;
} else
while (ISDIGIT(*f)) {
++f;
++direc_length;
}
if (*f == '.') {
++f;
++direc_length;
if (*f == '*') {
++f;
++direc_length;
if (argc > 0) {
precision = xstrtoul(*argv);
++argv;
--argc;
} else
precision = 0;
} else
while (ISDIGIT(*f)) {
++f;
++direc_length;
}
}
if (*f == 'l' || *f == 'L' || *f == 'h') {
++f;
++direc_length;
}
/*
if (!strchr ("diouxXfeEgGcs", *f))
fprintf(stderr, "%%%c: invalid directive", *f);
*/
++direc_length;
if (argc > 0) {
print_direc(direc_start, direc_length, field_width,
precision, *argv);
++argv;
--argc;
} else
print_direc(direc_start, direc_length, field_width,
precision, "");
break;
case '\\':
f += print_esc (f);
break;
case '\\':
f += print_esc(f);
break;
default:
putchar (*f);
default:
putchar(*f);
}
}
}
return save_argc - argc;
return save_argc - argc;
}
/* Print a \ escape sequence starting at ESCSTART.
Return the number of characters in the escape sequence
besides the backslash. */
static int
print_esc (char *escstart)
static int print_esc(char *escstart)
{
register char *p = escstart + 1;
int esc_value = 0; /* Value of \nnn escape. */
int esc_length; /* Length of \nnn escape. */
register char *p = escstart + 1;
int esc_value = 0; /* Value of \nnn escape. */
int esc_length; /* Length of \nnn escape. */
/* \0ooo and \xhhh escapes have maximum length of 3 chars. */
if (*p == 'x')
{
for (esc_length = 0, ++p;
esc_length < 3 && ISXDIGIT (*p);
++esc_length, ++p)
esc_value = esc_value * 16 + hextobin (*p);
/* \0ooo and \xhhh escapes have maximum length of 3 chars. */
if (*p == 'x') {
for (esc_length = 0, ++p;
esc_length < 3 && ISXDIGIT(*p); ++esc_length, ++p)
esc_value = esc_value * 16 + hextobin(*p);
/* if (esc_length == 0)
fprintf(stderr, "missing hex in esc");
*/
putchar (esc_value);
}
else if (*p == '0')
{
for (esc_length = 0, ++p;
esc_length < 3 && isodigit (*p);
++esc_length, ++p)
esc_value = esc_value * 8 + octtobin (*p);
putchar (esc_value);
}
else if (strchr ("\"\\abcfnrtv", *p))
print_esc_char (*p++);
putchar(esc_value);
} else if (*p == '0') {
for (esc_length = 0, ++p;
esc_length < 3 && isodigit(*p); ++esc_length, ++p)
esc_value = esc_value * 8 + octtobin(*p);
putchar(esc_value);
} else if (strchr("\"\\abcfnrtv", *p))
print_esc_char(*p++);
/* else
fprintf(stderr, "\\%c: invalid esc", *p);
*/
return p - escstart - 1;
return p - escstart - 1;
}
/* Output a single-character \ escape. */
static void
print_esc_char (int c)
static void print_esc_char(int c)
{
switch (c)
{
case 'a': /* Alert. */
putchar (7);
break;
case 'b': /* Backspace. */
putchar (8);
break;
case 'c': /* Cancel the rest of the output. */
exit (0);
break;
case 'f': /* Form feed. */
putchar (12);
break;
case 'n': /* New line. */
putchar (10);
break;
case 'r': /* Carriage return. */
putchar (13);
break;
case 't': /* Horizontal tab. */
putchar (9);
break;
case 'v': /* Vertical tab. */
putchar (11);
break;
default:
putchar (c);
break;
}
switch (c) {
case 'a': /* Alert. */
putchar(7);
break;
case 'b': /* Backspace. */
putchar(8);
break;
case 'c': /* Cancel the rest of the output. */
exit(0);
break;
case 'f': /* Form feed. */
putchar(12);
break;
case 'n': /* New line. */
putchar(10);
break;
case 'r': /* Carriage return. */
putchar(13);
break;
case 't': /* Horizontal tab. */
putchar(9);
break;
case 'v': /* Vertical tab. */
putchar(11);
break;
default:
putchar(c);
break;
}
}
/* Print string STR, evaluating \ escapes. */
static void
print_esc_string (char *str)
static void print_esc_string(char *str)
{
for (; *str; str++)
if (*str == '\\')
str += print_esc (str);
else
putchar (*str);
for (; *str; str++)
if (*str == '\\')
str += print_esc(str);
else
putchar(*str);
}
static void
print_direc (char *start, size_t length, int field_width, int precision, char *argument)
print_direc(char *start, size_t length, int field_width, int precision,
char *argument)
{
char *p; /* Null-terminated copy of % directive. */
char *p; /* Null-terminated copy of % directive. */
p = xmalloc ((unsigned) (length + 1));
strncpy (p, start, length);
p[length] = 0;
p = xmalloc((unsigned) (length + 1));
strncpy(p, start, length);
p[length] = 0;
switch (p[length - 1])
{
case 'd':
case 'i':
if (field_width < 0)
{
if (precision < 0)
printf (p, xstrtol (argument));
else
printf (p, precision, xstrtol (argument));
}
else
{
if (precision < 0)
printf (p, field_width, xstrtol (argument));
else
printf (p, field_width, precision, xstrtol (argument));
}
break;
switch (p[length - 1]) {
case 'd':
case 'i':
if (field_width < 0) {
if (precision < 0)
printf(p, xstrtol(argument));
else
printf(p, precision, xstrtol(argument));
} else {
if (precision < 0)
printf(p, field_width, xstrtol(argument));
else
printf(p, field_width, precision, xstrtol(argument));
}
break;
case 'o':
case 'u':
case 'x':
case 'X':
if (field_width < 0)
{
if (precision < 0)
printf (p, xstrtoul (argument));
else
printf (p, precision, xstrtoul (argument));
}
else
{
if (precision < 0)
printf (p, field_width, xstrtoul (argument));
else
printf (p, field_width, precision, xstrtoul (argument));
}
break;
case 'o':
case 'u':
case 'x':
case 'X':
if (field_width < 0) {
if (precision < 0)
printf(p, xstrtoul(argument));
else
printf(p, precision, xstrtoul(argument));
} else {
if (precision < 0)
printf(p, field_width, xstrtoul(argument));
else
printf(p, field_width, precision, xstrtoul(argument));
}
break;
case 'f':
case 'e':
case 'E':
case 'g':
case 'G':
if (field_width < 0)
{
if (precision < 0)
printf (p, xstrtod (argument));
else
printf (p, precision, xstrtod (argument));
}
else
{
if (precision < 0)
printf (p, field_width, xstrtod (argument));
else
printf (p, field_width, precision, xstrtod (argument));
}
break;
case 'f':
case 'e':
case 'E':
case 'g':
case 'G':
if (field_width < 0) {
if (precision < 0)
printf(p, xstrtod(argument));
else
printf(p, precision, xstrtod(argument));
} else {
if (precision < 0)
printf(p, field_width, xstrtod(argument));
else
printf(p, field_width, precision, xstrtod(argument));
}
break;
case 'c':
printf (p, *argument);
break;
case 'c':
printf(p, *argument);
break;
case 's':
if (field_width < 0)
{
if (precision < 0)
printf (p, argument);
else
printf (p, precision, argument);
case 's':
if (field_width < 0) {
if (precision < 0)
printf(p, argument);
else
printf(p, precision, argument);
} else {
if (precision < 0)
printf(p, field_width, argument);
else
printf(p, field_width, precision, argument);
}
break;
}
else
{
if (precision < 0)
printf (p, field_width, argument);
else
printf (p, field_width, precision, argument);
}
break;
}
free (p);
free(p);
}
static unsigned long
xstrtoul (char *s)
static unsigned long xstrtoul(char *s)
{
char *end;
unsigned long val;
char *end;
unsigned long val;
errno = 0;
val = strtoul (s, &end, 0);
verify (s, end);
return val;
errno = 0;
val = strtoul(s, &end, 0);
verify(s, end);
return val;
}
static long
xstrtol (char *s)
static long xstrtol(char *s)
{
char *end;
long val;
char *end;
long val;
errno = 0;
val = strtol (s, &end, 0);
verify (s, end);
return val;
errno = 0;
val = strtol(s, &end, 0);
verify(s, end);
return val;
}
static double
xstrtod (char *s)
static double xstrtod(char *s)
{
char *end;
double val;
char *end;
double val;
errno = 0;
val = strtod (s, &end);
verify (s, end);
return val;
errno = 0;
val = strtod(s, &end);
verify(s, end);
return val;
}
static void
verify (char *s, char *end)
static void verify(char *s, char *end)
{
if (errno)
{
fprintf(stderr, "%s", s);
exit_status = 1;
}
else if (*end)
{
/*
if (s == end)
fprintf(stderr, "%s: expected numeric", s);
else
fprintf(stderr, "%s: not completely converted", s);
*/
exit_status = 1;
}
if (errno) {
fprintf(stderr, "%s", s);
exit_status = 1;
} else if (*end) {
/*
if (s == end)
fprintf(stderr, "%s: expected numeric", s);
else
fprintf(stderr, "%s: not completely converted", s);
*/
exit_status = 1;
}
}

View File

@ -1,3 +1,4 @@
/* vi: set sw=4 ts=4: */
/*
* Mini pwd implementation for busybox
*
@ -25,16 +26,15 @@
#include <dirent.h>
#include <sys/param.h>
extern int
pwd_main(int argc, char * * argv)
extern int pwd_main(int argc, char **argv)
{
char buf[PATH_MAX + 1];
char buf[PATH_MAX + 1];
if ( getcwd(buf, sizeof(buf)) == NULL ) {
if (getcwd(buf, sizeof(buf)) == NULL) {
perror("get working directory");
exit( FALSE);
exit(FALSE);
}
printf("%s\n", buf);
exit( TRUE);
exit(TRUE);
}

View File

@ -1,3 +1,4 @@
/* vi: set sw=4 ts=4: */
/*
* Mini rm implementation for busybox
*
@ -28,11 +29,12 @@
#include <dirent.h>
#include <errno.h>
static const char* rm_usage = "rm [OPTION]... FILE...\n\n"
"Remove (unlink) the FILE(s).\n\n"
"Options:\n"
"\t-f\t\tremove existing destinations, never prompt\n"
"\t-r or -R\tremove the contents of directories recursively\n";
static const char *rm_usage = "rm [OPTION]... FILE...\n\n"
"Remove (unlink) the FILE(s).\n\n"
"Options:\n"
"\t-f\t\tremove existing destinations, never prompt\n"
"\t-r or -R\tremove the contents of directories recursively\n";
static int recursiveFlag = FALSE;
@ -40,63 +42,63 @@ static int forceFlag = FALSE;
static const char *srcName;
static int fileAction(const char *fileName, struct stat* statbuf)
static int fileAction(const char *fileName, struct stat *statbuf)
{
if (unlink( fileName) < 0 ) {
perror( fileName);
return ( FALSE);
}
return ( TRUE);
if (unlink(fileName) < 0) {
perror(fileName);
return (FALSE);
}
return (TRUE);
}
static int dirAction(const char *fileName, struct stat* statbuf)
static int dirAction(const char *fileName, struct stat *statbuf)
{
if (rmdir( fileName) < 0 ) {
perror( fileName);
return ( FALSE);
}
return ( TRUE);
if (rmdir(fileName) < 0) {
perror(fileName);
return (FALSE);
}
return (TRUE);
}
extern int rm_main(int argc, char **argv)
{
struct stat statbuf;
struct stat statbuf;
if (argc < 2) {
usage( rm_usage);
}
argc--;
argv++;
/* Parse any options */
while (**argv == '-') {
while (*++(*argv))
switch (**argv) {
case 'R':
case 'r':
recursiveFlag = TRUE;
break;
case 'f':
forceFlag = TRUE;
break;
default:
usage( rm_usage);
}
if (argc < 2) {
usage(rm_usage);
}
argc--;
argv++;
}
while (argc-- > 0) {
srcName = *(argv++);
if (forceFlag == TRUE && lstat(srcName, &statbuf) != 0 && errno == ENOENT) {
/* do not reports errors for non-existent files if -f, just skip them */
/* Parse any options */
while (**argv == '-') {
while (*++(*argv))
switch (**argv) {
case 'R':
case 'r':
recursiveFlag = TRUE;
break;
case 'f':
forceFlag = TRUE;
break;
default:
usage(rm_usage);
}
argc--;
argv++;
}
else {
if (recursiveAction( srcName, recursiveFlag, FALSE,
TRUE, fileAction, dirAction) == FALSE) {
exit( FALSE);
}
while (argc-- > 0) {
srcName = *(argv++);
if (forceFlag == TRUE && lstat(srcName, &statbuf) != 0
&& errno == ENOENT) {
/* do not reports errors for non-existent files if -f, just skip them */
} else {
if (recursiveAction(srcName, recursiveFlag, FALSE,
TRUE, fileAction, dirAction) == FALSE) {
exit(FALSE);
}
}
}
}
exit( TRUE);
exit(TRUE);
}

View File

@ -1,3 +1,4 @@
/* vi: set sw=4 ts=4: */
/*
* Mini rmdir implementation for busybox
*
@ -28,15 +29,16 @@
extern int rmdir_main(int argc, char **argv)
{
if ( argc==1 || **(argv+1) == '-' ) {
usage( "rmdir [OPTION]... DIRECTORY...\n\nRemove the DIRECTORY(ies), if they are empty.\n");
}
while (--argc > 0) {
if ( rmdir(*(++argv)) == -1 ) {
fprintf(stderr, "%s: %s\n", *argv, strerror(errno));
exit(FALSE);
if (argc == 1 || **(argv + 1) == '-') {
usage
("rmdir [OPTION]... DIRECTORY...\n\nRemove the DIRECTORY(ies), if they are empty.\n");
}
}
exit(TRUE);
while (--argc > 0) {
if (rmdir(*(++argv)) == -1) {
fprintf(stderr, "%s: %s\n", *argv, strerror(errno));
exit(FALSE);
}
}
exit(TRUE);
}

View File

@ -1,3 +1,4 @@
/* vi: set sw=4 ts=4: */
/*
* Mini sleep implementation for busybox
*
@ -23,19 +24,17 @@
#include "internal.h"
#include <stdio.h>
const char sleep_usage[] = "sleep N\n\n"
"Pause for N seconds.\n";
const char sleep_usage[] = "sleep N\n\n" "Pause for N seconds.\n";
extern int
sleep_main(int argc, char * * argv)
extern int sleep_main(int argc, char **argv)
{
if ( (argc < 2) || (**(argv+1) == '-') ) {
usage( sleep_usage );
if ((argc < 2) || (**(argv + 1) == '-')) {
usage(sleep_usage);
}
if ( sleep(atoi(*(++argv))) != 0 ) {
perror( "sleep");
exit (FALSE);
if (sleep(atoi(*(++argv))) != 0) {
perror("sleep");
exit(FALSE);
} else
exit (TRUE);
exit(TRUE);
}

View File

@ -1,3 +1,4 @@
/* vi: set sw=4 ts=4: */
/*
* Mini sort implementation for busybox
*
@ -28,29 +29,27 @@
#include <stdio.h>
#include <errno.h>
static const char sort_usage[] =
"sort [OPTION]... [FILE]...\n\n"
;
static const char sort_usage[] = "sort [OPTION]... [FILE]...\n\n";
/* typedefs _______________________________________________________________ */
/* line node */
typedef struct Line {
char *data; /* line data */
struct Line *next; /* pointer to next line node */
char *data; /* line data */
struct Line *next; /* pointer to next line node */
} Line;
/* singly-linked list of lines */
typedef struct {
int len; /* number of Lines */
Line **sorted; /* array fed to qsort */
int len; /* number of Lines */
Line **sorted; /* array fed to qsort */
Line *head; /* head of List */
Line *current; /* current Line */
Line *head; /* head of List */
Line *current; /* current Line */
} List;
/* comparison function */
typedef int (Compare)(const void *, const void *);
typedef int (Compare) (const void *, const void *);
/* methods ________________________________________________________________ */
@ -58,175 +57,176 @@ typedef int (Compare)(const void *, const void *);
static const int max = 1024;
/* mallocate Line */
static Line *
line_alloc()
static Line *line_alloc()
{
Line *self;
self = malloc(1 * sizeof(Line));
return self;
Line *self;
self = malloc(1 * sizeof(Line));
return self;
}
/* Initialize Line with string */
static Line *
line_init(Line *self, const char *string)
static Line *line_init(Line * self, const char *string)
{
self->data = malloc((strlen(string) + 1) * sizeof(char));
if (self->data == NULL) { return NULL; }
strcpy(self->data, string);
self->next = NULL;
return self;
self->data = malloc((strlen(string) + 1) * sizeof(char));
if (self->data == NULL) {
return NULL;
}
strcpy(self->data, string);
self->next = NULL;
return self;
}
/* Construct Line from FILE* */
static Line *
line_newFromFile(FILE *src)
static Line *line_newFromFile(FILE * src)
{
char buffer[max];
Line *self;
char buffer[max];
Line *self;
if (fgets(buffer, max, src)) {
self = line_alloc();
if (self == NULL) { return NULL; }
line_init(self, buffer);
return self;
}
return NULL;
if (fgets(buffer, max, src)) {
self = line_alloc();
if (self == NULL) {
return NULL;
}
line_init(self, buffer);
return self;
}
return NULL;
}
/* Line destructor */
static Line *
line_release(Line *self)
static Line *line_release(Line * self)
{
if (self->data) {
free(self->data);
free(self);
}
return self;
if (self->data) {
free(self->data);
free(self);
}
return self;
}
/* Comparison */
/* ascii order */
static int
compare_ascii(const void *a, const void *b)
static int compare_ascii(const void *a, const void *b)
{
Line **doh;
Line *x, *y;
Line **doh;
Line *x, *y;
doh = (Line **) a;
x = *doh;
doh = (Line **) b;
y = *doh;
doh = (Line **) a;
x = *doh;
doh = (Line **) b;
y = *doh;
// fprintf(stdout, "> %p: %s< %p: %s", x, x->data, y, y->data);
return strcmp(x->data, y->data);
// fprintf(stdout, "> %p: %s< %p: %s", x, x->data, y, y->data);
return strcmp(x->data, y->data);
}
/* numeric order */
static int
compare_numeric(const void *a, const void *b)
static int compare_numeric(const void *a, const void *b)
{
Line **doh;
Line *x, *y;
int xint, yint;
Line **doh;
Line *x, *y;
int xint, yint;
doh = (Line **) a;
x = *doh;
doh = (Line **) b;
y = *doh;
doh = (Line **) a;
x = *doh;
doh = (Line **) b;
y = *doh;
xint = strtoul(x->data, NULL, 10);
yint = strtoul(y->data, NULL, 10);
xint = strtoul(x->data, NULL, 10);
yint = strtoul(y->data, NULL, 10);
return (xint - yint);
return (xint - yint);
}
/* List */
/* */
static List *
list_init(List *self)
static List *list_init(List * self)
{
self->len = 0;
self->sorted = NULL;
self->head = NULL;
self->current = NULL;
return self;
self->len = 0;
self->sorted = NULL;
self->head = NULL;
self->current = NULL;
return self;
}
/* for simplicity, the List gains ownership of the line */
static List *
list_insert(List *self, Line *line)
static List *list_insert(List * self, Line * line)
{
if (line == NULL) { return NULL; }
if (line == NULL) {
return NULL;
}
/* first insertion */
if (self->head == NULL) {
self->head = line;
self->current = line;
/* first insertion */
if (self->head == NULL) {
self->head = line;
self->current = line;
/* all subsequent insertions */
} else {
self->current->next = line;
self->current = line;
}
self->len++;
return self;
/* all subsequent insertions */
} else {
self->current->next = line;
self->current = line;
}
self->len++;
return self;
}
/* order the list according to compare() */
static List *
list_sort(List *self, Compare *compare)
static List *list_sort(List * self, Compare * compare)
{
int i;
Line *line;
int i;
Line *line;
/* mallocate array of Line*s */
self->sorted = (Line **) malloc(self->len * sizeof(Line*));
if (self->sorted == NULL) { return NULL; }
/* mallocate array of Line*s */
self->sorted = (Line **) malloc(self->len * sizeof(Line *));
if (self->sorted == NULL) {
return NULL;
}
/* fill array w/ List's contents */
i = 0;
line = self->head;
while (line) {
self->sorted[i++] = line;
line = line->next;
}
/* fill array w/ List's contents */
i = 0;
line = self->head;
while (line) {
self->sorted[i++] = line;
line = line->next;
}
/* apply qsort */
qsort(self->sorted, self->len, sizeof(Line*), compare);
return self;
/* apply qsort */
qsort(self->sorted, self->len, sizeof(Line *), compare);
return self;
}
/* precondition: list must be sorted */
static List *
list_writeToFile(List *self, FILE* dst)
static List *list_writeToFile(List * self, FILE * dst)
{
int i;
Line **line = self->sorted;
int i;
Line **line = self->sorted;
if (self->sorted == NULL) { return NULL; }
for (i = 0; i < self->len; i++) {
fprintf(dst, "%s", line[i]->data);
}
return self;
if (self->sorted == NULL) {
return NULL;
}
for (i = 0; i < self->len; i++) {
fprintf(dst, "%s", line[i]->data);
}
return self;
}
/* deallocate */
static void
list_release(List *self)
static void list_release(List * self)
{
Line *i;
Line *die;
Line *i;
Line *die;
i = self->head;
while (i) {
die = i;
i = die->next;
line_release(die);
}
i = self->head;
while (i) {
die = i;
i = die->next;
line_release(die);
}
}
@ -237,76 +237,77 @@ list_release(List *self)
* and finally print it
*/
int
sort_main(int argc, char **argv)
int sort_main(int argc, char **argv)
{
int i;
char opt;
List list;
Line *l;
Compare *compare;
int i;
char opt;
List list;
Line *l;
Compare *compare;
/* init */
compare = compare_ascii;
list_init(&list);
/* init */
compare = compare_ascii;
list_init(&list);
/* parse argv[] */
for (i = 1; i < argc; i++) {
if (argv[i][0] == '-') {
opt = argv[i][1];
switch (opt) {
case 'g':
/* what's the diff between -g && -n? */
compare = compare_numeric;
break;
case 'h':
usage(sort_usage);
break;
case 'n':
/* what's the diff between -g && -n? */
compare = compare_numeric;
break;
case 'r':
/* reverse */
break;
default:
fprintf(stderr, "sort: invalid option -- %c\n", opt);
usage(sort_usage);
}
/* parse argv[] */
for (i = 1; i < argc; i++) {
if (argv[i][0] == '-') {
opt = argv[i][1];
switch (opt) {
case 'g':
/* what's the diff between -g && -n? */
compare = compare_numeric;
break;
case 'h':
usage(sort_usage);
break;
case 'n':
/* what's the diff between -g && -n? */
compare = compare_numeric;
break;
case 'r':
/* reverse */
break;
default:
fprintf(stderr, "sort: invalid option -- %c\n", opt);
usage(sort_usage);
}
} else {
break;
}
}
/* this could be factored better */
/* work w/ stdin */
if (i >= argc) {
while ((l = line_newFromFile(stdin))) {
list_insert(&list, l);
}
list_sort(&list, compare);
list_writeToFile(&list, stdout);
list_release(&list);
/* work w/ what's left in argv[] */
} else {
break;
FILE *src;
for (; i < argc; i++) {
src = fopen(argv[i], "r");
if (src == NULL) {
break;
}
while ((l = line_newFromFile(src))) {
list_insert(&list, l);
}
fclose(src);
}
list_sort(&list, compare);
list_writeToFile(&list, stdout);
list_release(&list);
}
}
/* this could be factored better */
/* work w/ stdin */
if (i >= argc) {
while ( (l = line_newFromFile(stdin))) {
list_insert(&list, l);
}
list_sort(&list, compare);
list_writeToFile(&list, stdout);
list_release(&list);
/* work w/ what's left in argv[] */
} else {
FILE *src;
for ( ; i < argc; i++) {
src = fopen(argv[i], "r");
if (src == NULL) { break; }
while ( (l = line_newFromFile(src))) {
list_insert(&list, l);
}
fclose(src);
}
list_sort(&list, compare);
list_writeToFile(&list, stdout);
list_release(&list);
}
exit(0);
exit(0);
}
/* $Id: sort.c,v 1.10 2000/02/07 05:29:42 erik Exp $ */
/* $Id: sort.c,v 1.11 2000/02/08 19:58:47 erik Exp $ */

View File

@ -1,3 +1,4 @@
/* vi: set sw=4 ts=4: */
/*
* Mini sync implementation for busybox
*
@ -23,12 +24,10 @@
#include "internal.h"
#include <stdio.h>
extern int
sync_main(int argc, char * * argv)
extern int sync_main(int argc, char **argv)
{
if ( argc>1 && **(argv+1) == '-' ) {
usage( "sync\n\nWrite all buffered filesystem blocks to disk.\n");
}
exit( sync());
if (argc > 1 && **(argv + 1) == '-') {
usage("sync\n\nWrite all buffered filesystem blocks to disk.\n");
}
exit(sync());
}

File diff suppressed because it is too large Load Diff

View File

@ -1,3 +1,4 @@
/* vi: set sw=4 ts=4: */
/*
* Mini tee implementation for busybox
*
@ -25,102 +26,100 @@
#include <stdio.h>
static const char tee_usage[] =
"tee [OPTION]... [FILE]...\n\n"
"Copy standard input to each FILE, and also to standard output.\n\n"
"Options:\n"
"\t-a\tappend to the given FILEs, do not overwrite\n"
"tee [OPTION]... [FILE]...\n\n"
"Copy standard input to each FILE, and also to standard output.\n\n"
"Options:\n" "\t-a\tappend to the given FILEs, do not overwrite\n"
#if 0
"\t-i\tignore interrupt signals\n"
"\t-i\tignore interrupt signals\n"
#endif
;
;
/* FileList _______________________________________________________________ */
#define FL_MAX 1024
static FILE *FileList[FL_MAX];
static int FL_end;
static int FL_end;
typedef void (FL_Function) (FILE * file, char c);
typedef void (FL_Function)(FILE *file, char c);
/* apply a function to everything in FileList */
static void
FL_apply(FL_Function *f, char c)
static void FL_apply(FL_Function * f, char c)
{
int i;
for (i = 0; i <= FL_end; i++) {
f(FileList[i], c);
}
int i;
for (i = 0; i <= FL_end; i++) {
f(FileList[i], c);
}
}
/* FL_Function for writing to files*/
static void
tee_fwrite(FILE *file, char c)
static void tee_fwrite(FILE * file, char c)
{
fputc(c, file);
fputc(c, file);
}
/* FL_Function for closing files */
static void
tee_fclose(FILE *file, char c)
static void tee_fclose(FILE * file, char c)
{
fclose(file);
fclose(file);
}
/* ________________________________________________________________________ */
/* BusyBoxed tee(1) */
int
tee_main(int argc, char **argv)
int tee_main(int argc, char **argv)
{
int i;
char c;
char opt;
char opt_fopen[2] = "w";
FILE *file;
int i;
char c;
char opt;
char opt_fopen[2] = "w";
FILE *file;
/* parse argv[] */
for (i = 1; i < argc; i++) {
if (argv[i][0] == '-') {
opt = argv[i][1];
switch (opt) {
case 'a':
opt_fopen[0] = 'a';
break;
/* parse argv[] */
for (i = 1; i < argc; i++) {
if (argv[i][0] == '-') {
opt = argv[i][1];
switch (opt) {
case 'a':
opt_fopen[0] = 'a';
break;
#if 0
case 'i':
fprintf(stderr, "ignore interrupt not implemented\n");
break;
case 'i':
fprintf(stderr, "ignore interrupt not implemented\n");
break;
#endif
default:
usage(tee_usage);
}
} else {
break;
default:
usage(tee_usage);
}
} else {
break;
}
}
}
/* init FILE pointers */
FL_end = 0;
FileList[0] = stdout;
for ( ; i < argc; i++) {
/* add a file to FileList */
file = fopen(argv[i], opt_fopen);
if (!file) { continue; }
if (FL_end < FL_MAX) {
FileList[++FL_end] = file;
/* init FILE pointers */
FL_end = 0;
FileList[0] = stdout;
for (; i < argc; i++) {
/* add a file to FileList */
file = fopen(argv[i], opt_fopen);
if (!file) {
continue;
}
if (FL_end < FL_MAX) {
FileList[++FL_end] = file;
}
}
}
/* read and redirect */
while ((c = (char) getchar()) && (!feof(stdin))) {
FL_apply(tee_fwrite, c);
}
/* read and redirect */
while ((c = (char) getchar()) && (!feof(stdin))) {
FL_apply(tee_fwrite, c);
}
/* clean up */
FL_apply(tee_fclose, 0);
exit(0);
/* clean up */
FL_apply(tee_fclose, 0);
exit(0);
}
/* $Id: tee.c,v 1.5 2000/02/07 05:29:42 erik Exp $ */
/* $Id: tee.c,v 1.6 2000/02/08 19:58:47 erik Exp $ */

View File

@ -1,3 +1,4 @@
/* vi: set sw=4 ts=4: */
/*
* Mini touch implementation for busybox
*
@ -31,56 +32,50 @@
static const char touch_usage[] = "touch [-c] file [file ...]\n\n"
"Update the last-modified date on the given file[s].\n";
"Update the last-modified date on the given file[s].\n";
extern int
touch_main(int argc, char **argv)
extern int touch_main(int argc, char **argv)
{
int fd;
int create=TRUE;
int fd;
int create = TRUE;
if (argc < 2) {
usage( touch_usage);
}
argc--;
argv++;
/* Parse options */
while (**argv == '-') {
while (*++(*argv)) switch (**argv) {
case 'c':
create = FALSE;
break;
default:
usage( touch_usage);
exit( FALSE);
if (argc < 2) {
usage(touch_usage);
}
argc--;
argv++;
}
fd = open (*argv, (create==FALSE)? O_RDWR : O_RDWR | O_CREAT, 0644);
if (fd < 0 ) {
if (create==FALSE && errno == ENOENT)
exit( TRUE);
else {
perror("touch");
exit( FALSE);
/* Parse options */
while (**argv == '-') {
while (*++(*argv))
switch (**argv) {
case 'c':
create = FALSE;
break;
default:
usage(touch_usage);
exit(FALSE);
}
argc--;
argv++;
}
}
close( fd);
if (utime (*argv, NULL)) {
perror("touch");
exit( FALSE);
}
else
exit( TRUE);
fd = open(*argv, (create == FALSE) ? O_RDWR : O_RDWR | O_CREAT, 0644);
if (fd < 0) {
if (create == FALSE && errno == ENOENT)
exit(TRUE);
else {
perror("touch");
exit(FALSE);
}
}
close(fd);
if (utime(*argv, NULL)) {
perror("touch");
exit(FALSE);
} else
exit(TRUE);
}

View File

@ -1,3 +1,4 @@
/* vi: set sw=4 ts=4: */
/*
* Mini tty implementation for busybox
*
@ -24,19 +25,23 @@
#include <sys/types.h>
static const char tty_usage[] = "tty\n\n"
"Print the file name of the terminal connected to standard input.\n"
"\t-s\tprint nothing, only return an exit status\n";
"Print the file name of the terminal connected to standard input.\n"
extern int tty_main(int argc, char **argv) {
"\t-s\tprint nothing, only return an exit status\n";
extern int tty_main(int argc, char **argv)
{
char *tty;
if (argc > 1) {
if (argv[1][0] != '-' || argv[1][1] != 's') usage (tty_usage);
if (argv[1][0] != '-' || argv[1][1] != 's')
usage(tty_usage);
} else {
tty = ttyname(0);
if (tty)
puts(tty);
else
puts("not a tty");
}
else {
tty = ttyname (0);
if (tty) puts (tty);
else puts ("not a tty");
}
exit (isatty (0) ? TRUE : FALSE);
exit(isatty(0) ? TRUE : FALSE);
}

View File

@ -1,3 +1,4 @@
/* vi: set sw=4 ts=4: */
/* uname -- print system information
Copyright (C) 1989-1999 Free Software Foundation, Inc.
@ -41,16 +42,17 @@
static const char uname_usage[] =
"uname [OPTION]...\n\n"
"Print certain system information. With no OPTION, same as -s.\n\n"
"Options:\n"
"\t-a\tprint all information\n"
"\t-m\tthe machine (hardware) type\n"
"\t-n\tprint the machine's network node hostname\n"
"\t-r\tprint the operating system release\n"
"\t-s\tprint the operating system name\n"
"\t-p\tprint the host processor type\n"
"\t-v\tprint the operating system version\n";
"uname [OPTION]...\n\n"
"Print certain system information. With no OPTION, same as -s.\n\n"
"Options:\n"
"\t-a\tprint all information\n"
"\t-m\tthe machine (hardware) type\n"
"\t-n\tprint the machine's network node hostname\n"
"\t-r\tprint the operating system release\n"
"\t-s\tprint the operating system name\n"
"\t-p\tprint the host processor type\n"
"\t-v\tprint the operating system version\n";
static void print_element(unsigned int mask, char *element);
@ -80,77 +82,78 @@ static unsigned char toprint;
int uname_main(int argc, char **argv)
{
struct utsname name;
char processor[256];
struct utsname name;
char processor[256];
#if defined(__sparc__) && defined(__linux__)
char *fake_sparc = getenv("FAKE_SPARC");
char *fake_sparc = getenv("FAKE_SPARC");
#endif
toprint = 0;
toprint = 0;
/* Parse any options */
//fprintf(stderr, "argc=%d, argv=%s\n", argc, *argv);
while (--argc > 0 && **(++argv) == '-') {
while (*(++(*argv))) {
switch (**argv) {
case 's':
toprint |= PRINT_SYSNAME;
break;
case 'n':
toprint |= PRINT_NODENAME;
break;
case 'r':
toprint |= PRINT_RELEASE;
break;
case 'v':
toprint |= PRINT_VERSION;
break;
case 'm':
toprint |= PRINT_MACHINE;
break;
case 'p':
toprint |= PRINT_PROCESSOR;
break;
case 'a':
toprint = (PRINT_SYSNAME | PRINT_NODENAME | PRINT_RELEASE |
PRINT_PROCESSOR | PRINT_VERSION |
PRINT_MACHINE);
break;
default:
usage(uname_usage);
}
/* Parse any options */
//fprintf(stderr, "argc=%d, argv=%s\n", argc, *argv);
while (--argc > 0 && **(++argv) == '-') {
while (*(++(*argv))) {
switch (**argv) {
case 's':
toprint |= PRINT_SYSNAME;
break;
case 'n':
toprint |= PRINT_NODENAME;
break;
case 'r':
toprint |= PRINT_RELEASE;
break;
case 'v':
toprint |= PRINT_VERSION;
break;
case 'm':
toprint |= PRINT_MACHINE;
break;
case 'p':
toprint |= PRINT_PROCESSOR;
break;
case 'a':
toprint = (PRINT_SYSNAME | PRINT_NODENAME | PRINT_RELEASE |
PRINT_PROCESSOR | PRINT_VERSION |
PRINT_MACHINE);
break;
default:
usage(uname_usage);
}
}
}
}
if (toprint == 0)
toprint = PRINT_SYSNAME;
if (toprint == 0)
toprint = PRINT_SYSNAME;
if (uname(&name) == -1)
perror("cannot get system name");
if (uname(&name) == -1)
perror("cannot get system name");
#if defined (HAVE_SYSINFO) && defined (SI_ARCHITECTURE)
if (sysinfo(SI_ARCHITECTURE, processor, sizeof(processor)) == -1)
perror("cannot get processor type");
if (sysinfo(SI_ARCHITECTURE, processor, sizeof(processor)) == -1)
perror("cannot get processor type");
}
#else
strcpy(processor, "unknown");
strcpy(processor, "unknown");
#endif
#if defined(__sparc__) && defined(__linux__)
if (fake_sparc != NULL
&& (fake_sparc[0] == 'y'
|| fake_sparc[0] == 'Y')) strcpy(name.machine, "sparc");
if (fake_sparc != NULL
&& (fake_sparc[0] == 'y'
|| fake_sparc[0] == 'Y')) strcpy(name.machine, "sparc");
#endif
print_element(PRINT_SYSNAME, name.sysname);
print_element(PRINT_NODENAME, name.nodename);
print_element(PRINT_RELEASE, name.release);
print_element(PRINT_VERSION, name.version);
print_element(PRINT_MACHINE, name.machine);
print_element(PRINT_PROCESSOR, processor);
print_element(PRINT_SYSNAME, name.sysname);
print_element(PRINT_NODENAME, name.nodename);
print_element(PRINT_RELEASE, name.release);
print_element(PRINT_VERSION, name.version);
print_element(PRINT_MACHINE, name.machine);
print_element(PRINT_PROCESSOR, processor);
exit(TRUE);
exit(TRUE);
}
/* If the name element set in MASK is selected for printing in `toprint',
@ -159,8 +162,8 @@ int uname_main(int argc, char **argv)
static void print_element(unsigned int mask, char *element)
{
if (toprint & mask) {
toprint &= ~mask;
printf("%s%c", element, toprint ? ' ' : '\n');
}
if (toprint & mask) {
toprint &= ~mask;
printf("%s%c", element, toprint ? ' ' : '\n');
}
}

View File

@ -1,3 +1,4 @@
/* vi: set sw=4 ts=4: */
/*
* Mini uniq implementation for busybox
*
@ -27,119 +28,116 @@
#include <errno.h>
static const char uniq_usage[] =
"uniq [OPTION]... [INPUT [OUTPUT]]\n"
"Discard all but one of successive identical lines from INPUT (or\n"
"standard input), writing to OUTPUT (or standard output).\n"
"\n"
"\t-h\tdisplay this help and exit\n"
"\n"
"A field is a run of whitespace, then non-whitespace characters.\n"
"Fields are skipped before chars.\n"
;
"uniq [OPTION]... [INPUT [OUTPUT]]\n"
"Discard all but one of successive identical lines from INPUT (or\n"
"standard input), writing to OUTPUT (or standard output).\n"
"\n"
"\t-h\tdisplay this help and exit\n"
"\n"
"A field is a run of whitespace, then non-whitespace characters.\n"
"Fields are skipped before chars.\n";
/* max chars in line */
#define UNIQ_MAX 4096
typedef void (Print)(FILE *, const char *);
typedef void (Print) (FILE *, const char *);
typedef int (Decide)(const char *, const char *);
typedef int (Decide) (const char *, const char *);
/* container for two lines to be compared */
typedef struct {
char *a;
char *b;
int recurrence;
FILE *in;
FILE *out;
void *func;
char *a;
char *b;
int recurrence;
FILE *in;
FILE *out;
void *func;
} Subject;
/* set up all the variables of a uniq operation */
static Subject *
subject_init(Subject *self, FILE *in, FILE *out, void *func)
static Subject *subject_init(Subject * self, FILE * in, FILE * out,
void *func)
{
self->a = NULL;
self->b = NULL;
self->in = in;
self->out = out;
self->func = func;
self->recurrence = 0;
return self;
self->a = NULL;
self->b = NULL;
self->in = in;
self->out = out;
self->func = func;
self->recurrence = 0;
return self;
}
/* point a and b to the appropriate lines;
* count the recurrences (if any) of a string;
*/
static Subject *
subject_next(Subject *self)
static Subject *subject_next(Subject * self)
{
/* tmp line holders */
static char line[2][UNIQ_MAX];
static int alternator = 0;
/* tmp line holders */
static char line[2][UNIQ_MAX];
static int alternator = 0;
if (fgets(line[alternator], UNIQ_MAX, self->in)) {
if (fgets(line[alternator], UNIQ_MAX, self->in)) {
self->a = self->b;
self->b = line[alternator];
alternator ^= 1;
return self;
}
return NULL;
}
static Subject *subject_last(Subject * self)
{
self->a = self->b;
self->b = line[alternator];
alternator ^= 1;
self->b = NULL;
return self;
}
return NULL;
}
static Subject *
subject_last(Subject *self)
static Subject *subject_study(Subject * self)
{
self->a = self->b;
self->b = NULL;
return self;
}
static Subject *
subject_study(Subject *self)
{
if (self->a == NULL) {
if (self->a == NULL) {
return self;
}
if (self->b == NULL) {
fprintf(self->out, "%s", self->a);
return self;
}
if (strcmp(self->a, self->b) == 0) {
self->recurrence++;
} else {
fprintf(self->out, "%s", self->a);
self->recurrence = 0;
}
return self;
}
if (self->b == NULL) {
fprintf(self->out, "%s", self->a);
return self;
}
if (strcmp(self->a, self->b) == 0) {
self->recurrence++;
} else {
fprintf(self->out, "%s", self->a);
self->recurrence = 0;
}
return self;
}
static int
set_file_pointers(int schema, FILE **in, FILE **out, char **argv)
set_file_pointers(int schema, FILE ** in, FILE ** out, char **argv)
{
switch (schema) {
switch (schema) {
case 0:
*in = stdin;
*out = stdout;
break;
*in = stdin;
*out = stdout;
break;
case 1:
*in = fopen(argv[0], "r");
*out = stdout;
break;
*in = fopen(argv[0], "r");
*out = stdout;
break;
case 2:
*in = fopen(argv[0], "r");
*out = fopen(argv[1], "w");
break;
}
if (*in == NULL) {
fprintf(stderr, "uniq: %s: %s\n", argv[0], strerror(errno));
return errno;
}
if (*out == NULL) {
fprintf(stderr, "uniq: %s: %s\n", argv[1], strerror(errno));
return errno;
}
return 0;
*in = fopen(argv[0], "r");
*out = fopen(argv[1], "w");
break;
}
if (*in == NULL) {
fprintf(stderr, "uniq: %s: %s\n", argv[0], strerror(errno));
return errno;
}
if (*out == NULL) {
fprintf(stderr, "uniq: %s: %s\n", argv[1], strerror(errno));
return errno;
}
return 0;
}
@ -152,45 +150,44 @@ set_file_pointers(int schema, FILE **in, FILE **out, char **argv)
/* it seems like GNU/uniq only takes one or two files as an option */
/* ________________________________________________________________________ */
int
uniq_main(int argc, char **argv)
int uniq_main(int argc, char **argv)
{
int i;
char opt;
FILE *in, *out;
Subject s;
int i;
char opt;
FILE *in, *out;
Subject s;
/* parse argv[] */
for (i = 1; i < argc; i++) {
if (argv[i][0] == '-') {
opt = argv[i][1];
switch (opt) {
case '-':
case 'h':
usage(uniq_usage);
default:
usage(uniq_usage);
}
} else {
break;
/* parse argv[] */
for (i = 1; i < argc; i++) {
if (argv[i][0] == '-') {
opt = argv[i][1];
switch (opt) {
case '-':
case 'h':
usage(uniq_usage);
default:
usage(uniq_usage);
}
} else {
break;
}
}
}
/* 0 src: stdin; dst: stdout */
/* 1 src: file; dst: stdout */
/* 2 src: file; dst: file */
if (set_file_pointers((argc - 1), &in, &out, &argv[i])) {
exit(1);
}
/* 0 src: stdin; dst: stdout */
/* 1 src: file; dst: stdout */
/* 2 src: file; dst: file */
if (set_file_pointers((argc - 1), &in, &out, &argv[i])) {
exit(1);
}
subject_init(&s, in, out, NULL);
while (subject_next(&s)) {
subject_init(&s, in, out, NULL);
while (subject_next(&s)) {
subject_study(&s);
}
subject_last(&s);
subject_study(&s);
}
subject_last(&s);
subject_study(&s);
exit(0);
exit(0);
}
/* $Id: uniq.c,v 1.6 2000/02/07 05:29:42 erik Exp $ */
/* $Id: uniq.c,v 1.7 2000/02/08 19:58:47 erik Exp $ */

View File

@ -1,3 +1,4 @@
/* vi: set sw=4 ts=4: */
/*
* Mini wc implementation for busybox
*
@ -23,78 +24,82 @@
#include <stdio.h>
static const char wc_usage[] = "wc [OPTION]... [FILE]...\n\n"
"Print line, word, and byte counts for each FILE, and a total line if\n"
"more than one FILE is specified. With no FILE, read standard input.\n"
"\t-c\tprint the byte counts\n"
"\t-l\tprint the newline counts\n"
"\t-L\tprint the length of the longest line\n"
"\t-w\tprint the word counts\n";
"Print line, word, and byte counts for each FILE, and a total line if\n"
"more than one FILE is specified. With no FILE, read standard input.\n"
"\t-c\tprint the byte counts\n"
"\t-l\tprint the newline counts\n"
"\t-L\tprint the length of the longest line\n"
"\t-w\tprint the word counts\n";
static int total_lines, total_words, total_chars, max_length;
static int print_lines, print_words, print_chars, print_length;
void print_counts (int lines, int words, int chars, int length,
const char *name) {
void print_counts(int lines, int words, int chars, int length,
const char *name)
{
char const *space = "";
if (print_lines) {
printf ("%7d", lines);
printf("%7d", lines);
space = " ";
}
if (print_words) {
printf ("%s%7d", space, words);
printf("%s%7d", space, words);
space = " ";
}
if (print_chars) {
printf ("%s%7d", space, chars);
printf("%s%7d", space, chars);
space = " ";
}
if (print_length)
printf ("%s%7d", space, length);
printf("%s%7d", space, length);
if (*name)
printf (" %s", name);
putchar ('\n');
printf(" %s", name);
putchar('\n');
}
static void wc_file(FILE *file, const char *name)
static void wc_file(FILE * file, const char *name)
{
int lines, words, chars, length;
int in_word = 0, linepos = 0;
int c;
lines = words = chars = length = 0;
while ((c = getc(file)) != EOF) {
chars++;
switch (c) {
case '\n':
lines++;
case '\r':
case '\f':
if (linepos > length)
length = linepos;
linepos = 0;
goto word_separator;
case '\t':
linepos += 8 - (linepos % 8);
goto word_separator;
case ' ':
linepos++;
case '\v':
word_separator:
if (in_word) {
in_word = 0;
words++;
}
break;
default:
linepos++;
in_word = 1;
break;
case '\n':
lines++;
case '\r':
case '\f':
if (linepos > length)
length = linepos;
linepos = 0;
goto word_separator;
case '\t':
linepos += 8 - (linepos % 8);
goto word_separator;
case ' ':
linepos++;
case '\v':
word_separator:
if (in_word) {
in_word = 0;
words++;
}
break;
default:
linepos++;
in_word = 1;
break;
}
}
if (linepos > length)
length = linepos;
if (in_word)
words++;
print_counts (lines, words, chars, length, name);
print_counts(lines, words, chars, length, name);
total_lines += lines;
total_words += words;
total_chars += chars;
@ -104,28 +109,30 @@ static void wc_file(FILE *file, const char *name)
fflush(stdout);
}
int wc_main(int argc, char **argv) {
int wc_main(int argc, char **argv)
{
FILE *file;
total_lines = total_words = total_chars = max_length = 0;
print_lines = print_words = print_chars = print_length = 0;
while (--argc && **(++argv) == '-') {
while (*++(*argv))
switch (**argv) {
case 'c':
print_chars = 1;
break;
case 'l':
print_lines = 1;
break;
case 'L':
print_length = 1;
break;
case 'w':
print_words = 1;
break;
default:
usage (wc_usage);
case 'c':
print_chars = 1;
break;
case 'l':
print_lines = 1;
break;
case 'L':
print_length = 1;
break;
case 'w':
print_words = 1;
break;
default:
usage(wc_usage);
}
}
@ -135,16 +142,14 @@ int wc_main(int argc, char **argv) {
if (argc == 0) {
wc_file(stdin, "");
exit(TRUE);
}
else if (argc == 1) {
} else if (argc == 1) {
file = fopen(*argv, "r");
if (file == NULL) {
perror(*argv);
exit(FALSE);
}
wc_file(file, *argv);
}
else {
} else {
while (argc-- > 0 && *argv != '\0' && strlen(*argv)) {
file = fopen(*argv, "r");
if (file == NULL) {
@ -154,8 +159,8 @@ int wc_main(int argc, char **argv) {
wc_file(file, *argv);
argv++;
}
print_counts (total_lines, total_words, total_chars,
max_length, "total");
print_counts(total_lines, total_words, total_chars,
max_length, "total");
}
exit(TRUE);
}

View File

@ -1,3 +1,4 @@
/* vi: set sw=4 ts=4: */
/*
* Mini whoami implementation for busybox
*
@ -24,21 +25,25 @@
#include <pwd.h>
static const char whoami_usage[] = "whoami\n\n"
"Print the user name associated with the current effective user id.\n"
"Same as id -un.\n";
"Print the user name associated with the current effective user id.\n"
extern int whoami_main(int argc, char **argv) {
"Same as id -un.\n";
extern int whoami_main(int argc, char **argv)
{
struct passwd *pw;
uid_t uid;
if (argc > 1) usage (whoami_usage);
if (argc > 1)
usage(whoami_usage);
uid = geteuid ();
pw = getpwuid (uid);
uid = geteuid();
pw = getpwuid(uid);
if (pw) {
puts (pw->pw_name);
exit (TRUE);
}
fprintf (stderr, "%s: cannot find username for UID %u\n", argv[0], (unsigned) uid);
exit (FALSE);
puts(pw->pw_name);
exit(TRUE);
}
fprintf(stderr, "%s: cannot find username for UID %u\n", argv[0],
(unsigned) uid);
exit(FALSE);
}

View File

@ -1,3 +1,4 @@
/* vi: set sw=4 ts=4: */
/*
* Mini yes implementation for busybox
*
@ -22,19 +23,22 @@
#include "internal.h"
#include <stdio.h>
extern int yes_main(int argc, char **argv) {
extern int yes_main(int argc, char **argv)
{
int i;
if (argc == 1)
while (1)
if (puts ("y") == EOF) {
perror ("yes");
if (puts("y") == EOF) {
perror("yes");
exit(FALSE);
}
while (1)
for (i = 1; i < argc; i++)
if (fputs (argv[i], stdout) == EOF || putchar (i == argc - 1 ? '\n' : ' ') == EOF) {
perror ("yes");
if (fputs(argv[i], stdout) == EOF
|| putchar(i == argc - 1 ? '\n' : ' ') == EOF) {
perror("yes");
exit(FALSE);
}
exit(TRUE);

381
cp_mv.c
View File

@ -1,3 +1,4 @@
/* vi: set sw=4 ts=4: */
/*
* Mini `cp' and `mv' implementation for BusyBox.
*
@ -39,217 +40,205 @@
#define is_cp 0
#define is_mv 1
static const char *dz; /* dollar zero, .bss */
static int dz_i; /* index, .bss */
static const char *cp_mv_usage[] = /* .rodata */
static const char *dz; /* dollar zero, .bss */
static int dz_i; /* index, .bss */
static const char *cp_mv_usage[] = /* .rodata */
{
"cp [OPTION]... SOURCE DEST\n"
" or: cp [OPTION]... SOURCE... DIRECTORY\n\n"
"Copy SOURCE to DEST, or multiple SOURCE(s) to DIRECTORY.\n"
"\n"
"\t-a\tsame as -dpR\n"
"\t-d\tpreserve links\n"
"\t-p\tpreserve file attributes if possible\n"
"\t-R\tcopy directories recursively\n"
,
"mv SOURCE DEST\n"
" or: mv SOURCE... DIRECTORY\n\n"
"Rename SOURCE to DEST, or move SOURCE(s) to DIRECTORY.\n"
"Warning!! This is not GNU `mv'. It does not preserve hard links.\n"
"cp [OPTION]... SOURCE DEST\n"
" or: cp [OPTION]... SOURCE... DIRECTORY\n\n"
"Copy SOURCE to DEST, or multiple SOURCE(s) to DIRECTORY.\n"
"\n"
"\t-a\tsame as -dpR\n"
"\t-d\tpreserve links\n"
"\t-p\tpreserve file attributes if possible\n"
"\t-R\tcopy directories recursively\n",
"mv SOURCE DEST\n"
" or: mv SOURCE... DIRECTORY\n\n"
"Rename SOURCE to DEST, or move SOURCE(s) to DIRECTORY.\n"
"Warning!! This is not GNU `mv'. It does not preserve hard links.\n"
};
extern int cp_mv_main(int argc, char **argv)
{
__label__ name_too_long__exit;
__label__ exit_false;
__label__ name_too_long__exit;
__label__ exit_false;
int recursiveFlag;
int followLinks;
int preserveFlag;
int recursiveFlag;
int followLinks;
int preserveFlag;
const char *baseSrcName;
int srcDirFlag;
const char *baseSrcName;
int srcDirFlag;
char baseDestName[PATH_MAX + 1];
size_t baseDestLen;
int destDirFlag;
char baseDestName[PATH_MAX + 1];
size_t baseDestLen;
int destDirFlag;
void fill_baseDest_buf(char *_buf, size_t *_buflen)
{
const char *srcBasename;
if ((srcBasename = strrchr(baseSrcName, '/')) == NULL)
{
srcBasename = baseSrcName;
if (_buf[*_buflen - 1] != '/')
{
if (++(*_buflen) > PATH_MAX)
void fill_baseDest_buf(char *_buf, size_t * _buflen) {
const char *srcBasename;
if ((srcBasename = strrchr(baseSrcName, '/')) == NULL) {
srcBasename = baseSrcName;
if (_buf[*_buflen - 1] != '/') {
if (++(*_buflen) > PATH_MAX)
goto name_too_long__exit;
strcat(_buf, "/");
}
}
if (*_buflen + strlen(srcBasename) > PATH_MAX)
goto name_too_long__exit;
strcat(_buf, srcBasename);
return;
}
int fileAction(const char *fileName, struct stat *statbuf) {
__label__ return_false;
char destName[PATH_MAX + 1];
size_t destLen;
const char *srcBasename;
strcpy(destName, baseDestName);
destLen = strlen(destName);
if (srcDirFlag == TRUE) {
if (recursiveFlag == FALSE) {
fprintf(stderr, omitting_directory, "cp", baseSrcName);
return TRUE;
}
srcBasename = (strstr(fileName, baseSrcName)
+ strlen(baseSrcName));
if (destLen + strlen(srcBasename) > PATH_MAX) {
fprintf(stderr, name_too_long, "cp");
goto return_false;
}
strcat(destName, srcBasename);
} else if (destDirFlag == TRUE) {
fill_baseDest_buf(&destName[0], &destLen);
} else {
srcBasename = baseSrcName;
}
return copyFile(fileName, destName, preserveFlag, followLinks);
return_false:
return FALSE;
}
int rmfileAction(const char *fileName, struct stat *statbuf) {
if (unlink(fileName) < 0) {
perror(fileName);
return FALSE;
}
return TRUE;
}
int rmdirAction(const char *fileName, struct stat *statbuf) {
if (rmdir(fileName) < 0) {
perror(fileName);
return FALSE;
}
return TRUE;
}
if ((dz = strrchr(*argv, '/')) == NULL)
dz = *argv;
else
dz++;
if (*dz == 'c' && *(dz + 1) == 'p')
dz_i = is_cp;
else
dz_i = is_mv;
if (argc < 3)
usage(cp_mv_usage[dz_i]);
argc--;
argv++;
if (dz_i == is_cp) {
recursiveFlag = preserveFlag = FALSE;
followLinks = TRUE;
while (**argv == '-') {
while (*++(*argv)) {
switch (**argv) {
case 'a':
followLinks = FALSE;
preserveFlag = TRUE;
recursiveFlag = TRUE;
break;
case 'd':
followLinks = FALSE;
break;
case 'p':
preserveFlag = TRUE;
break;
case 'R':
recursiveFlag = TRUE;
break;
default:
usage(cp_mv_usage[is_cp]);
}
}
argc--;
argv++;
}
} else { /* (dz_i == is_mv) */
recursiveFlag = preserveFlag = TRUE;
followLinks = FALSE;
}
if (strlen(argv[argc - 1]) > PATH_MAX) {
fprintf(stderr, name_too_long, "cp");
goto exit_false;
}
strcpy(baseDestName, argv[argc - 1]);
baseDestLen = strlen(baseDestName);
if (baseDestLen == 0)
goto exit_false;
destDirFlag = isDirectory(baseDestName, TRUE);
if ((argc > 3) && destDirFlag == FALSE) {
fprintf(stderr, not_a_directory, "cp", baseDestName);
goto exit_false;
}
while (argc-- > 1) {
size_t srcLen;
int flags_memo;
baseSrcName = *(argv++);
if ((srcLen = strlen(baseSrcName)) > PATH_MAX)
goto name_too_long__exit;
strcat(_buf, "/");
if (srcLen == 0)
continue;
srcDirFlag = isDirectory(baseSrcName, followLinks);
if ((flags_memo = (recursiveFlag == TRUE &&
srcDirFlag == TRUE && destDirFlag == TRUE))) {
fill_baseDest_buf(&baseDestName[0], &baseDestLen);
}
}
if (*_buflen + strlen(srcBasename) > PATH_MAX)
goto name_too_long__exit;
strcat(_buf, srcBasename);
return;
if (recursiveAction(baseSrcName,
recursiveFlag, followLinks, FALSE,
fileAction, fileAction) == FALSE)
goto exit_false;
if (dz_i == is_mv &&
recursiveAction(baseSrcName,
recursiveFlag, followLinks, TRUE,
rmfileAction, rmdirAction) == FALSE)
goto exit_false;
if (flags_memo)
*(baseDestName + baseDestLen) = '\0';
}
int fileAction(const char *fileName, struct stat *statbuf)
{
__label__ return_false;
char destName[PATH_MAX + 1];
size_t destLen;
const char *srcBasename;
strcpy(destName, baseDestName);
destLen = strlen(destName);
if (srcDirFlag == TRUE)
{
if (recursiveFlag == FALSE)
{
fprintf(stderr, omitting_directory, "cp", baseSrcName);
return TRUE;
}
srcBasename = (strstr(fileName, baseSrcName)
+ strlen(baseSrcName));
if (destLen + strlen(srcBasename) > PATH_MAX)
{
fprintf(stderr, name_too_long, "cp");
goto return_false;
}
strcat(destName, srcBasename);
}
else if (destDirFlag == TRUE)
{
fill_baseDest_buf(&destName[0], &destLen);
}
else
{
srcBasename = baseSrcName;
}
return copyFile(fileName, destName, preserveFlag, followLinks);
return_false:
return FALSE;
}
exit TRUE;
int rmfileAction(const char *fileName, struct stat* statbuf)
{
if (unlink(fileName) < 0 ) {
perror(fileName);
return FALSE;
}
return TRUE;
}
int rmdirAction(const char *fileName, struct stat* statbuf)
{
if (rmdir(fileName) < 0 ) {
perror(fileName);
return FALSE;
}
return TRUE;
}
if ((dz = strrchr(*argv, '/')) == NULL) dz = *argv; else dz++;
if (*dz == 'c' && *(dz + 1) == 'p') dz_i = is_cp; else dz_i = is_mv;
if (argc < 3) usage(cp_mv_usage[dz_i]);
argc--;
argv++;
if (dz_i == is_cp)
{
recursiveFlag = preserveFlag = FALSE;
followLinks = TRUE;
while (**argv == '-')
{
while (*++(*argv))
{
switch (**argv)
{
case 'a':
followLinks = FALSE;
preserveFlag = TRUE;
recursiveFlag = TRUE;
break;
case 'd':
followLinks = FALSE;
break;
case 'p':
preserveFlag = TRUE;
break;
case 'R':
recursiveFlag = TRUE;
break;
default:
usage(cp_mv_usage[is_cp]);
}
}
argc--;
argv++;
}
}
else /* (dz_i == is_mv) */
{
recursiveFlag = preserveFlag = TRUE;
followLinks = FALSE;
}
if (strlen(argv[argc - 1]) > PATH_MAX)
{
name_too_long__exit:
fprintf(stderr, name_too_long, "cp");
goto exit_false;
}
strcpy(baseDestName, argv[argc - 1]);
baseDestLen = strlen(baseDestName);
if (baseDestLen == 0) goto exit_false;
destDirFlag = isDirectory(baseDestName, TRUE);
if ((argc > 3) && destDirFlag == FALSE)
{
fprintf(stderr, not_a_directory, "cp", baseDestName);
goto exit_false;
}
while (argc-- > 1)
{
size_t srcLen;
int flags_memo;
baseSrcName = *(argv++);
if ((srcLen = strlen(baseSrcName)) > PATH_MAX)
goto name_too_long__exit;
if (srcLen == 0) continue;
srcDirFlag = isDirectory(baseSrcName, followLinks);
if ((flags_memo = (recursiveFlag == TRUE &&
srcDirFlag == TRUE && destDirFlag == TRUE)))
{
fill_baseDest_buf(&baseDestName[0], &baseDestLen);
}
if (recursiveAction(baseSrcName,
recursiveFlag, followLinks, FALSE,
fileAction, fileAction)
== FALSE) goto exit_false;
if (dz_i == is_mv &&
recursiveAction(baseSrcName,
recursiveFlag, followLinks, TRUE,
rmfileAction, rmdirAction)
== FALSE) goto exit_false;
if (flags_memo) *(baseDestName + baseDestLen) = '\0';
}
exit TRUE;
name_too_long__exit:
fprintf(stderr, name_too_long, "cp");
exit_false:
exit FALSE;
exit_false:
exit FALSE;
}
// Local Variables:

451
date.c
View File

@ -1,3 +1,4 @@
/* vi: set sw=4 ts=4: */
/*
* Mini date implementation for busybox
*
@ -38,12 +39,13 @@
an RFC 822 complient date output for shell scripting
mail commands */
static const char date_usage[] = "date [OPTION]... [+FORMAT]\n"
" or: date [OPTION] [MMDDhhmm[[CC]YY][.ss]]\n\n"
"Display the current time in the given FORMAT, or set the system date.\n"
"\nOptions:\n\t-R\t\toutput RFC-822 compliant date string\n"
"\t-s\t\tset time described by STRING\n"
"\t-u\t\tprint or set Coordinated Universal Time\n";
static const char date_usage[] = "date [OPTION]... [+FORMAT]\n"
" or: date [OPTION] [MMDDhhmm[[CC]YY][.ss]]\n\n"
"Display the current time in the given FORMAT, or set the system date.\n"
"\nOptions:\n\t-R\t\toutput RFC-822 compliant date string\n"
"\t-s\t\tset time described by STRING\n"
"\t-u\t\tprint or set Coordinated Universal Time\n";
/* Input parsing code is always bulky - used heavy duty libc stuff as
@ -51,240 +53,233 @@ static const char date_usage[] = "date [OPTION]... [+FORMAT]\n"
/* Default input handling to save suprising some people */
struct tm *
date_conv_time(struct tm *tm_time, const char *t_string) {
int nr;
struct tm *date_conv_time(struct tm *tm_time, const char *t_string)
{
int nr;
nr = sscanf(t_string, "%2d%2d%2d%2d%d",
&(tm_time->tm_mon),
&(tm_time->tm_mday),
&(tm_time->tm_hour),
&(tm_time->tm_min),
&(tm_time->tm_year));
nr = sscanf(t_string, "%2d%2d%2d%2d%d",
&(tm_time->tm_mon),
&(tm_time->tm_mday),
&(tm_time->tm_hour),
&(tm_time->tm_min), &(tm_time->tm_year));
if(nr < 4 || nr > 5) {
fprintf(stderr, invalid_date, "date", t_string);
exit( FALSE);
}
if (nr < 4 || nr > 5) {
fprintf(stderr, invalid_date, "date", t_string);
exit(FALSE);
}
/* correct for century - minor Y2K problem here? */
if(tm_time->tm_year >= 1900)
tm_time->tm_year -= 1900;
/* adjust date */
tm_time->tm_mon -= 1;
return(tm_time);
/* correct for century - minor Y2K problem here? */
if (tm_time->tm_year >= 1900)
tm_time->tm_year -= 1900;
/* adjust date */
tm_time->tm_mon -= 1;
return (tm_time);
}
/* The new stuff for LRP */
struct tm *
date_conv_ftime(struct tm *tm_time, const char *t_string) {
struct tm itm_time, jtm_time, ktm_time, \
ltm_time, mtm_time, ntm_time;
itm_time = *tm_time;
jtm_time = *tm_time;
ktm_time = *tm_time;
ltm_time = *tm_time;
mtm_time = *tm_time;
ntm_time = *tm_time;
/* Parse input and assign appropriately to tm_time */
if(sscanf(t_string, "%d:%d:%d",
&itm_time.tm_hour,
&itm_time.tm_min,
&itm_time.tm_sec) == 3 ) {
*tm_time = itm_time;
return(tm_time);
} else if (sscanf(t_string, "%d:%d",
&jtm_time.tm_hour,
&jtm_time.tm_min) == 2) {
*tm_time = jtm_time;
return(tm_time);
} else if (sscanf(t_string, "%d.%d-%d:%d:%d",
&ktm_time.tm_mon,
&ktm_time.tm_mday,
&ktm_time.tm_hour,
&ktm_time.tm_min,
&ktm_time.tm_sec) == 5) {
ktm_time.tm_mon -= 1; /* Adjust dates from 1-12 to 0-11 */
*tm_time = ktm_time;
return(tm_time);
} else if (sscanf(t_string, "%d.%d-%d:%d",
&ltm_time.tm_mon,
&ltm_time.tm_mday,
&ltm_time.tm_hour,
&ltm_time.tm_min) == 4) {
ltm_time.tm_mon -= 1; /* Adjust dates from 1-12 to 0-11 */
*tm_time = ltm_time;
return(tm_time);
} else if (sscanf(t_string, "%d.%d.%d-%d:%d:%d",
&mtm_time.tm_year,
&mtm_time.tm_mon,
&mtm_time.tm_mday,
&mtm_time.tm_hour,
&mtm_time.tm_min,
&mtm_time.tm_sec) == 6) {
mtm_time.tm_year -= 1900; /* Adjust years */
mtm_time.tm_mon -= 1; /* Adjust dates from 1-12 to 0-11 */
*tm_time = mtm_time;
return(tm_time);
} else if (sscanf(t_string, "%d.%d.%d-%d:%d",
&ntm_time.tm_year,
&ntm_time.tm_mon,
&ntm_time.tm_mday,
&ntm_time.tm_hour,
&ntm_time.tm_min) == 5) {
ntm_time.tm_year -= 1900; /* Adjust years */
ntm_time.tm_mon -= 1; /* Adjust dates from 1-12 to 0-11 */
*tm_time = ntm_time;
return(tm_time);
}
fprintf(stderr, invalid_date, "date", t_string);
exit( FALSE);
}
int
date_main(int argc, char * * argv)
struct tm *date_conv_ftime(struct tm *tm_time, const char *t_string)
{
char *date_str = NULL;
char *date_fmt = NULL;
char *t_buff;
int i;
int set_time = 0;
int rfc822 = 0;
int utc = 0;
int use_arg = 0;
time_t tm;
struct tm tm_time;
/* Interpret command line args */
i = --argc;
argv++;
while (i > 0 && **argv) {
if (**argv == '-') {
while (i>0 && *++(*argv)) switch (**argv) {
case 'R':
rfc822 = 1;
break;
case 's':
set_time = 1;
if(date_str != NULL) usage ( date_usage);
date_str = optarg;
break;
case 'u':
utc = 1;
if (putenv ("TZ=UTC0") != 0) {
fprintf(stderr, memory_exhausted, "date");
exit( FALSE);
}
/* Look ma, no break. Don't fix it either. */
case 'd':
use_arg = 1;
if(date_str != NULL) usage ( date_usage);
date_str = optarg;
break;
case '-':
usage ( date_usage);
}
} else {
if ( (date_fmt == NULL) && (strcmp(*argv, "+")==0) )
date_fmt=*argv;
else if (date_str == NULL) {
set_time = 1;
date_str=*argv;
} else {
usage ( date_usage);
}
struct tm itm_time, jtm_time, ktm_time, ltm_time, mtm_time, ntm_time;
itm_time = *tm_time;
jtm_time = *tm_time;
ktm_time = *tm_time;
ltm_time = *tm_time;
mtm_time = *tm_time;
ntm_time = *tm_time;
/* Parse input and assign appropriately to tm_time */
if (sscanf(t_string, "%d:%d:%d",
&itm_time.tm_hour, &itm_time.tm_min, &itm_time.tm_sec) == 3) {
*tm_time = itm_time;
return (tm_time);
} else if (sscanf(t_string, "%d:%d",
&jtm_time.tm_hour, &jtm_time.tm_min) == 2) {
*tm_time = jtm_time;
return (tm_time);
} else if (sscanf(t_string, "%d.%d-%d:%d:%d",
&ktm_time.tm_mon,
&ktm_time.tm_mday,
&ktm_time.tm_hour,
&ktm_time.tm_min, &ktm_time.tm_sec) == 5) {
ktm_time.tm_mon -= 1; /* Adjust dates from 1-12 to 0-11 */
*tm_time = ktm_time;
return (tm_time);
} else if (sscanf(t_string, "%d.%d-%d:%d",
&ltm_time.tm_mon,
&ltm_time.tm_mday,
&ltm_time.tm_hour, &ltm_time.tm_min) == 4) {
ltm_time.tm_mon -= 1; /* Adjust dates from 1-12 to 0-11 */
*tm_time = ltm_time;
return (tm_time);
} else if (sscanf(t_string, "%d.%d.%d-%d:%d:%d",
&mtm_time.tm_year,
&mtm_time.tm_mon,
&mtm_time.tm_mday,
&mtm_time.tm_hour,
&mtm_time.tm_min, &mtm_time.tm_sec) == 6) {
mtm_time.tm_year -= 1900; /* Adjust years */
mtm_time.tm_mon -= 1; /* Adjust dates from 1-12 to 0-11 */
*tm_time = mtm_time;
return (tm_time);
} else if (sscanf(t_string, "%d.%d.%d-%d:%d",
&ntm_time.tm_year,
&ntm_time.tm_mon,
&ntm_time.tm_mday,
&ntm_time.tm_hour, &ntm_time.tm_min) == 5) {
ntm_time.tm_year -= 1900; /* Adjust years */
ntm_time.tm_mon -= 1; /* Adjust dates from 1-12 to 0-11 */
*tm_time = ntm_time;
return (tm_time);
}
i--;
argv++;
}
fprintf(stderr, invalid_date, "date", t_string);
/* Now we have parsed all the information except the date format
which depends on whether the clock is being set or read */
time(&tm);
memcpy(&tm_time, localtime(&tm), sizeof(tm_time));
/* Zero out fields - take her back to midnight!*/
if(date_str != NULL) {
tm_time.tm_sec = 0;
tm_time.tm_min = 0;
tm_time.tm_hour = 0;
}
/* Process any date input to UNIX time since 1 Jan 1970 */
if(date_str != NULL) {
if(strchr(date_str, ':') != NULL) {
date_conv_ftime(&tm_time, date_str);
} else {
date_conv_time(&tm_time, date_str);
}
/* Correct any day of week and day of year etc fields */
tm = mktime(&tm_time);
if (tm < 0 ) {
fprintf(stderr, invalid_date, "date", date_str);
exit( FALSE);
}
/* if setting time, set it */
if(set_time) {
if( stime(&tm) < 0) {
fprintf(stderr, "date: can't set date.\n");
exit( FALSE);
}
}
}
/* Display output */
/* Deal with format string */
if(date_fmt == NULL) {
date_fmt = (rfc822
? (utc
? "%a, %_d %b %Y %H:%M:%S GMT"
: "%a, %_d %b %Y %H:%M:%S %z")
: "%a %b %e %H:%M:%S %Z %Y");
} else if ( *date_fmt == '\0' ) {
/* Imitate what GNU 'date' does with NO format string! */
printf ("\n");
exit( TRUE);
}
/* Handle special conversions */
if( strncmp( date_fmt, "%f", 2) == 0 ) {
date_fmt = "%Y.%m.%d-%H:%M:%S";
}
/* Print OUTPUT (after ALL that!) */
t_buff = malloc(201);
strftime(t_buff, 200, date_fmt, &tm_time);
printf("%s\n", t_buff);
exit( TRUE);
exit(FALSE);
}
int date_main(int argc, char **argv)
{
char *date_str = NULL;
char *date_fmt = NULL;
char *t_buff;
int i;
int set_time = 0;
int rfc822 = 0;
int utc = 0;
int use_arg = 0;
time_t tm;
struct tm tm_time;
/* Interpret command line args */
i = --argc;
argv++;
while (i > 0 && **argv) {
if (**argv == '-') {
while (i > 0 && *++(*argv))
switch (**argv) {
case 'R':
rfc822 = 1;
break;
case 's':
set_time = 1;
if (date_str != NULL)
usage(date_usage);
date_str = optarg;
break;
case 'u':
utc = 1;
if (putenv("TZ=UTC0") != 0) {
fprintf(stderr, memory_exhausted, "date");
exit(FALSE);
}
/* Look ma, no break. Don't fix it either. */
case 'd':
use_arg = 1;
if (date_str != NULL)
usage(date_usage);
date_str = optarg;
break;
case '-':
usage(date_usage);
}
} else {
if ((date_fmt == NULL) && (strcmp(*argv, "+") == 0))
date_fmt = *argv;
else if (date_str == NULL) {
set_time = 1;
date_str = *argv;
} else {
usage(date_usage);
}
}
i--;
argv++;
}
/* Now we have parsed all the information except the date format
which depends on whether the clock is being set or read */
time(&tm);
memcpy(&tm_time, localtime(&tm), sizeof(tm_time));
/* Zero out fields - take her back to midnight! */
if (date_str != NULL) {
tm_time.tm_sec = 0;
tm_time.tm_min = 0;
tm_time.tm_hour = 0;
}
/* Process any date input to UNIX time since 1 Jan 1970 */
if (date_str != NULL) {
if (strchr(date_str, ':') != NULL) {
date_conv_ftime(&tm_time, date_str);
} else {
date_conv_time(&tm_time, date_str);
}
/* Correct any day of week and day of year etc fields */
tm = mktime(&tm_time);
if (tm < 0) {
fprintf(stderr, invalid_date, "date", date_str);
exit(FALSE);
}
/* if setting time, set it */
if (set_time) {
if (stime(&tm) < 0) {
fprintf(stderr, "date: can't set date.\n");
exit(FALSE);
}
}
}
/* Display output */
/* Deal with format string */
if (date_fmt == NULL) {
date_fmt = (rfc822
? (utc
? "%a, %_d %b %Y %H:%M:%S GMT"
: "%a, %_d %b %Y %H:%M:%S %z")
: "%a %b %e %H:%M:%S %Z %Y");
} else if (*date_fmt == '\0') {
/* Imitate what GNU 'date' does with NO format string! */
printf("\n");
exit(TRUE);
}
/* Handle special conversions */
if (strncmp(date_fmt, "%f", 2) == 0) {
date_fmt = "%Y.%m.%d-%H:%M:%S";
}
/* Print OUTPUT (after ALL that!) */
t_buff = malloc(201);
strftime(t_buff, 200, date_fmt, &tm_time);
printf("%s\n", t_buff);
exit(TRUE);
}

278
dd.c
View File

@ -1,3 +1,4 @@
/* vi: set sw=4 ts=4: */
/*
* Mini dd implementation for busybox
*
@ -40,164 +41,159 @@ typedef unsigned long long int uintmax_t;
#endif
static const char dd_usage[] =
"dd [if=name] [of=name] [bs=n] [count=n] [skip=n] [seek=n]\n\n"
"Copy a file, converting and formatting according to options\n\n"
"\tif=FILE\tread from FILE instead of stdin\n"
"\tof=FILE\twrite to FILE instead of stdout\n"
"\tbs=n\tread and write n bytes at a time\n"
"\tcount=n\tcopy only n input blocks\n"
"\tskip=n\tskip n input blocks\n"
"\tseek=n\tskip n output blocks\n"
"\n"
"Numbers may be suffixed by w (x2), k (x1024), b (x512), or M (x1024^2)\n";
"dd [if=name] [of=name] [bs=n] [count=n] [skip=n] [seek=n]\n\n"
"Copy a file, converting and formatting according to options\n\n"
"\tif=FILE\tread from FILE instead of stdin\n"
"\tof=FILE\twrite to FILE instead of stdout\n"
"\tbs=n\tread and write n bytes at a time\n"
"\tcount=n\tcopy only n input blocks\n"
"\tskip=n\tskip n input blocks\n"
"\tseek=n\tskip n output blocks\n"
"\n"
"Numbers may be suffixed by w (x2), k (x1024), b (x512), or M (x1024^2)\n";
extern int dd_main (int argc, char **argv)
extern int dd_main(int argc, char **argv)
{
const char *inFile = NULL;
const char *outFile = NULL;
char *cp;
int inFd;
int outFd;
int inCc = 0;
int outCc;
long blockSize = 512;
uintmax_t skipBlocks = 0;
uintmax_t seekBlocks = 0;
uintmax_t count = (uintmax_t)-1;
uintmax_t intotal;
uintmax_t outTotal;
unsigned char *buf;
const char *inFile = NULL;
const char *outFile = NULL;
char *cp;
int inFd;
int outFd;
int inCc = 0;
int outCc;
long blockSize = 512;
uintmax_t skipBlocks = 0;
uintmax_t seekBlocks = 0;
uintmax_t count = (uintmax_t) - 1;
uintmax_t intotal;
uintmax_t outTotal;
unsigned char *buf;
argc--;
argv++;
/* Parse any options */
while (argc) {
if (inFile == NULL && (strncmp(*argv, "if", 2) == 0))
inFile=((strchr(*argv, '='))+1);
else if (outFile == NULL && (strncmp(*argv, "of", 2) == 0))
outFile=((strchr(*argv, '='))+1);
else if (strncmp("count", *argv, 5) == 0) {
count = getNum ((strchr(*argv, '='))+1);
if (count <= 0) {
fprintf (stderr, "Bad count value %s\n", *argv);
goto usage;
}
}
else if (strncmp(*argv, "bs", 2) == 0) {
blockSize = getNum ((strchr(*argv, '='))+1);
if (blockSize <= 0) {
fprintf (stderr, "Bad block size value %s\n", *argv);
goto usage;
}
}
else if (strncmp(*argv, "skip", 4) == 0) {
skipBlocks = getNum ((strchr(*argv, '='))+1);
if (skipBlocks <= 0) {
fprintf (stderr, "Bad skip value %s\n", *argv);
goto usage;
}
}
else if (strncmp(*argv, "seek", 4) == 0) {
seekBlocks = getNum ((strchr(*argv, '='))+1);
if (seekBlocks <= 0) {
fprintf (stderr, "Bad seek value %s\n", *argv);
goto usage;
}
}
else {
goto usage;
}
argc--;
argv++;
}
buf = malloc (blockSize);
if (buf == NULL) {
fprintf (stderr, "Cannot allocate buffer\n");
exit( FALSE);
}
/* Parse any options */
while (argc) {
if (inFile == NULL && (strncmp(*argv, "if", 2) == 0))
inFile = ((strchr(*argv, '=')) + 1);
else if (outFile == NULL && (strncmp(*argv, "of", 2) == 0))
outFile = ((strchr(*argv, '=')) + 1);
else if (strncmp("count", *argv, 5) == 0) {
count = getNum((strchr(*argv, '=')) + 1);
if (count <= 0) {
fprintf(stderr, "Bad count value %s\n", *argv);
goto usage;
}
} else if (strncmp(*argv, "bs", 2) == 0) {
blockSize = getNum((strchr(*argv, '=')) + 1);
if (blockSize <= 0) {
fprintf(stderr, "Bad block size value %s\n", *argv);
goto usage;
}
} else if (strncmp(*argv, "skip", 4) == 0) {
skipBlocks = getNum((strchr(*argv, '=')) + 1);
if (skipBlocks <= 0) {
fprintf(stderr, "Bad skip value %s\n", *argv);
goto usage;
}
intotal = 0;
outTotal = 0;
} else if (strncmp(*argv, "seek", 4) == 0) {
seekBlocks = getNum((strchr(*argv, '=')) + 1);
if (seekBlocks <= 0) {
fprintf(stderr, "Bad seek value %s\n", *argv);
goto usage;
}
if (inFile == NULL)
inFd = fileno(stdin);
else
inFd = open (inFile, 0);
if (inFd < 0) {
perror (inFile);
free (buf);
exit( FALSE);
}
if (outFile == NULL)
outFd = fileno(stdout);
else
outFd = open(outFile, O_WRONLY | O_CREAT | O_TRUNC, 0666);
if (outFd < 0) {
perror (outFile);
close (inFd);
free (buf);
exit( FALSE);
}
lseek(inFd, skipBlocks*blockSize, SEEK_SET);
lseek(outFd, seekBlocks*blockSize, SEEK_SET);
//
//TODO: Convert to using fullRead & fullWrite
// from utility.c
// -Erik
while (outTotal < count * blockSize) {
inCc = read (inFd, buf, blockSize);
if (inCc < 0) {
perror (inFile);
goto cleanup;
} else if (inCc == 0) {
goto cleanup;
} else {
goto usage;
}
argc--;
argv++;
}
intotal += inCc;
cp = buf;
while (intotal > outTotal) {
if (outTotal + inCc > count * blockSize)
inCc = count * blockSize - outTotal;
outCc = write (outFd, cp, inCc);
if (outCc < 0) {
perror (outFile);
goto cleanup;
} else if (outCc == 0) {
goto cleanup;
}
inCc -= outCc;
cp += outCc;
outTotal += outCc;
buf = malloc(blockSize);
if (buf == NULL) {
fprintf(stderr, "Cannot allocate buffer\n");
exit(FALSE);
}
}
if (inCc < 0)
perror (inFile);
intotal = 0;
outTotal = 0;
if (inFile == NULL)
inFd = fileno(stdin);
else
inFd = open(inFile, 0);
if (inFd < 0) {
perror(inFile);
free(buf);
exit(FALSE);
}
if (outFile == NULL)
outFd = fileno(stdout);
else
outFd = open(outFile, O_WRONLY | O_CREAT | O_TRUNC, 0666);
if (outFd < 0) {
perror(outFile);
close(inFd);
free(buf);
exit(FALSE);
}
lseek(inFd, skipBlocks * blockSize, SEEK_SET);
lseek(outFd, seekBlocks * blockSize, SEEK_SET);
//
//TODO: Convert to using fullRead & fullWrite
// from utility.c
// -Erik
while (outTotal < count * blockSize) {
inCc = read(inFd, buf, blockSize);
if (inCc < 0) {
perror(inFile);
goto cleanup;
} else if (inCc == 0) {
goto cleanup;
}
intotal += inCc;
cp = buf;
while (intotal > outTotal) {
if (outTotal + inCc > count * blockSize)
inCc = count * blockSize - outTotal;
outCc = write(outFd, cp, inCc);
if (outCc < 0) {
perror(outFile);
goto cleanup;
} else if (outCc == 0) {
goto cleanup;
}
inCc -= outCc;
cp += outCc;
outTotal += outCc;
}
}
if (inCc < 0)
perror(inFile);
cleanup:
close (inFd);
close (outFd);
free (buf);
close(inFd);
close(outFd);
free(buf);
printf ("%ld+%d records in\n", (long)(intotal / blockSize),
(intotal % blockSize) != 0);
printf ("%ld+%d records out\n", (long)(outTotal / blockSize),
(outTotal % blockSize) != 0);
exit( TRUE);
printf("%ld+%d records in\n", (long) (intotal / blockSize),
(intotal % blockSize) != 0);
printf("%ld+%d records out\n", (long) (outTotal / blockSize),
(outTotal % blockSize) != 0);
exit(TRUE);
usage:
usage( dd_usage);
usage(dd_usage);
}

View File

@ -1,3 +1,4 @@
/* vi: set sw=4 ts=4: */
/*
* disalloc.c - aeb - 940501 - Disallocate virtual terminal(s)
* Renamed deallocvt.
@ -13,38 +14,39 @@
extern int getfd(void);
char *progname;
int
deallocvt_main(int argc, char *argv[]) {
int fd, num, i;
int deallocvt_main(int argc, char *argv[])
{
int fd, num, i;
if ( ( argc != 2) || (**(argv+1) == '-' ) ) {
usage ("deallocvt N\n\nDeallocate unused virtual terminal /dev/ttyN\n");
}
progname = argv[0];
fd = get_console_fd("/dev/console");
if (argc == 1) {
/* deallocate all unused consoles */
if (ioctl(fd,VT_DISALLOCATE,0)) {
perror("VT_DISALLOCATE");
exit(1);
if ((argc != 2) || (**(argv + 1) == '-')) {
usage
("deallocvt N\n\nDeallocate unused virtual terminal /dev/ttyN\n");
}
} else
for (i = 1; i < argc; i++) {
num = atoi(argv[i]);
if (num == 0)
fprintf(stderr, "%s: 0: illegal VT number\n", progname);
else if (num == 1)
fprintf(stderr, "%s: VT 1 cannot be deallocated\n", progname);
else
if (ioctl(fd,VT_DISALLOCATE,num)) {
perror("VT_DISALLOCATE");
fprintf(stderr, "%s: could not deallocate console %d\n",
progname, num);
exit(1);
}
}
exit(0);
progname = argv[0];
fd = get_console_fd("/dev/console");
if (argc == 1) {
/* deallocate all unused consoles */
if (ioctl(fd, VT_DISALLOCATE, 0)) {
perror("VT_DISALLOCATE");
exit(1);
}
} else
for (i = 1; i < argc; i++) {
num = atoi(argv[i]);
if (num == 0)
fprintf(stderr, "%s: 0: illegal VT number\n", progname);
else if (num == 1)
fprintf(stderr, "%s: VT 1 cannot be deallocated\n",
progname);
else if (ioctl(fd, VT_DISALLOCATE, num)) {
perror("VT_DISALLOCATE");
fprintf(stderr, "%s: could not deallocate console %d\n",
progname, num);
exit(1);
}
}
exit(0);
}

121
df.c
View File

@ -1,3 +1,4 @@
/* vi: set sw=4 ts=4: */
/*
* Mini df implementation for busybox
*
@ -29,81 +30,81 @@
#include <fstab.h>
static const char df_usage[] = "df [filesystem ...]\n"
"\n" "\tPrint the filesystem space used and space available.\n";
extern const char mtab_file[]; /* Defined in utility.c */
"\n" "\tPrint the filesystem space used and space available.\n";
extern const char mtab_file[]; /* Defined in utility.c */
static int df(char *device, const char *mountPoint)
{
struct statfs s;
long blocks_used;
long blocks_percent_used;
struct fstab* fstabItem;
struct statfs s;
long blocks_used;
long blocks_percent_used;
struct fstab *fstabItem;
if (statfs(mountPoint, &s) != 0) {
perror(mountPoint);
return FALSE;
}
if (s.f_blocks > 0) {
blocks_used = s.f_blocks - s.f_bfree;
blocks_percent_used = (long)
(blocks_used * 100.0 / (blocks_used + s.f_bavail) + 0.5);
/* Note that if /etc/fstab is missing, libc can't fix up /dev/root for us */
if (strcmp (device, "/dev/root") == 0) {
fstabItem = getfsfile ("/");
if (fstabItem != NULL)
device = fstabItem->fs_spec;
if (statfs(mountPoint, &s) != 0) {
perror(mountPoint);
return FALSE;
}
printf("%-20s %9ld %9ld %9ld %3ld%% %s\n",
device,
(long) (s.f_blocks * (s.f_bsize / 1024.0)),
(long) ((s.f_blocks - s.f_bfree) * (s.f_bsize / 1024.0)),
(long) (s.f_bavail * (s.f_bsize / 1024.0)),
blocks_percent_used, mountPoint);
}
if (s.f_blocks > 0) {
blocks_used = s.f_blocks - s.f_bfree;
blocks_percent_used = (long)
(blocks_used * 100.0 / (blocks_used + s.f_bavail) + 0.5);
/* Note that if /etc/fstab is missing, libc can't fix up /dev/root for us */
if (strcmp(device, "/dev/root") == 0) {
fstabItem = getfsfile("/");
if (fstabItem != NULL)
device = fstabItem->fs_spec;
}
printf("%-20s %9ld %9ld %9ld %3ld%% %s\n",
device,
(long) (s.f_blocks * (s.f_bsize / 1024.0)),
(long) ((s.f_blocks - s.f_bfree) * (s.f_bsize / 1024.0)),
(long) (s.f_bavail * (s.f_bsize / 1024.0)),
blocks_percent_used, mountPoint);
return TRUE;
}
return TRUE;
}
extern int df_main(int argc, char **argv)
{
printf("%-20s %-14s %s %s %s %s\n", "Filesystem",
"1k-blocks", "Used", "Available", "Use%", "Mounted on");
printf("%-20s %-14s %s %s %s %s\n", "Filesystem",
"1k-blocks", "Used", "Available", "Use%", "Mounted on");
if (argc > 1) {
struct mntent *mountEntry;
int status;
if (argc > 1) {
struct mntent *mountEntry;
int status;
while (argc > 1) {
if ((mountEntry = findMountPoint(argv[1], mtab_file)) ==
0) {
fprintf(stderr, "%s: can't find mount point.\n", argv[1]);
exit( FALSE);
}
status = df(mountEntry->mnt_fsname, mountEntry->mnt_dir);
if (status != 0)
exit( status);
argc--;
argv++;
}
exit( TRUE);
} else {
FILE *mountTable;
struct mntent *mountEntry;
while (argc > 1) {
if ((mountEntry = findMountPoint(argv[1], mtab_file)) == 0) {
fprintf(stderr, "%s: can't find mount point.\n", argv[1]);
exit(FALSE);
}
status = df(mountEntry->mnt_fsname, mountEntry->mnt_dir);
if (status != 0)
exit(status);
argc--;
argv++;
}
exit(TRUE);
} else {
FILE *mountTable;
struct mntent *mountEntry;
mountTable = setmntent(mtab_file, "r");
if (mountTable == 0) {
perror(mtab_file);
exit(FALSE);
mountTable = setmntent(mtab_file, "r");
if (mountTable == 0) {
perror(mtab_file);
exit(FALSE);
}
while ((mountEntry = getmntent(mountTable))) {
df(mountEntry->mnt_fsname, mountEntry->mnt_dir);
}
endmntent(mountTable);
}
while ((mountEntry = getmntent(mountTable))) {
df(mountEntry->mnt_fsname, mountEntry->mnt_dir);
}
endmntent(mountTable);
}
exit( TRUE);
exit(TRUE);
}

162
dmesg.c
View File

@ -1,3 +1,4 @@
/* vi: set sw=4 ts=4: */
/* dmesg.c -- Print out the contents of the kernel ring buffer
* Created: Sat Oct 9 16:19:47 1993
* Revised: Thu Oct 28 21:52:17 1993 by faith@cs.unc.edu
@ -24,8 +25,8 @@
#ifndef __alpha__
# define __NR_klogctl __NR_syslog
static inline _syscall3(int, klogctl, int, type, char *, b, int, len);
#else /* __alpha__ */
static inline _syscall3(int, klogctl, int, type, char *, b, int, len);
#else /* __alpha__ */
#define klogctl syslog
#endif
@ -35,90 +36,91 @@
static const char dmesg_usage[] = "dmesg [-c] [-n level] [-s bufsize]\n";
int dmesg_main( int argc, char** argv )
int dmesg_main(int argc, char **argv)
{
char *buf;
int bufsize=8196;
int i;
int n;
int level = 0;
int lastc;
int cmd = 3;
int stopDoingThat;
char *buf;
int bufsize = 8196;
int i;
int n;
int level = 0;
int lastc;
int cmd = 3;
int stopDoingThat;
argc--;
argv++;
argc--;
argv++;
/* Parse any options */
while (argc && **argv == '-') {
stopDoingThat = FALSE;
while (stopDoingThat == FALSE && *++(*argv)) {
switch (**argv) {
case 'c':
cmd = 4;
break;
case 'n':
cmd = 8;
if (--argc == 0)
goto end;
level = atoi (*(++argv));
if (--argc > 0)
++argv;
stopDoingThat = TRUE;
break;
case 's':
if (--argc == 0)
goto end;
bufsize = atoi (*(++argv));
if (--argc > 0)
++argv;
stopDoingThat = TRUE;
break;
default:
goto end;
}
/* Parse any options */
while (argc && **argv == '-') {
stopDoingThat = FALSE;
while (stopDoingThat == FALSE && *++(*argv)) {
switch (**argv) {
case 'c':
cmd = 4;
break;
case 'n':
cmd = 8;
if (--argc == 0)
goto end;
level = atoi(*(++argv));
if (--argc > 0)
++argv;
stopDoingThat = TRUE;
break;
case 's':
if (--argc == 0)
goto end;
bufsize = atoi(*(++argv));
if (--argc > 0)
++argv;
stopDoingThat = TRUE;
break;
default:
goto end;
}
}
}
}
if (argc > 1) {
goto end;
}
if (cmd == 8) {
n = klogctl( cmd, NULL, level );
if (n < 0) {
goto klogctl_error;
}
exit( TRUE );
}
if (argc > 1) {
goto end;
}
if (bufsize < 4096) bufsize = 4096;
buf = (char*)malloc(bufsize);
n = klogctl( cmd, buf, bufsize );
if (n < 0) {
goto klogctl_error;
}
if (cmd == 8) {
n = klogctl(cmd, NULL, level);
if (n < 0) {
goto klogctl_error;
}
exit(TRUE);
}
lastc = '\n';
for (i = 0; i < n; i++) {
if ((i == 0 || buf[i - 1] == '\n') && buf[i] == '<') {
i++;
while (buf[i] >= '0' && buf[i] <= '9')
i++;
if (buf[i] == '>')
i++;
}
lastc = buf[i];
putchar( lastc );
}
if (lastc != '\n')
putchar( '\n' );
exit( TRUE);
end:
usage( dmesg_usage);
exit (FALSE);
klogctl_error:
perror( "klogctl" );
exit( FALSE );
if (bufsize < 4096)
bufsize = 4096;
buf = (char *) malloc(bufsize);
n = klogctl(cmd, buf, bufsize);
if (n < 0) {
goto klogctl_error;
}
lastc = '\n';
for (i = 0; i < n; i++) {
if ((i == 0 || buf[i - 1] == '\n') && buf[i] == '<') {
i++;
while (buf[i] >= '0' && buf[i] <= '9')
i++;
if (buf[i] == '>')
i++;
}
lastc = buf[i];
putchar(lastc);
}
if (lastc != '\n')
putchar('\n');
exit(TRUE);
end:
usage(dmesg_usage);
exit(FALSE);
klogctl_error:
perror("klogctl");
exit(FALSE);
}

197
du.c
View File

@ -1,3 +1,4 @@
/* vi: set sw=4 ts=4: */
/*
* Mini du implementation for busybox
*
@ -31,119 +32,121 @@
#include <dirent.h>
#include <stdio.h>
#include <errno.h>
#include <sys/param.h> /* for PATH_MAX */
#include <sys/param.h> /* for PATH_MAX */
typedef void (Display)(long, char *);
typedef void (Display) (long, char *);
static const char du_usage[] =
"du [OPTION]... [FILE]...\n\n"
"\t-s\tdisplay only a total for each argument\n"
;
static int du_depth = 0;
"du [OPTION]... [FILE]...\n\n"
"\t-s\tdisplay only a total for each argument\n";
static Display *print;
static int du_depth = 0;
static void
print_normal(long size, char *filename)
static Display *print;
static void print_normal(long size, char *filename)
{
fprintf(stdout, "%-7ld %s\n", size, filename);
fprintf(stdout, "%-7ld %s\n", size, filename);
}
static void
print_summary(long size, char *filename)
static void print_summary(long size, char *filename)
{
if (du_depth == 1) {
print_normal(size, filename);
}
if (du_depth == 1) {
print_normal(size, filename);
}
}
/* tiny recursive du */
static long
du(char *filename)
static long du(char *filename)
{
struct stat statbuf;
long sum;
if ((lstat(filename, &statbuf)) != 0) {
fprintf(stdout, "du: %s: %s\n", filename, strerror(errno));
return 0;
}
du_depth++;
sum = statbuf.st_blocks;
if (S_ISDIR(statbuf.st_mode)) {
DIR *dir;
struct dirent *entry;
dir = opendir(filename);
if (!dir) { return 0; }
while ((entry = readdir(dir))) {
char newfile[PATH_MAX + 1];
char *name = entry->d_name;
if ( (strcmp(name, "..") == 0)
|| (strcmp(name, ".") == 0))
{ continue; }
if (strlen(filename) + strlen(name) + 1 > PATH_MAX) {
fprintf(stderr, name_too_long, "du");
return 0;
}
sprintf(newfile, "%s/%s", filename, name);
sum += du(newfile);
}
closedir(dir);
print(sum, filename);
}
du_depth--;
return sum;
}
int
du_main(int argc, char **argv)
{
int i;
char opt;
/* default behaviour */
print = print_normal;
/* parse argv[] */
for (i = 1; i < argc; i++) {
if (argv[i][0] == '-') {
opt = argv[i][1];
switch (opt) {
case 's':
print = print_summary;
break;
case 'h':
usage(du_usage);
break;
default:
fprintf(stderr, "du: invalid option -- %c\n", opt);
usage(du_usage);
}
} else {
break;
}
}
/* go through remaining args (if any) */
if (i >= argc) {
du(".");
} else {
struct stat statbuf;
long sum;
for ( ; i < argc; i++) {
sum = du(argv[i]);
if ((sum) && (isDirectory(argv[i], FALSE))) { print_normal(sum, argv[i]); }
}
}
exit(0);
if ((lstat(filename, &statbuf)) != 0) {
fprintf(stdout, "du: %s: %s\n", filename, strerror(errno));
return 0;
}
du_depth++;
sum = statbuf.st_blocks;
if (S_ISDIR(statbuf.st_mode)) {
DIR *dir;
struct dirent *entry;
dir = opendir(filename);
if (!dir) {
return 0;
}
while ((entry = readdir(dir))) {
char newfile[PATH_MAX + 1];
char *name = entry->d_name;
if ((strcmp(name, "..") == 0)
|| (strcmp(name, ".") == 0)) {
continue;
}
if (strlen(filename) + strlen(name) + 1 > PATH_MAX) {
fprintf(stderr, name_too_long, "du");
return 0;
}
sprintf(newfile, "%s/%s", filename, name);
sum += du(newfile);
}
closedir(dir);
print(sum, filename);
}
du_depth--;
return sum;
}
/* $Id: du.c,v 1.10 2000/02/07 05:29:42 erik Exp $ */
int du_main(int argc, char **argv)
{
int i;
char opt;
/* default behaviour */
print = print_normal;
/* parse argv[] */
for (i = 1; i < argc; i++) {
if (argv[i][0] == '-') {
opt = argv[i][1];
switch (opt) {
case 's':
print = print_summary;
break;
case 'h':
usage(du_usage);
break;
default:
fprintf(stderr, "du: invalid option -- %c\n", opt);
usage(du_usage);
}
} else {
break;
}
}
/* go through remaining args (if any) */
if (i >= argc) {
du(".");
} else {
long sum;
for (; i < argc; i++) {
sum = du(argv[i]);
if ((sum) && (isDirectory(argv[i], FALSE))) {
print_normal(sum, argv[i]);
}
}
}
exit(0);
}
/* $Id: du.c,v 1.11 2000/02/08 19:58:47 erik Exp $ */

54
dutmp.c
View File

@ -1,3 +1,4 @@
/* vi: set sw=4 ts=4: */
/*
* public domain -- Dave 'Kill a Cop' Cinege <dcinege@psychosis.com>
*
@ -15,37 +16,38 @@
#include <utmp.h>
static const char dutmp_usage[] = "dutmp\n"
"\n"
"\tDump file or stdin utmp file format to stdout, pipe delimited.\n"
"\tdutmp /var/run/utmp\n";
"\n"
extern int dutmp_main (int argc, char **argv)
"\tDump file or stdin utmp file format to stdout, pipe delimited.\n"
"\tdutmp /var/run/utmp\n";
extern int dutmp_main(int argc, char **argv)
{
FILE *f = stdin;
struct utmp ut;
FILE *f = stdin;
struct utmp ut;
if ((argc < 2) || (**(argv + 1) == '-')) {
usage( dutmp_usage);
}
if ((argc < 2) || (**(argv + 1) == '-')) {
usage(dutmp_usage);
}
if ( **(++argv) == 0 ) {
f = fopen (*(++argv), "r");
if (f < 0 ) {
perror (*argv);
exit (FALSE);
}
}
if (**(++argv) == 0) {
f = fopen(*(++argv), "r");
if (f < 0) {
perror(*argv);
exit(FALSE);
}
}
while (fread (&ut, 1, sizeof (struct utmp), f)) {
// printf("%d:%d:%s:%s:%s:%s:%d:%d:%ld:%ld:%ld:%x\n",
printf ("%d|%d|%s|%s|%s|%s|%d|%d|%ld|%ld|%ld|%x\n",
ut.ut_type, ut.ut_pid, ut.ut_line,
ut.ut_id, ut.ut_user, ut.ut_host,
ut.ut_exit.e_termination, ut.ut_exit.e_exit,
ut.ut_session,
ut.ut_tv.tv_sec, ut.ut_tv.tv_usec, ut.ut_addr);
}
while (fread(&ut, 1, sizeof(struct utmp), f)) {
// printf("%d:%d:%s:%s:%s:%s:%d:%d:%ld:%ld:%ld:%x\n",
printf("%d|%d|%s|%s|%s|%s|%d|%d|%ld|%ld|%ld|%x\n",
ut.ut_type, ut.ut_pid, ut.ut_line,
ut.ut_id, ut.ut_user, ut.ut_host,
ut.ut_exit.e_termination, ut.ut_exit.e_exit,
ut.ut_session,
ut.ut_tv.tv_sec, ut.ut_tv.tv_usec, ut.ut_addr);
}
exit (TRUE);
exit(TRUE);
}

View File

@ -1,3 +1,4 @@
/* vi: set sw=4 ts=4: */
/*
* Mini sed implementation for busybox
*
@ -37,27 +38,27 @@
#include <ctype.h>
static const char sed_usage[] =
"sed [-n] -e script [file...]\n\n"
"Allowed sed scripts come in the following form:\n"
"\t'ADDR [!] COMMAND'\n\n"
"\twhere address ADDR can be:\n"
"\t NUMBER Match specified line number\n"
"\t $ Match last line\n"
"\t /REGEXP/ Match specified regexp\n"
"\t (! inverts the meaning of the match)\n\n"
"\tand COMMAND can be:\n"
"\t s/regexp/replacement/[igp]\n"
"\t which attempt to match regexp against the pattern space\n"
"\t and if successful replaces the matched portion with replacement.\n\n"
"\t aTEXT\n"
"\t which appends TEXT after the pattern space\n"
"Options:\n"
"-e\tadd the script to the commands to be executed\n"
"-n\tsuppress automatic printing of pattern space\n\n"
"sed [-n] -e script [file...]\n\n"
"Allowed sed scripts come in the following form:\n"
"\t'ADDR [!] COMMAND'\n\n"
"\twhere address ADDR can be:\n"
"\t NUMBER Match specified line number\n"
"\t $ Match last line\n"
"\t /REGEXP/ Match specified regexp\n"
"\t (! inverts the meaning of the match)\n\n"
"\tand COMMAND can be:\n"
"\t s/regexp/replacement/[igp]\n"
"\t which attempt to match regexp against the pattern space\n"
"\t and if successful replaces the matched portion with replacement.\n\n"
"\t aTEXT\n"
"\t which appends TEXT after the pattern space\n"
"Options:\n"
"-e\tadd the script to the commands to be executed\n"
"-n\tsuppress automatic printing of pattern space\n\n"
#if defined BB_REGEXP
"This version of sed matches full regular expresions.\n";
"This version of sed matches full regular expresions.\n";
#else
"This version of sed matches strings (not full regular expresions).\n";
"This version of sed matches strings (not full regular expresions).\n";
#endif
/* Flags & variables */
@ -76,276 +77,277 @@ static int negated = 0;
static inline int at_last(FILE * fp)
{
int res = 0;
int res = 0;
if (feof(fp))
return 1;
else {
char ch;
if ((ch = fgetc(fp)) == EOF)
res++;
ungetc(ch, fp);
}
return res;
if (feof(fp))
return 1;
else {
char ch;
if ((ch = fgetc(fp)) == EOF)
res++;
ungetc(ch, fp);
}
return res;
}
static void do_sed_repl(FILE * fp, char *needle, char *newNeedle,
int ignoreCase, int printFlag, int quietFlag)
int ignoreCase, int printFlag, int quietFlag)
{
int foundOne = FALSE;
char haystack[BUFSIZE];
int line = 1, doit;
int foundOne = FALSE;
char haystack[BUFSIZE];
int line = 1, doit;
while (fgets(haystack, BUFSIZE - 1, fp)) {
doit = 0;
if (addr_pattern) {
doit = !find_match(haystack, addr_pattern, FALSE);
} else if (addr_line == NO_LINE)
doit = 1;
else if (addr_line == LAST_LINE) {
if (at_last(fp))
doit = 1;
} else {
if (line == addr_line)
doit = 1;
while (fgets(haystack, BUFSIZE - 1, fp)) {
doit = 0;
if (addr_pattern) {
doit = !find_match(haystack, addr_pattern, FALSE);
} else if (addr_line == NO_LINE)
doit = 1;
else if (addr_line == LAST_LINE) {
if (at_last(fp))
doit = 1;
} else {
if (line == addr_line)
doit = 1;
}
if (negated)
doit = 1 - doit;
if (doit) {
foundOne =
replace_match(haystack, needle, newNeedle, ignoreCase);
if (foundOne == TRUE && printFlag == TRUE) {
fprintf(stdout, haystack);
}
}
if (quietFlag == FALSE) {
fprintf(stdout, haystack);
}
line++;
}
if (negated)
doit = 1 - doit;
if (doit) {
foundOne =
replace_match(haystack, needle, newNeedle, ignoreCase);
if (foundOne == TRUE && printFlag == TRUE) {
fprintf(stdout, haystack);
}
}
if (quietFlag == FALSE) {
fprintf(stdout, haystack);
}
line++;
}
}
static void do_sed_append(FILE * fp, char *appendline, int quietFlag)
{
char buffer[BUFSIZE];
int line = 1, doit;
char buffer[BUFSIZE];
int line = 1, doit;
while (fgets(buffer, BUFSIZE - 1, fp)) {
doit = 0;
if (addr_pattern) {
doit = !find_match(buffer, addr_pattern, FALSE);
} else if (addr_line == NO_LINE)
doit = 1;
else if (addr_line == LAST_LINE) {
if (at_last(fp))
doit = 1;
} else {
if (line == addr_line)
doit = 1;
}
if (negated)
doit = 1 - doit;
if (quietFlag == FALSE) {
fprintf(stdout, buffer);
}
if (doit) {
fputs(appendline, stdout);
fputc('\n', stdout);
}
while (fgets(buffer, BUFSIZE - 1, fp)) {
doit = 0;
if (addr_pattern) {
doit = !find_match(buffer, addr_pattern, FALSE);
} else if (addr_line == NO_LINE)
doit = 1;
else if (addr_line == LAST_LINE) {
if (at_last(fp))
doit = 1;
} else {
if (line == addr_line)
doit = 1;
}
if (negated)
doit = 1 - doit;
if (quietFlag == FALSE) {
fprintf(stdout, buffer);
}
if (doit) {
fputs(appendline, stdout);
fputc('\n', stdout);
}
line++;
}
line++;
}
}
extern int sed_main(int argc, char **argv)
{
FILE *fp;
char *needle = NULL, *newNeedle = NULL;
char *name;
char *cp;
int ignoreCase = FALSE;
int printFlag = FALSE;
int quietFlag = FALSE;
int stopNow;
char *line_s = NULL, saved;
char *appendline = NULL;
char *pos;
sed_function sed_f = f_none;
FILE *fp;
char *needle = NULL, *newNeedle = NULL;
char *name;
char *cp;
int ignoreCase = FALSE;
int printFlag = FALSE;
int quietFlag = FALSE;
int stopNow;
char *line_s = NULL, saved;
char *appendline = NULL;
char *pos;
sed_function sed_f = f_none;
argc--;
argv++;
if (argc < 1) {
usage(sed_usage);
}
if (**argv == '-') {
argc--;
cp = *argv++;
stopNow = FALSE;
while (*++cp && stopNow == FALSE) {
switch (*cp) {
case 'n':
quietFlag = TRUE;
break;
case 'e':
if (*(cp + 1) == 0 && --argc < 0) {
usage(sed_usage);
}
if (*++cp != 's')
cp = *argv++;
/* Read address if present */
SKIPSPACES(cp);
if (*cp == '$') {
addr_line = LAST_LINE;
cp++;
} else {
if (isdigit(*cp)) { /* LINE ADDRESS */
line_s = cp;
while (isdigit(*cp))
cp++;
if (cp > line_s) {
/* numeric line */
saved = *cp;
*cp = '\0';
addr_line = atoi(line_s);
*cp = saved;
}
} else if (*cp == '/') { /* PATTERN ADDRESS */
pos = addr_pattern = cp + 1;
pos = strchr(pos, '/');
if (!pos)
usage(sed_usage);
*pos = '\0';
cp = pos + 1;
}
}
SKIPSPACES(cp);
if (*cp == '!') {
negated++;
cp++;
}
/* Read command */
SKIPSPACES(cp);
switch (*cp) {
case 's': /* REPLACE */
if (strlen(cp) <= 3 || *(cp + 1) != '/')
break;
sed_f = f_replace;
pos = needle = cp + 2;
for (;;) {
pos = strchr(pos, '/');
if (pos == NULL) {
usage(sed_usage);
}
if (*(pos - 1) == '\\') {
pos++;
continue;
}
break;
}
*pos = 0;
newNeedle = ++pos;
for (;;) {
pos = strchr(pos, '/');
if (pos == NULL) {
usage(sed_usage);
}
if (*(pos - 1) == '\\') {
pos++;
continue;
}
break;
}
*pos = 0;
if (pos + 2 != 0) {
while (*++pos) {
switch (*pos) {
case 'i':
ignoreCase = TRUE;
break;
case 'p':
printFlag = TRUE;
break;
case 'g':
break;
default:
usage(sed_usage);
}
}
}
cp = pos;
/* fprintf(stderr, "replace '%s' with '%s'\n", needle, newNeedle); */
break;
case 'a': /* APPEND */
if (strlen(cp) < 2)
break;
sed_f = f_append;
appendline = ++cp;
/* fprintf(stderr, "append '%s'\n", appendline); */
break;
}
stopNow = TRUE;
break;
default:
argv++;
if (argc < 1) {
usage(sed_usage);
}
}
}
if (argc == 0) {
switch (sed_f) {
case f_none:
break;
case f_replace:
do_sed_repl(stdin, needle, newNeedle, ignoreCase, printFlag,
quietFlag);
break;
case f_append:
do_sed_append(stdin, appendline, quietFlag);
break;
if (**argv == '-') {
argc--;
cp = *argv++;
stopNow = FALSE;
while (*++cp && stopNow == FALSE) {
switch (*cp) {
case 'n':
quietFlag = TRUE;
break;
case 'e':
if (*(cp + 1) == 0 && --argc < 0) {
usage(sed_usage);
}
if (*++cp != 's')
cp = *argv++;
/* Read address if present */
SKIPSPACES(cp);
if (*cp == '$') {
addr_line = LAST_LINE;
cp++;
} else {
if (isdigit(*cp)) { /* LINE ADDRESS */
line_s = cp;
while (isdigit(*cp))
cp++;
if (cp > line_s) {
/* numeric line */
saved = *cp;
*cp = '\0';
addr_line = atoi(line_s);
*cp = saved;
}
} else if (*cp == '/') { /* PATTERN ADDRESS */
pos = addr_pattern = cp + 1;
pos = strchr(pos, '/');
if (!pos)
usage(sed_usage);
*pos = '\0';
cp = pos + 1;
}
}
SKIPSPACES(cp);
if (*cp == '!') {
negated++;
cp++;
}
/* Read command */
SKIPSPACES(cp);
switch (*cp) {
case 's': /* REPLACE */
if (strlen(cp) <= 3 || *(cp + 1) != '/')
break;
sed_f = f_replace;
pos = needle = cp + 2;
for (;;) {
pos = strchr(pos, '/');
if (pos == NULL) {
usage(sed_usage);
}
if (*(pos - 1) == '\\') {
pos++;
continue;
}
break;
}
*pos = 0;
newNeedle = ++pos;
for (;;) {
pos = strchr(pos, '/');
if (pos == NULL) {
usage(sed_usage);
}
if (*(pos - 1) == '\\') {
pos++;
continue;
}
break;
}
*pos = 0;
if (pos + 2 != 0) {
while (*++pos) {
switch (*pos) {
case 'i':
ignoreCase = TRUE;
break;
case 'p':
printFlag = TRUE;
break;
case 'g':
break;
default:
usage(sed_usage);
}
}
}
cp = pos;
/* fprintf(stderr, "replace '%s' with '%s'\n", needle, newNeedle); */
break;
case 'a': /* APPEND */
if (strlen(cp) < 2)
break;
sed_f = f_append;
appendline = ++cp;
/* fprintf(stderr, "append '%s'\n", appendline); */
break;
}
stopNow = TRUE;
break;
default:
usage(sed_usage);
}
}
}
} else {
while (argc-- > 0) {
name = *argv++;
fp = fopen(name, "r");
if (fp == NULL) {
perror(name);
continue;
}
if (argc == 0) {
switch (sed_f) {
case f_none:
break;
case f_replace:
do_sed_repl(stdin, needle, newNeedle, ignoreCase, printFlag,
quietFlag);
break;
case f_append:
do_sed_append(stdin, appendline, quietFlag);
break;
}
} else {
while (argc-- > 0) {
name = *argv++;
switch (sed_f) {
case f_none:
break;
case f_replace:
do_sed_repl(fp, needle, newNeedle, ignoreCase, printFlag,
quietFlag);
break;
case f_append:
do_sed_append(fp, appendline, quietFlag);
break;
}
fp = fopen(name, "r");
if (fp == NULL) {
perror(name);
continue;
}
if (ferror(fp))
perror(name);
switch (sed_f) {
case f_none:
break;
case f_replace:
do_sed_repl(fp, needle, newNeedle, ignoreCase, printFlag,
quietFlag);
break;
case f_append:
do_sed_append(fp, appendline, quietFlag);
break;
}
fclose(fp);
if (ferror(fp))
perror(name);
fclose(fp);
}
}
}
exit(TRUE);
exit(TRUE);
}

360
fbset.c
View File

@ -1,3 +1,4 @@
/* vi: set sw=4 ts=4: */
/*
* Mini fbset implementation for busybox
*
@ -48,7 +49,7 @@
#define OPT_READMODE (1 << 2)
#define CMD_HELP 0
#define CMD_FB 1
#define CMD_FB 1
#define CMD_DB 2
#define CMD_GEOMETRY 3
#define CMD_TIMING 4
@ -87,213 +88,242 @@
static unsigned int g_options = 0;
struct cmdoptions_t {
char *name;
unsigned char param_count;
unsigned char code;
char *name;
unsigned char param_count;
unsigned char code;
} g_cmdoptions[] = {
{ "-h", 0, CMD_HELP },
{ "-fb", 1, CMD_FB },
{ "-db", 1, CMD_DB },
{ "-a", 0, CMD_ALL },
{ "-i", 0, CMD_INFO },
{ "-g", 5, CMD_GEOMETRY },
{ "-t", 7, CMD_TIMING },
{ "-accel", 1, CMD_ACCEL },
{ "-hsync", 1, CMD_HSYNC },
{ "-vsync", 1, CMD_VSYNC },
{ "-laced", 1, CMD_LACED },
{ "-double", 1, CMD_DOUBLE },
{
"-h", 0, CMD_HELP}, {
"-fb", 1, CMD_FB}, {
"-db", 1, CMD_DB}, {
"-a", 0, CMD_ALL}, {
"-i", 0, CMD_INFO}, {
"-g", 5, CMD_GEOMETRY}, {
"-t", 7, CMD_TIMING}, {
"-accel", 1, CMD_ACCEL}, {
"-hsync", 1, CMD_HSYNC}, {
"-vsync", 1, CMD_VSYNC}, {
"-laced", 1, CMD_LACED}, {
"-double", 1, CMD_DOUBLE},
#ifdef BB_FBSET_FANCY
{ "--help", 0, CMD_HELP },
{ "-all", 0, CMD_ALL },
{ "-xres", 1, CMD_XRES },
{ "-yres", 1, CMD_YRES },
{ "-vxres", 1, CMD_VXRES },
{ "-vyres", 1, CMD_VYRES },
{ "-depth", 1, CMD_DEPTH },
{ "-match", 0, CMD_MATCH },
{ "--geometry", 5, CMD_GEOMETRY },
{ "-pixclock", 1, CMD_PIXCLOCK },
{ "-left", 1, CMD_LEFT },
{ "-right", 1, CMD_RIGHT },
{ "-upper", 1, CMD_UPPER },
{ "-lower", 1, CMD_LOWER },
{ "-hslen", 1, CMD_HSLEN },
{ "-vslen", 1, CMD_VSLEN },
{ "--timings", 7, CMD_TIMING },
{ "-csync", 1, CMD_CSYNC },
{ "-gsync", 1, CMD_GSYNC },
{ "-extsync", 1, CMD_EXTSYNC },
{ "-bcast", 1, CMD_BCAST },
{ "-rgba", 1, CMD_RGBA },
{ "-step", 1, CMD_STEP },
{ "-move", 1, CMD_MOVE },
{
"--help", 0, CMD_HELP}, {
"-all", 0, CMD_ALL}, {
"-xres", 1, CMD_XRES}, {
"-yres", 1, CMD_YRES}, {
"-vxres", 1, CMD_VXRES}, {
"-vyres", 1, CMD_VYRES}, {
"-depth", 1, CMD_DEPTH}, {
"-match", 0, CMD_MATCH}, {
"--geometry", 5, CMD_GEOMETRY}, {
"-pixclock", 1, CMD_PIXCLOCK}, {
"-left", 1, CMD_LEFT}, {
"-right", 1, CMD_RIGHT}, {
"-upper", 1, CMD_UPPER}, {
"-lower", 1, CMD_LOWER}, {
"-hslen", 1, CMD_HSLEN}, {
"-vslen", 1, CMD_VSLEN}, {
"--timings", 7, CMD_TIMING}, {
"-csync", 1, CMD_CSYNC}, {
"-gsync", 1, CMD_GSYNC}, {
"-extsync", 1, CMD_EXTSYNC}, {
"-bcast", 1, CMD_BCAST}, {
"-rgba", 1, CMD_RGBA}, {
"-step", 1, CMD_STEP}, {
"-move", 1, CMD_MOVE},
#endif
{ 0, 0, 0 }
{
0, 0, 0}
};
static int readmode(struct fb_var_screeninfo *base, const char *fn,
const char *mode)
const char *mode)
{
#ifdef BB_FBSET_READMODE
FILE *f;
char buf[256];
char *p = buf;
if ((f = fopen(fn, "r")) == NULL) PERROR("readmode(fopen)");
while (!feof(f)) {
fgets(buf, sizeof(buf), f);
if ((p = strstr(buf, "mode ")) || (p = strstr(buf, "mode\t"))) {
p += 5;
if ((p = strstr(buf, mode))) {
p += strlen(mode);
if (!isspace(*p) && (*p != 0) && (*p != '"') && (*p != '\r')
&& (*p != '\n')) continue; /* almost, but not quite */
while (!feof(f)) {
fgets(buf, sizeof(buf), f);
if (!strstr(buf, "endmode")) return 1;
FILE *f;
char buf[256];
char *p = buf;
if ((f = fopen(fn, "r")) == NULL)
PERROR("readmode(fopen)");
while (!feof(f)) {
fgets(buf, sizeof(buf), f);
if ((p = strstr(buf, "mode ")) || (p = strstr(buf, "mode\t"))) {
p += 5;
if ((p = strstr(buf, mode))) {
p += strlen(mode);
if (!isspace(*p) && (*p != 0) && (*p != '"')
&& (*p != '\r') && (*p != '\n'))
continue; /* almost, but not quite */
while (!feof(f)) {
fgets(buf, sizeof(buf), f);
if (!strstr(buf, "endmode"))
return 1;
}
}
}
}
}
}
#else
fprintf(stderr, "W: mode reading was disabled on this copy of fbset; ignoring request\n");
fprintf(stderr,
"W: mode reading was disabled on this copy of fbset; ignoring request\n");
#endif
return 0;
return 0;
}
static void setmode(struct fb_var_screeninfo *base,
struct fb_var_screeninfo *set)
static void setmode(struct fb_var_screeninfo *base,
struct fb_var_screeninfo *set)
{
if ((int)set->xres > 0) base->xres = set->xres;
if ((int)set->yres > 0) base->yres = set->yres;
if ((int)set->xres_virtual > 0) base->xres_virtual = set->xres_virtual;
if ((int)set->yres_virtual > 0) base->yres_virtual = set->yres_virtual;
if ((int)set->bits_per_pixel > 0) base->bits_per_pixel = set->bits_per_pixel;
if ((int) set->xres > 0)
base->xres = set->xres;
if ((int) set->yres > 0)
base->yres = set->yres;
if ((int) set->xres_virtual > 0)
base->xres_virtual = set->xres_virtual;
if ((int) set->yres_virtual > 0)
base->yres_virtual = set->yres_virtual;
if ((int) set->bits_per_pixel > 0)
base->bits_per_pixel = set->bits_per_pixel;
}
static void showmode(struct fb_var_screeninfo *v)
{
double drate = 0, hrate = 0, vrate = 0;
if (v->pixclock) {
drate = 1e12 / v->pixclock;
hrate = drate / (v->left_margin+v->xres+v->right_margin+v->hsync_len);
vrate = hrate / (v->upper_margin+v->yres+v->lower_margin+v->vsync_len);
}
printf("\nmode \"%ux%u-%u\"\n", v->xres, v->yres, (int)(vrate+0.5));
double drate = 0, hrate = 0, vrate = 0;
if (v->pixclock) {
drate = 1e12 / v->pixclock;
hrate =
drate / (v->left_margin + v->xres + v->right_margin +
v->hsync_len);
vrate =
hrate / (v->upper_margin + v->yres + v->lower_margin +
v->vsync_len);
}
printf("\nmode \"%ux%u-%u\"\n", v->xres, v->yres, (int) (vrate + 0.5));
#ifdef BB_FBSET_FANCY
printf("\t# D: %.3f MHz, H: %.3f kHz, V: %.3f Hz\n", drate/1e6, hrate/1e3,
vrate);
printf("\t# D: %.3f MHz, H: %.3f kHz, V: %.3f Hz\n", drate / 1e6,
hrate / 1e3, vrate);
#endif
printf("\tgeometry %u %u %u %u %u\n", v->xres, v->yres,
v->xres_virtual, v->yres_virtual, v->bits_per_pixel);
printf("\tgeometry %u %u %u %u %u\n", v->xres, v->yres,
v->xres_virtual, v->yres_virtual, v->bits_per_pixel);
#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,2,0)
printf("\ttimings %u %u %u %u %u %u %u\n", v->pixclock, v->left_margin,
v->right_margin, v->upper_margin, v->lower_margin, v->hsync_len,
v->vsync_len);
printf("\taccel %s\n", (v->accel_flags > 0 ? "true" : "false"));
printf("\ttimings %u %u %u %u %u %u %u\n", v->pixclock, v->left_margin,
v->right_margin, v->upper_margin, v->lower_margin, v->hsync_len,
v->vsync_len);
printf("\taccel %s\n", (v->accel_flags > 0 ? "true" : "false"));
#else
printf("\ttimings %lu %lu %lu %lu %lu %lu %lu\n", v->pixclock, v->left_margin,
v->right_margin, v->upper_margin, v->lower_margin, v->hsync_len,
v->vsync_len);
printf("\ttimings %lu %lu %lu %lu %lu %lu %lu\n", v->pixclock,
v->left_margin, v->right_margin, v->upper_margin,
v->lower_margin, v->hsync_len, v->vsync_len);
#endif
printf("\trgba %u/%u,%u/%u,%u/%u,%u/%u\n", v->red.length, v->red.offset,
v->green.length, v->green.offset, v->blue.length, v->blue.offset,
v->transp.length, v->transp.offset);
printf("endmode\n");
printf("\trgba %u/%u,%u/%u,%u/%u,%u/%u\n", v->red.length,
v->red.offset, v->green.length, v->green.offset, v->blue.length,
v->blue.offset, v->transp.length, v->transp.offset);
printf("endmode\n");
}
static void fbset_usage(void)
{
int i;
int i;
#ifndef STANDALONE
fprintf(stderr, "BusyBox v%s (%s) multi-call binary -- GPL2\n\n", BB_VER, BB_BT);
fprintf(stderr, "BusyBox v%s (%s) multi-call binary -- GPL2\n\n",
BB_VER, BB_BT);
#endif
fprintf(stderr, "Usage: fbset [options] [mode]\n");
fprintf(stderr, "\tThe following options are recognized:\n");
for (i = 0; g_cmdoptions[i].name; i++)
fprintf(stderr, "\t\t%s\n", g_cmdoptions[i].name);
exit(-1);
fprintf(stderr, "Usage: fbset [options] [mode]\n");
fprintf(stderr, "\tThe following options are recognized:\n");
for (i = 0; g_cmdoptions[i].name; i++)
fprintf(stderr, "\t\t%s\n", g_cmdoptions[i].name);
exit(-1);
}
#ifdef STANDALONE
int main(int argc, char **argv)
#else
#else
extern int fbset_main(int argc, char **argv)
#endif
{
struct fb_var_screeninfo var, varset;
int fh, i;
char *fbdev = DEFAULTFBDEV;
char *modefile = DEFAULTFBMODE;
char *thisarg, *mode = NULL;
struct fb_var_screeninfo var, varset;
int fh, i;
char *fbdev = DEFAULTFBDEV;
char *modefile = DEFAULTFBMODE;
char *thisarg, *mode = NULL;
memset(&varset, 0xFF, sizeof(varset));
/* parse cmd args.... why do they have to make things so difficult? */
argv++; argc--;
for (; argc > 0 && (thisarg = *argv); argc--, argv++) {
for (i = 0; g_cmdoptions[i].name; i++) {
if (!strcmp(thisarg, g_cmdoptions[i].name)) {
if (argc - 1 < g_cmdoptions[i].param_count) fbset_usage();
switch (g_cmdoptions[i].code) {
case CMD_HELP: fbset_usage();
case CMD_FB: fbdev = argv[1]; break;
case CMD_DB: modefile = argv[1]; break;
case CMD_GEOMETRY:
varset.xres = strtoul(argv[1],0,0);
varset.yres = strtoul(argv[2],0,0);
varset.xres_virtual = strtoul(argv[3],0,0);
varset.yres_virtual = strtoul(argv[4],0,0);
varset.bits_per_pixel = strtoul(argv[5],0,0);
break;
case CMD_TIMING:
varset.pixclock = strtoul(argv[1],0,0);
varset.left_margin = strtoul(argv[2],0,0);
varset.right_margin = strtoul(argv[3],0,0);
varset.upper_margin = strtoul(argv[4],0,0);
varset.lower_margin = strtoul(argv[5],0,0);
varset.hsync_len = strtoul(argv[6],0,0);
varset.vsync_len = strtoul(argv[7],0,0);
break;
memset(&varset, 0xFF, sizeof(varset));
/* parse cmd args.... why do they have to make things so difficult? */
argv++;
argc--;
for (; argc > 0 && (thisarg = *argv); argc--, argv++) {
for (i = 0; g_cmdoptions[i].name; i++) {
if (!strcmp(thisarg, g_cmdoptions[i].name)) {
if (argc - 1 < g_cmdoptions[i].param_count)
fbset_usage();
switch (g_cmdoptions[i].code) {
case CMD_HELP:
fbset_usage();
case CMD_FB:
fbdev = argv[1];
break;
case CMD_DB:
modefile = argv[1];
break;
case CMD_GEOMETRY:
varset.xres = strtoul(argv[1], 0, 0);
varset.yres = strtoul(argv[2], 0, 0);
varset.xres_virtual = strtoul(argv[3], 0, 0);
varset.yres_virtual = strtoul(argv[4], 0, 0);
varset.bits_per_pixel = strtoul(argv[5], 0, 0);
break;
case CMD_TIMING:
varset.pixclock = strtoul(argv[1], 0, 0);
varset.left_margin = strtoul(argv[2], 0, 0);
varset.right_margin = strtoul(argv[3], 0, 0);
varset.upper_margin = strtoul(argv[4], 0, 0);
varset.lower_margin = strtoul(argv[5], 0, 0);
varset.hsync_len = strtoul(argv[6], 0, 0);
varset.vsync_len = strtoul(argv[7], 0, 0);
break;
#ifdef BB_FBSET_FANCY
case CMD_XRES: varset.xres = strtoul(argv[1],0,0); break;
case CMD_YRES: varset.yres = strtoul(argv[1],0,0); break;
case CMD_XRES:
varset.xres = strtoul(argv[1], 0, 0);
break;
case CMD_YRES:
varset.yres = strtoul(argv[1], 0, 0);
break;
#endif
}
argc -= g_cmdoptions[i].param_count;
argv += g_cmdoptions[i].param_count;
break;
}
}
if (!g_cmdoptions[i].name) {
if (argc == 1) {
mode = *argv;
g_options |= OPT_READMODE;
} else {
fbset_usage();
}
}
argc -= g_cmdoptions[i].param_count;
argv += g_cmdoptions[i].param_count;
break;
}
}
if (!g_cmdoptions[i].name) {
if (argc == 1) {
mode = *argv;
g_options |= OPT_READMODE;
} else {
fbset_usage();
}
}
}
if ((fh = open(fbdev, O_RDONLY)) < 0) PERROR("fbset(open)");
if (ioctl(fh, FBIOGET_VSCREENINFO, &var)) PERROR("fbset(ioctl)");
if (g_options & OPT_READMODE) {
if (!readmode(&var, modefile, mode)) {
fprintf(stderr, "Unknown video mode `%s'\n", mode);
exit(1);
if ((fh = open(fbdev, O_RDONLY)) < 0)
PERROR("fbset(open)");
if (ioctl(fh, FBIOGET_VSCREENINFO, &var))
PERROR("fbset(ioctl)");
if (g_options & OPT_READMODE) {
if (!readmode(&var, modefile, mode)) {
fprintf(stderr, "Unknown video mode `%s'\n", mode);
exit(1);
}
}
}
setmode(&var, &varset);
if (g_options & OPT_CHANGE)
if (ioctl(fh, FBIOPUT_VSCREENINFO, &var)) PERROR("fbset(ioctl)");
showmode(&var);
close(fh);
return(TRUE);
setmode(&var, &varset);
if (g_options & OPT_CHANGE)
if (ioctl(fh, FBIOPUT_VSCREENINFO, &var))
PERROR("fbset(ioctl)");
showmode(&var);
close(fh);
return (TRUE);
}

View File

@ -1,3 +1,4 @@
/* vi: set sw=4 ts=4: */
/*
* Mini fdflush implementation for busybox
*
@ -29,24 +30,25 @@
extern int fdflush_main(int argc, char **argv)
{
int value;
int fd;
if ( argc <= 1 || **(argv++) == '-' ) {
usage( "fdflush device\n");
}
int value;
int fd;
fd = open(*argv, 0);
if ( fd < 0 ) {
perror(*argv);
exit(FALSE);
}
if (argc <= 1 || **(argv++) == '-') {
usage("fdflush device\n");
}
value = ioctl(fd, FDFLUSH, 0);
close(fd);
fd = open(*argv, 0);
if (fd < 0) {
perror(*argv);
exit(FALSE);
}
if ( value ) {
perror(*argv);
exit(FALSE);
}
exit (TRUE);
value = ioctl(fd, FDFLUSH, 0);
close(fd);
if (value) {
perror(*argv);
exit(FALSE);
}
exit(TRUE);
}

142
find.c
View File

@ -1,3 +1,4 @@
/* vi: set sw=4 ts=4: */
/*
* Mini find implementation for busybox
*
@ -28,92 +29,95 @@
#include <dirent.h>
static char* pattern=NULL;
static char* directory=".";
static int dereferenceFlag=FALSE;
static char *pattern = NULL;
static char *directory = ".";
static int dereferenceFlag = FALSE;
static const char find_usage[] = "find [PATH...] [EXPRESSION]\n\n"
"Search for files in a directory hierarchy. The default PATH is\n"
"the current directory; default EXPRESSION is '-print'\n\n"
"\nEXPRESSION may consist of:\n"
"\t-follow\n\t\tDereference symbolic links.\n"
"\t-name PATTERN\n\t\tFile name (with leading directories removed) matches PATTERN.\n"
"\t-print\n\t\tprint the full file name followed by a newline to stdout.\n\n"
"Search for files in a directory hierarchy. The default PATH is\n"
"the current directory; default EXPRESSION is '-print'\n\n"
"\nEXPRESSION may consist of:\n"
"\t-follow\n\t\tDereference symbolic links.\n"
"\t-name PATTERN\n\t\tFile name (with leading directories removed) matches PATTERN.\n"
"\t-print\n\t\tprint the full file name followed by a newline to stdout.\n\n"
#if defined BB_REGEXP
"This version of find matches full regular expresions.\n";
"This version of find matches full regular expresions.\n";
#else
"This version of find matches strings (not regular expresions).\n";
"This version of find matches strings (not regular expresions).\n";
#endif
static int fileAction(const char *fileName, struct stat* statbuf)
static int fileAction(const char *fileName, struct stat *statbuf)
{
if (pattern==NULL)
fprintf(stdout, "%s\n", fileName);
else {
char* tmp = strrchr( fileName, '/');
if (tmp == NULL)
tmp = (char*)fileName;
else
tmp++;
if (check_wildcard_match(tmp, pattern) == TRUE)
fprintf(stdout, "%s\n", fileName);
}
return( TRUE);
if (pattern == NULL)
fprintf(stdout, "%s\n", fileName);
else {
char *tmp = strrchr(fileName, '/');
if (tmp == NULL)
tmp = (char *) fileName;
else
tmp++;
if (check_wildcard_match(tmp, pattern) == TRUE)
fprintf(stdout, "%s\n", fileName);
}
return (TRUE);
}
int find_main(int argc, char **argv)
{
/* peel off the "find" */
argc--;
argv++;
if ( argc > 0 && **argv != '-') {
directory = *argv;
/* peel off the "find" */
argc--;
argv++;
}
/* Parse any options */
while (argc > 0 && **argv == '-') {
int stopit=FALSE;
while (*++(*argv) && stopit==FALSE) switch (**argv) {
case 'f':
if (strcmp(*argv, "follow")==0) {
argc--;
argv++;
dereferenceFlag=TRUE;
}
break;
case 'n':
if (strcmp(*argv, "name")==0) {
if (argc-- > 1) {
pattern = *(++argv);
stopit = TRUE;
} else {
usage (find_usage);
}
}
break;
case '-':
/* Ignore all long options */
break;
default:
usage (find_usage);
if (argc > 0 && **argv != '-') {
directory = *argv;
argc--;
argv++;
}
if (argc-- > 1)
argv++;
if (**argv != '-')
break;
else
break;
}
if (recursiveAction(directory, TRUE, FALSE, FALSE,
fileAction, fileAction) == FALSE) {
exit( FALSE);
}
/* Parse any options */
while (argc > 0 && **argv == '-') {
int stopit = FALSE;
exit(TRUE);
while (*++(*argv) && stopit == FALSE)
switch (**argv) {
case 'f':
if (strcmp(*argv, "follow") == 0) {
argc--;
argv++;
dereferenceFlag = TRUE;
}
break;
case 'n':
if (strcmp(*argv, "name") == 0) {
if (argc-- > 1) {
pattern = *(++argv);
stopit = TRUE;
} else {
usage(find_usage);
}
}
break;
case '-':
/* Ignore all long options */
break;
default:
usage(find_usage);
}
if (argc-- > 1)
argv++;
if (**argv != '-')
break;
else
break;
}
if (recursiveAction(directory, TRUE, FALSE, FALSE,
fileAction, fileAction) == FALSE) {
exit(FALSE);
}
exit(TRUE);
}

View File

@ -1,3 +1,4 @@
/* vi: set sw=4 ts=4: */
/*
* Mini find implementation for busybox
*
@ -28,92 +29,95 @@
#include <dirent.h>
static char* pattern=NULL;
static char* directory=".";
static int dereferenceFlag=FALSE;
static char *pattern = NULL;
static char *directory = ".";
static int dereferenceFlag = FALSE;
static const char find_usage[] = "find [PATH...] [EXPRESSION]\n\n"
"Search for files in a directory hierarchy. The default PATH is\n"
"the current directory; default EXPRESSION is '-print'\n\n"
"\nEXPRESSION may consist of:\n"
"\t-follow\n\t\tDereference symbolic links.\n"
"\t-name PATTERN\n\t\tFile name (with leading directories removed) matches PATTERN.\n"
"\t-print\n\t\tprint the full file name followed by a newline to stdout.\n\n"
"Search for files in a directory hierarchy. The default PATH is\n"
"the current directory; default EXPRESSION is '-print'\n\n"
"\nEXPRESSION may consist of:\n"
"\t-follow\n\t\tDereference symbolic links.\n"
"\t-name PATTERN\n\t\tFile name (with leading directories removed) matches PATTERN.\n"
"\t-print\n\t\tprint the full file name followed by a newline to stdout.\n\n"
#if defined BB_REGEXP
"This version of find matches full regular expresions.\n";
"This version of find matches full regular expresions.\n";
#else
"This version of find matches strings (not regular expresions).\n";
"This version of find matches strings (not regular expresions).\n";
#endif
static int fileAction(const char *fileName, struct stat* statbuf)
static int fileAction(const char *fileName, struct stat *statbuf)
{
if (pattern==NULL)
fprintf(stdout, "%s\n", fileName);
else {
char* tmp = strrchr( fileName, '/');
if (tmp == NULL)
tmp = (char*)fileName;
else
tmp++;
if (check_wildcard_match(tmp, pattern) == TRUE)
fprintf(stdout, "%s\n", fileName);
}
return( TRUE);
if (pattern == NULL)
fprintf(stdout, "%s\n", fileName);
else {
char *tmp = strrchr(fileName, '/');
if (tmp == NULL)
tmp = (char *) fileName;
else
tmp++;
if (check_wildcard_match(tmp, pattern) == TRUE)
fprintf(stdout, "%s\n", fileName);
}
return (TRUE);
}
int find_main(int argc, char **argv)
{
/* peel off the "find" */
argc--;
argv++;
if ( argc > 0 && **argv != '-') {
directory = *argv;
/* peel off the "find" */
argc--;
argv++;
}
/* Parse any options */
while (argc > 0 && **argv == '-') {
int stopit=FALSE;
while (*++(*argv) && stopit==FALSE) switch (**argv) {
case 'f':
if (strcmp(*argv, "follow")==0) {
argc--;
argv++;
dereferenceFlag=TRUE;
}
break;
case 'n':
if (strcmp(*argv, "name")==0) {
if (argc-- > 1) {
pattern = *(++argv);
stopit = TRUE;
} else {
usage (find_usage);
}
}
break;
case '-':
/* Ignore all long options */
break;
default:
usage (find_usage);
if (argc > 0 && **argv != '-') {
directory = *argv;
argc--;
argv++;
}
if (argc-- > 1)
argv++;
if (**argv != '-')
break;
else
break;
}
if (recursiveAction(directory, TRUE, FALSE, FALSE,
fileAction, fileAction) == FALSE) {
exit( FALSE);
}
/* Parse any options */
while (argc > 0 && **argv == '-') {
int stopit = FALSE;
exit(TRUE);
while (*++(*argv) && stopit == FALSE)
switch (**argv) {
case 'f':
if (strcmp(*argv, "follow") == 0) {
argc--;
argv++;
dereferenceFlag = TRUE;
}
break;
case 'n':
if (strcmp(*argv, "name") == 0) {
if (argc-- > 1) {
pattern = *(++argv);
stopit = TRUE;
} else {
usage(find_usage);
}
}
break;
case '-':
/* Ignore all long options */
break;
default:
usage(find_usage);
}
if (argc-- > 1)
argv++;
if (**argv != '-')
break;
else
break;
}
if (recursiveAction(directory, TRUE, FALSE, FALSE,
fileAction, fileAction) == FALSE) {
exit(FALSE);
}
exit(TRUE);
}

View File

@ -1,3 +1,4 @@
/* vi: set sw=4 ts=4: */
/*
* Mini grep implementation for busybox
*
@ -40,126 +41,125 @@
#include <ctype.h>
static const char grep_usage[] =
"grep [OPTIONS]... PATTERN [FILE]...\n\n"
"Search for PATTERN in each FILE or standard input.\n\n"
"OPTIONS:\n"
"\t-h\tsuppress the prefixing filename on output\n"
"\t-i\tignore case distinctions\n"
"\t-n\tprint line number with output lines\n"
"\t-q\tbe quiet. Returns 0 if result was found, 1 otherwise\n\n"
"grep [OPTIONS]... PATTERN [FILE]...\n\n"
"Search for PATTERN in each FILE or standard input.\n\n"
"OPTIONS:\n"
"\t-h\tsuppress the prefixing filename on output\n"
"\t-i\tignore case distinctions\n"
"\t-n\tprint line number with output lines\n"
"\t-q\tbe quiet. Returns 0 if result was found, 1 otherwise\n\n"
#if defined BB_REGEXP
"This version of grep matches full regular expresions.\n";
"This version of grep matches full regular expresions.\n";
#else
"This version of grep matches strings (not regular expresions).\n";
"This version of grep matches strings (not regular expresions).\n";
#endif
static int match = FALSE, beQuiet = FALSE;
static void do_grep(FILE *fp, char* needle, char *fileName, int tellName, int ignoreCase, int tellLine)
static void do_grep(FILE * fp, char *needle, char *fileName, int tellName,
int ignoreCase, int tellLine)
{
char *cp;
long line = 0;
char haystack[BUF_SIZE];
char *cp;
long line = 0;
char haystack[BUF_SIZE];
while (fgets (haystack, sizeof (haystack), fp)) {
line++;
cp = &haystack[strlen (haystack) - 1];
while (fgets(haystack, sizeof(haystack), fp)) {
line++;
cp = &haystack[strlen(haystack) - 1];
if (*cp != '\n')
fprintf (stderr, "%s: Line too long\n", fileName);
if (*cp != '\n')
fprintf(stderr, "%s: Line too long\n", fileName);
if (find_match(haystack, needle, ignoreCase) == TRUE) {
if (tellName==TRUE)
printf ("%s:", fileName);
if (find_match(haystack, needle, ignoreCase) == TRUE) {
if (tellName == TRUE)
printf("%s:", fileName);
if (tellLine==TRUE)
printf ("%ld:", line);
if (tellLine == TRUE)
printf("%ld:", line);
if (beQuiet==FALSE)
fputs (haystack, stdout);
if (beQuiet == FALSE)
fputs(haystack, stdout);
match = TRUE;
match = TRUE;
}
}
}
}
extern int grep_main (int argc, char **argv)
extern int grep_main(int argc, char **argv)
{
FILE *fp;
char *cp;
char *needle;
char *fileName;
int tellName=TRUE;
int ignoreCase=TRUE;
int tellLine=FALSE;
FILE *fp;
char *cp;
char *needle;
char *fileName;
int tellName = TRUE;
int ignoreCase = TRUE;
int tellLine = FALSE;
ignoreCase = FALSE;
tellLine = FALSE;
ignoreCase = FALSE;
tellLine = FALSE;
argc--;
argv++;
if (argc < 1) {
usage(grep_usage);
}
if (**argv == '-') {
argc--;
cp = *argv++;
while (*++cp)
switch (*cp) {
case 'i':
ignoreCase = TRUE;
break;
case 'h':
tellName = FALSE;
break;
case 'n':
tellLine = TRUE;
break;
case 'q':
beQuiet = TRUE;
break;
default:
argv++;
if (argc < 1) {
usage(grep_usage);
}
}
needle = *argv++;
argc--;
if (argc==0) {
do_grep( stdin, needle, "stdin", FALSE, ignoreCase, tellLine);
} else {
/* Never print the filename for just one file */
if (argc==1)
tellName=FALSE;
while (argc-- > 0) {
fileName = *argv++;
fp = fopen (fileName, "r");
if (fp == NULL) {
perror (fileName);
continue;
}
do_grep( fp, needle, fileName, tellName, ignoreCase, tellLine);
if (ferror (fp))
perror (fileName);
fclose (fp);
}
}
exit(match);
if (**argv == '-') {
argc--;
cp = *argv++;
while (*++cp)
switch (*cp) {
case 'i':
ignoreCase = TRUE;
break;
case 'h':
tellName = FALSE;
break;
case 'n':
tellLine = TRUE;
break;
case 'q':
beQuiet = TRUE;
break;
default:
usage(grep_usage);
}
}
needle = *argv++;
argc--;
if (argc == 0) {
do_grep(stdin, needle, "stdin", FALSE, ignoreCase, tellLine);
} else {
/* Never print the filename for just one file */
if (argc == 1)
tellName = FALSE;
while (argc-- > 0) {
fileName = *argv++;
fp = fopen(fileName, "r");
if (fp == NULL) {
perror(fileName);
continue;
}
do_grep(fp, needle, fileName, tellName, ignoreCase, tellLine);
if (ferror(fp))
perror(fileName);
fclose(fp);
}
}
exit(match);
}
/* END CODE */

6
free.c
View File

@ -1,3 +1,4 @@
/* vi: set sw=4 ts=4: */
/*
* Mini free implementation for busybox
*
@ -30,6 +31,7 @@
extern int free_main(int argc, char **argv)
{
char* cmd[] = { "cat", "/proc/meminfo", "\0" };
exit(cat_main( 3, cmd));
char *cmd[] = { "cat", "/proc/meminfo", "\0" };
exit(cat_main(3, cmd));
}

File diff suppressed because it is too large Load Diff

190
grep.c
View File

@ -1,3 +1,4 @@
/* vi: set sw=4 ts=4: */
/*
* Mini grep implementation for busybox
*
@ -40,126 +41,125 @@
#include <ctype.h>
static const char grep_usage[] =
"grep [OPTIONS]... PATTERN [FILE]...\n\n"
"Search for PATTERN in each FILE or standard input.\n\n"
"OPTIONS:\n"
"\t-h\tsuppress the prefixing filename on output\n"
"\t-i\tignore case distinctions\n"
"\t-n\tprint line number with output lines\n"
"\t-q\tbe quiet. Returns 0 if result was found, 1 otherwise\n\n"
"grep [OPTIONS]... PATTERN [FILE]...\n\n"
"Search for PATTERN in each FILE or standard input.\n\n"
"OPTIONS:\n"
"\t-h\tsuppress the prefixing filename on output\n"
"\t-i\tignore case distinctions\n"
"\t-n\tprint line number with output lines\n"
"\t-q\tbe quiet. Returns 0 if result was found, 1 otherwise\n\n"
#if defined BB_REGEXP
"This version of grep matches full regular expresions.\n";
"This version of grep matches full regular expresions.\n";
#else
"This version of grep matches strings (not regular expresions).\n";
"This version of grep matches strings (not regular expresions).\n";
#endif
static int match = FALSE, beQuiet = FALSE;
static void do_grep(FILE *fp, char* needle, char *fileName, int tellName, int ignoreCase, int tellLine)
static void do_grep(FILE * fp, char *needle, char *fileName, int tellName,
int ignoreCase, int tellLine)
{
char *cp;
long line = 0;
char haystack[BUF_SIZE];
char *cp;
long line = 0;
char haystack[BUF_SIZE];
while (fgets (haystack, sizeof (haystack), fp)) {
line++;
cp = &haystack[strlen (haystack) - 1];
while (fgets(haystack, sizeof(haystack), fp)) {
line++;
cp = &haystack[strlen(haystack) - 1];
if (*cp != '\n')
fprintf (stderr, "%s: Line too long\n", fileName);
if (*cp != '\n')
fprintf(stderr, "%s: Line too long\n", fileName);
if (find_match(haystack, needle, ignoreCase) == TRUE) {
if (tellName==TRUE)
printf ("%s:", fileName);
if (find_match(haystack, needle, ignoreCase) == TRUE) {
if (tellName == TRUE)
printf("%s:", fileName);
if (tellLine==TRUE)
printf ("%ld:", line);
if (tellLine == TRUE)
printf("%ld:", line);
if (beQuiet==FALSE)
fputs (haystack, stdout);
if (beQuiet == FALSE)
fputs(haystack, stdout);
match = TRUE;
match = TRUE;
}
}
}
}
extern int grep_main (int argc, char **argv)
extern int grep_main(int argc, char **argv)
{
FILE *fp;
char *cp;
char *needle;
char *fileName;
int tellName=TRUE;
int ignoreCase=TRUE;
int tellLine=FALSE;
FILE *fp;
char *cp;
char *needle;
char *fileName;
int tellName = TRUE;
int ignoreCase = TRUE;
int tellLine = FALSE;
ignoreCase = FALSE;
tellLine = FALSE;
ignoreCase = FALSE;
tellLine = FALSE;
argc--;
argv++;
if (argc < 1) {
usage(grep_usage);
}
if (**argv == '-') {
argc--;
cp = *argv++;
while (*++cp)
switch (*cp) {
case 'i':
ignoreCase = TRUE;
break;
case 'h':
tellName = FALSE;
break;
case 'n':
tellLine = TRUE;
break;
case 'q':
beQuiet = TRUE;
break;
default:
argv++;
if (argc < 1) {
usage(grep_usage);
}
}
needle = *argv++;
argc--;
if (argc==0) {
do_grep( stdin, needle, "stdin", FALSE, ignoreCase, tellLine);
} else {
/* Never print the filename for just one file */
if (argc==1)
tellName=FALSE;
while (argc-- > 0) {
fileName = *argv++;
fp = fopen (fileName, "r");
if (fp == NULL) {
perror (fileName);
continue;
}
do_grep( fp, needle, fileName, tellName, ignoreCase, tellLine);
if (ferror (fp))
perror (fileName);
fclose (fp);
}
}
exit(match);
if (**argv == '-') {
argc--;
cp = *argv++;
while (*++cp)
switch (*cp) {
case 'i':
ignoreCase = TRUE;
break;
case 'h':
tellName = FALSE;
break;
case 'n':
tellLine = TRUE;
break;
case 'q':
beQuiet = TRUE;
break;
default:
usage(grep_usage);
}
}
needle = *argv++;
argc--;
if (argc == 0) {
do_grep(stdin, needle, "stdin", FALSE, ignoreCase, tellLine);
} else {
/* Never print the filename for just one file */
if (argc == 1)
tellName = FALSE;
while (argc-- > 0) {
fileName = *argv++;
fp = fopen(fileName, "r");
if (fp == NULL) {
perror(fileName);
continue;
}
do_grep(fp, needle, fileName, tellName, ignoreCase, tellLine);
if (ferror(fp))
perror(fileName);
fclose(fp);
}
}
exit(match);
}
/* END CODE */

2354
gunzip.c

File diff suppressed because it is too large Load Diff

2920
gzip.c

File diff suppressed because it is too large Load Diff

9
halt.c
View File

@ -1,3 +1,4 @@
/* vi: set sw=4 ts=4: */
/*
* Mini halt implementation for busybox
*
@ -23,10 +24,8 @@
#include "internal.h"
#include <signal.h>
extern int
halt_main(int argc, char ** argv)
extern int halt_main(int argc, char **argv)
{
/* don't assume init's pid == 1 */
exit( kill(findInitPid(), SIGUSR1));
/* don't assume init's pid == 1 */
exit(kill(findInitPid(), SIGUSR1));
}

134
head.c
View File

@ -1,3 +1,4 @@
/* vi: set sw=4 ts=4: */
/*
* Mini head implementation for busybox
*
@ -26,83 +27,86 @@
#include <stdio.h>
const char head_usage[] =
"head [OPTION] [FILE]...\n\n"
"Print first 10 lines of each FILE to standard output.\n"
"With more than one FILE, precede each with a header giving the\n"
"file name. With no FILE, or when FILE is -, read standard input.\n\n"
"Options:\n"
"\t-n NUM\t\tPrint first NUM lines instead of first 10\n";
"head [OPTION] [FILE]...\n\n"
"Print first 10 lines of each FILE to standard output.\n"
"With more than one FILE, precede each with a header giving the\n"
"file name. With no FILE, or when FILE is -, read standard input.\n\n"
int
head(int len, FILE *src)
"Options:\n" "\t-n NUM\t\tPrint first NUM lines instead of first 10\n";
int head(int len, FILE * src)
{
int i;
char buffer[1024];
int i;
char buffer[1024];
for (i = 0; i < len; i++) {
fgets(buffer, 1024, src);
if (feof(src)) { break; }
fputs(buffer, stdout);
}
return 0;
for (i = 0; i < len; i++) {
fgets(buffer, 1024, src);
if (feof(src)) {
break;
}
fputs(buffer, stdout);
}
return 0;
}
/* BusyBoxed head(1) */
int
head_main(int argc, char **argv)
int head_main(int argc, char **argv)
{
char opt;
int len = 10, tmplen, i;
char opt;
int len = 10, tmplen, i;
/* parse argv[] */
for (i = 1; i < argc; i++) {
if (argv[i][0] == '-') {
opt = argv[i][1];
switch (opt) {
case 'n':
tmplen = 0;
if (++i < argc)
tmplen = atoi(argv[i]);
if (tmplen < 1)
usage(head_usage);
len = tmplen;
break;
case '-':
case 'h':
usage(head_usage);
default:
fprintf(stderr, "head: invalid option -- %c\n", opt);
usage(head_usage);
}
} else {
break;
}
}
/* get rest of argv[] or stdin if nothing's left */
if (i >= argc) {
head(len, stdin);
/* parse argv[] */
for (i = 1; i < argc; i++) {
if (argv[i][0] == '-') {
opt = argv[i][1];
switch (opt) {
case 'n':
tmplen = 0;
if (++i < argc)
tmplen = atoi(argv[i]);
if (tmplen < 1)
usage(head_usage);
len = tmplen;
break;
case '-':
case 'h':
usage(head_usage);
default:
fprintf(stderr, "head: invalid option -- %c\n", opt);
usage(head_usage);
}
} else {
break;
}
}
int need_headers = ((argc - i) > 1);
/* get rest of argv[] or stdin if nothing's left */
if (i >= argc) {
head(len, stdin);
for (; i < argc; i++) {
FILE *src;
} else {
int need_headers = ((argc - i) > 1);
for ( ; i < argc; i++) {
FILE *src;
src = fopen(argv[i], "r");
if (!src) {
fprintf(stderr,"head: %s: %s\n", argv[i], strerror(errno));
} else {
/* emulating GNU behaviour */
if (need_headers) {
fprintf(stdout, "==> %s <==\n", argv[i]);
src = fopen(argv[i], "r");
if (!src) {
fprintf(stderr, "head: %s: %s\n", argv[i],
strerror(errno));
} else {
/* emulating GNU behaviour */
if (need_headers) {
fprintf(stdout, "==> %s <==\n", argv[i]);
}
head(len, src);
if (i < argc - 1) {
fprintf(stdout, "\n");
}
}
}
head(len, src);
if (i < argc - 1) {
fprintf(stdout, "\n");
}
}
}
}
exit(0);
exit(0);
}
/* $Id: head.c,v 1.7 2000/02/07 05:29:42 erik Exp $ */
/* $Id: head.c,v 1.8 2000/02/08 19:58:47 erik Exp $ */

View File

@ -1,3 +1,4 @@
/* vi: set sw=4 ts=4: */
/*
* Mini hostid implementation for busybox
*
@ -22,7 +23,8 @@
#include "internal.h"
#include <stdio.h>
extern int hostid_main(int argc, char **argv) {
printf ("%lx\n", gethostid());
exit( TRUE);
extern int hostid_main(int argc, char **argv)
{
printf("%lx\n", gethostid());
exit(TRUE);
}

View File

@ -1,5 +1,6 @@
/* vi: set sw=4 ts=4: */
/*
* $Id: hostname.c,v 1.6 2000/02/07 05:29:42 erik Exp $
* $Id: hostname.c,v 1.7 2000/02/08 19:58:47 erik Exp $
* Mini hostname implementation for busybox
*
* Copyright (C) 1999 by Randolph Chung <tausq@debian.org>
@ -29,110 +30,116 @@
#include <unistd.h>
#include <stdio.h>
static const char* hostname_usage =
"hostname [OPTION] {hostname | -F file}\n\n"
"Get or set the hostname or DNS domain name. If a hostname is given\n"
"(or a file with the -F parameter), the host name will be set.\n\n"
"Options:\n"
"\t-s\t\tShort\n"
"\t-i\t\tAddresses for the hostname\n"
"\t-d\t\tDNS domain name\n"
"\t-F FILE\t\tUse the contents of FILE to specify the hostname\n";
static const char *hostname_usage =
"hostname [OPTION] {hostname | -F file}\n\n"
"Get or set the hostname or DNS domain name. If a hostname is given\n"
"(or a file with the -F parameter), the host name will be set.\n\n"
"Options:\n"
"\t-s\t\tShort\n"
"\t-i\t\tAddresses for the hostname\n"
"\t-d\t\tDNS domain name\n"
"\t-F FILE\t\tUse the contents of FILE to specify the hostname\n";
void do_sethostname(char *s, int isfile)
{
FILE *f;
char buf[255];
if (!s) return;
if (!isfile) {
if (sethostname(s, strlen(s)) < 0) {
if (errno == EPERM)
fprintf(stderr, "hostname: you must be root to change the hostname\n");
else
perror("sethostname");
exit(1);
}
} else {
if ((f = fopen(s, "r")) == NULL) {
perror(s);
exit(1);
FILE *f;
char buf[255];
if (!s)
return;
if (!isfile) {
if (sethostname(s, strlen(s)) < 0) {
if (errno == EPERM)
fprintf(stderr,
"hostname: you must be root to change the hostname\n");
else
perror("sethostname");
exit(1);
}
} else {
fgets(buf, 255, f);
fclose(f);
if (buf[strlen(buf)-1] == '\n') buf[strlen(buf)-1] = 0;
if (sethostname(buf, strlen(buf)) < 0) {
perror("sethostname");
exit(1);
}
if ((f = fopen(s, "r")) == NULL) {
perror(s);
exit(1);
} else {
fgets(buf, 255, f);
fclose(f);
if (buf[strlen(buf) - 1] == '\n')
buf[strlen(buf) - 1] = 0;
if (sethostname(buf, strlen(buf)) < 0) {
perror("sethostname");
exit(1);
}
}
}
}
}
int hostname_main(int argc, char **argv)
{
int opt_short = 0;
int opt_domain = 0;
int opt_ip = 0;
struct hostent *h;
char *filename = NULL;
char buf[255];
char *s = NULL;
if (argc < 1) usage(hostname_usage);
int opt_short = 0;
int opt_domain = 0;
int opt_ip = 0;
struct hostent *h;
char *filename = NULL;
char buf[255];
char *s = NULL;
while (--argc > 0 && **(++argv) == '-') {
while (*(++(*argv))) {
switch (**argv) {
case 's':
opt_short = 1;
break;
case 'i':
opt_ip = 1;
break;
case 'd':
opt_domain = 1;
break;
case 'F':
filename = optarg;
if (--argc == 0) {
usage(hostname_usage);
}
filename = *(++argv);
break;
default:
if (argc < 1)
usage(hostname_usage);
}
if (filename!=NULL)
break;
}
}
if (argc >= 1) {
do_sethostname(*argv, 0);
} else if (filename!=NULL) {
do_sethostname(filename, 1);
} else {
gethostname(buf, 255);
if (opt_short) {
s = strchr(buf, '.');
if (!s) s = buf; *s = 0;
printf("%s\n", buf);
} else if (opt_domain) {
s = strchr(buf, '.');
printf("%s\n", (s ? s+1 : ""));
} else if (opt_ip) {
h = gethostbyname(buf);
if (!h) {
printf("Host not found\n");
exit(1);
}
printf("%s\n", inet_ntoa(*(struct in_addr *)(h->h_addr)));
} else {
printf("%s\n", buf);
}
}
exit( 0);
while (--argc > 0 && **(++argv) == '-') {
while (*(++(*argv))) {
switch (**argv) {
case 's':
opt_short = 1;
break;
case 'i':
opt_ip = 1;
break;
case 'd':
opt_domain = 1;
break;
case 'F':
filename = optarg;
if (--argc == 0) {
usage(hostname_usage);
}
filename = *(++argv);
break;
default:
usage(hostname_usage);
}
if (filename != NULL)
break;
}
}
if (argc >= 1) {
do_sethostname(*argv, 0);
} else if (filename != NULL) {
do_sethostname(filename, 1);
} else {
gethostname(buf, 255);
if (opt_short) {
s = strchr(buf, '.');
if (!s)
s = buf;
*s = 0;
printf("%s\n", buf);
} else if (opt_domain) {
s = strchr(buf, '.');
printf("%s\n", (s ? s + 1 : ""));
} else if (opt_ip) {
h = gethostbyname(buf);
if (!h) {
printf("Host not found\n");
exit(1);
}
printf("%s\n", inet_ntoa(*(struct in_addr *) (h->h_addr)));
} else {
printf("%s\n", buf);
}
}
exit(0);
}

1309
init.c

File diff suppressed because it is too large Load Diff

View File

@ -1,3 +1,4 @@
/* vi: set sw=4 ts=4: */
/*
* Mini halt implementation for busybox
*
@ -23,10 +24,8 @@
#include "internal.h"
#include <signal.h>
extern int
halt_main(int argc, char ** argv)
extern int halt_main(int argc, char **argv)
{
/* don't assume init's pid == 1 */
exit( kill(findInitPid(), SIGUSR1));
/* don't assume init's pid == 1 */
exit(kill(findInitPid(), SIGUSR1));
}

File diff suppressed because it is too large Load Diff

View File

@ -1,3 +1,4 @@
/* vi: set sw=4 ts=4: */
/*
* Mini poweroff implementation for busybox
*
@ -23,9 +24,8 @@
#include "internal.h"
#include <signal.h>
extern int
poweroff_main(int argc, char ** argv)
extern int poweroff_main(int argc, char **argv)
{
/* don't assume init's pid == 1 */
exit( kill(findInitPid(), SIGUSR2));
/* don't assume init's pid == 1 */
exit(kill(findInitPid(), SIGUSR2));
}

View File

@ -1,3 +1,4 @@
/* vi: set sw=4 ts=4: */
/*
* Mini reboot implementation for busybox
*
@ -23,9 +24,8 @@
#include "internal.h"
#include <signal.h>
extern int
reboot_main(int argc, char ** argv)
extern int reboot_main(int argc, char **argv)
{
/* don't assume init's pid == 1 */
exit( kill(findInitPid(), SIGINT));
/* don't assume init's pid == 1 */
exit(kill(findInitPid(), SIGINT));
}

234
insmod.c
View File

@ -1,3 +1,4 @@
/* vi: set sw=4 ts=4: */
/*
* Mini insmod implementation for busybox
*
@ -41,8 +42,7 @@
/* Some firendly syscalls to cheer everyone's day... */
_syscall2(int, init_module, const char *, name,
const struct module *, info)
const struct module *, info)
#ifndef BB_RMMOD
_syscall1(int, delete_module, const char *, name)
#else
@ -52,155 +52,159 @@ extern int delete_module(const char *);
#if defined(__i386__) || defined(__m68k__) || defined(__arm__)
/* Jump through hoops to fixup error return codes */
#define __NR__create_module __NR_create_module
static inline _syscall2(long, _create_module, const char *, name, size_t, size)
static inline _syscall2(long, _create_module, const char *, name, size_t,
size)
unsigned long create_module(const char *name, size_t size)
{
long ret = _create_module(name, size);
if (ret == -1 && errno > 125) {
ret = -errno;
errno = 0;
}
return ret;
long ret = _create_module(name, size);
if (ret == -1 && errno > 125) {
ret = -errno;
errno = 0;
}
return ret;
}
#else
_syscall2(unsigned long, create_module, const char *, name, size_t, size)
#endif
static char m_filename[PATH_MAX + 1] = "\0";
static char m_fullName[PATH_MAX + 1] = "\0";
static const char insmod_usage[] =
"insmod [OPTION]... MODULE [symbol=value]...\n\n"
"Loads the specified kernel modules into the kernel.\n\n"
"Options:\n"
"\t-f\tForce module to load into the wrong kernel version.\n"
"\t-k\tMake module autoclean-able.\n";
"insmod [OPTION]... MODULE [symbol=value]...\n\n"
"Loads the specified kernel modules into the kernel.\n\n"
"Options:\n"
"\t-f\tForce module to load into the wrong kernel version.\n"
"\t-k\tMake module autoclean-able.\n";
static int findNamedModule(const char *fileName, struct stat* statbuf)
static int findNamedModule(const char *fileName, struct stat *statbuf)
{
if (m_fullName[0]=='\0')
return( FALSE);
else {
char* tmp = strrchr( fileName, '/');
if (tmp == NULL)
tmp = (char*)fileName;
else
tmp++;
if (check_wildcard_match(tmp, m_fullName) == TRUE) {
/* Stop searching if we find a match */
memcpy(m_filename, fileName, strlen(fileName));
return( FALSE);
if (m_fullName[0] == '\0')
return (FALSE);
else {
char *tmp = strrchr(fileName, '/');
if (tmp == NULL)
tmp = (char *) fileName;
else
tmp++;
if (check_wildcard_match(tmp, m_fullName) == TRUE) {
/* Stop searching if we find a match */
memcpy(m_filename, fileName, strlen(fileName));
return (FALSE);
}
}
}
return( TRUE);
return (TRUE);
}
extern int insmod_main(int argc, char **argv)
{
int len;
char *tmp;
char m_name[PATH_MAX + 1] ="\0";
FILE *fp;
int len;
char *tmp;
char m_name[PATH_MAX + 1] = "\0";
FILE *fp;
if (argc<=1) {
usage( insmod_usage);
}
/* Parse any options */
while (--argc > 0 && **(++argv) == '-') {
while (*(++(*argv))) {
switch (**argv) {
case 'f':
break;
case 'k':
break;
default:
if (argc <= 1) {
usage(insmod_usage);
}
}
}
if (argc <= 0 )
usage(insmod_usage);
/* Grab the module name */
if ((tmp = strrchr(*argv, '/')) != NULL)
tmp++;
else
tmp = *argv;
len = strlen(tmp);
if (len > 2 && tmp[len - 2] == '.' && tmp[len - 1] == 'o')
len -= 2;
memcpy(m_name, tmp, len);
strcpy(m_fullName, m_name);
strcat(m_fullName, ".o");
/* Get a filedesc for the module */
if ((fp = fopen(*argv, "r")) == NULL) {
/* Hmpf. Could not open it. Search through _PATH_MODULES to find a module named m_name */
if (recursiveAction(_PATH_MODULES, TRUE, FALSE, FALSE,
findNamedModule, findNamedModule) == FALSE) {
if ( m_filename[0] == '\0' || ((fp = fopen(m_filename, "r")) == NULL)) {
perror("No module by that name found in " _PATH_MODULES "\n");
exit( FALSE);
}
/* Parse any options */
while (--argc > 0 && **(++argv) == '-') {
while (*(++(*argv))) {
switch (**argv) {
case 'f':
break;
case 'k':
break;
default:
usage(insmod_usage);
}
}
}
} else
memcpy(m_filename, *argv, strlen(*argv));
if (argc <= 0)
usage(insmod_usage);
/* Grab the module name */
if ((tmp = strrchr(*argv, '/')) != NULL)
tmp++;
else
tmp = *argv;
len = strlen(tmp);
if (len > 2 && tmp[len - 2] == '.' && tmp[len - 1] == 'o')
len -= 2;
memcpy(m_name, tmp, len);
strcpy(m_fullName, m_name);
strcat(m_fullName, ".o");
/* Get a filedesc for the module */
if ((fp = fopen(*argv, "r")) == NULL) {
/* Hmpf. Could not open it. Search through _PATH_MODULES to find a module named m_name */
if (recursiveAction(_PATH_MODULES, TRUE, FALSE, FALSE,
findNamedModule, findNamedModule) == FALSE) {
if (m_filename[0] == '\0'
|| ((fp = fopen(m_filename, "r")) == NULL)) {
perror("No module by that name found in " _PATH_MODULES
"\n");
exit(FALSE);
}
}
} else
memcpy(m_filename, *argv, strlen(*argv));
fprintf(stderr, "m_filename='%s'\n", m_filename);
fprintf(stderr, "m_name='%s'\n", m_name);
fprintf(stderr, "m_filename='%s'\n", m_filename);
fprintf(stderr, "m_name='%s'\n", m_name);
/* TODO: do something roughtly like this... */
/* TODO: do something roughtly like this... */
#if 0
if ((f = obj_load(fp)) == NULL) {
perror("Could not load the module\n");
exit( FALSE);
}
/* Let the module know about the kernel symbols. */
add_kernel_symbols(f);
if (!create_this_module(f, m_name)) {
perror("Could not create the module\n");
exit( FALSE);
}
if (!obj_check_undefineds(f, quiet)) {
perror("Undefined symbols in the module\n");
exit( FALSE);
}
obj_allocate_commons(f);
/* Perse the module's arguments */
while (argc-- >0 && *(argv++) != '\0') {
if (!process_module_arguments(f, argc - optind, argv + optind)) {
perror("Undefined symbols in the module\n");
exit( FALSE);
if ((f = obj_load(fp)) == NULL) {
perror("Could not load the module\n");
exit(FALSE);
}
}
/* Find current size of the module */
m_size = obj_load_size(f);
/* Let the module know about the kernel symbols. */
add_kernel_symbols(f);
if (!create_this_module(f, m_name)) {
perror("Could not create the module\n");
exit(FALSE);
}
if (!obj_check_undefineds(f, quiet)) {
perror("Undefined symbols in the module\n");
exit(FALSE);
}
obj_allocate_commons(f);
/* Perse the module's arguments */
while (argc-- > 0 && *(argv++) != '\0') {
if (!process_module_arguments(f, argc - optind, argv + optind)) {
perror("Undefined symbols in the module\n");
exit(FALSE);
}
}
/* Find current size of the module */
m_size = obj_load_size(f);
errno = 0;
m_addr = create_module(m_name, m_size);
switch (errno) {
/* yada yada */
errno = 0;
m_addr = create_module(m_name, m_size);
switch (errno) {
/* yada yada */
default:
perror("create_module: %m");
perror("create_module: %m");
}
}
#endif
fclose( fp);
exit( TRUE);
fclose(fp);
exit(TRUE);
}

View File

@ -1,4 +1,4 @@
/* vi: set sw=4 ts=4: */
/*
* Busybox main internal header file
*
@ -218,7 +218,7 @@ static inline int setbit(char * addr,unsigned int nr)
{
int __res = bit(addr, nr);
addr[nr >> 3] |= (1<<(nr & 7));
return __res != 0; \
return __res != 0;
}
static inline int clrbit(char * addr,unsigned int nr)

295
kill.c
View File

@ -1,3 +1,4 @@
/* vi: set sw=4 ts=4: */
/*
* Mini kill implementation for busybox
*
@ -29,188 +30,188 @@
#include <sys/stat.h>
#include <unistd.h>
static const char* kill_usage = "kill [-signal] process-id [process-id ...]\n\n"
"Send a signal (default is SIGTERM) to the specified process(es).\n\n"
"Options:\n"
"\t-l\tList all signal names and numbers.\n\n";
static const char *kill_usage =
"kill [-signal] process-id [process-id ...]\n\n"
"Send a signal (default is SIGTERM) to the specified process(es).\n\n"
"Options:\n" "\t-l\tList all signal names and numbers.\n\n";
struct signal_name {
const char *name;
int number;
const char *name;
int number;
};
const struct signal_name signames[] = {
{"HUP", SIGHUP},
{"INT", SIGINT},
{"QUIT", SIGQUIT},
{"ILL", SIGILL},
{"TRAP", SIGTRAP},
{"ABRT", SIGABRT},
{"HUP", SIGHUP},
{"INT", SIGINT},
{"QUIT", SIGQUIT},
{"ILL", SIGILL},
{"TRAP", SIGTRAP},
{"ABRT", SIGABRT},
#ifndef __alpha__
{"IOT", SIGIOT},
{"IOT", SIGIOT},
#endif
#if defined(__sparc__) || defined(__alpha__)
{"EMT", SIGEMT},
{"EMT", SIGEMT},
#else
{"BUS", SIGBUS},
{"BUS", SIGBUS},
#endif
{"FPE", SIGFPE},
{"KILL", SIGKILL},
{"FPE", SIGFPE},
{"KILL", SIGKILL},
#if defined(__sparc__) || defined(__alpha__)
{"BUS", SIGBUS},
{"BUS", SIGBUS},
#else
{"USR1", SIGUSR1},
{"USR1", SIGUSR1},
#endif
{"SEGV", SIGSEGV},
{"SEGV", SIGSEGV},
#if defined(__sparc__) || defined(__alpha__)
{"SYS", SIGSYS},
{"SYS", SIGSYS},
#else
{"USR2", SIGUSR2},
{"USR2", SIGUSR2},
#endif
{"PIPE", SIGPIPE},
{"ALRM", SIGALRM},
{"TERM", SIGTERM},
{"PIPE", SIGPIPE},
{"ALRM", SIGALRM},
{"TERM", SIGTERM},
#if defined(__sparc__) || defined(__alpha__)
{"URG", SIGURG},
{"STOP", SIGSTOP},
{"TSTP", SIGTSTP},
{"CONT", SIGCONT},
{"CHLD", SIGCHLD},
{"TTIN", SIGTTIN},
{"TTOU", SIGTTOU},
{"IO", SIGIO},
{"URG", SIGURG},
{"STOP", SIGSTOP},
{"TSTP", SIGTSTP},
{"CONT", SIGCONT},
{"CHLD", SIGCHLD},
{"TTIN", SIGTTIN},
{"TTOU", SIGTTOU},
{"IO", SIGIO},
# ifndef __alpha__
{"POLL", SIGIO},
{"POLL", SIGIO},
# endif
{"XCPU", SIGXCPU},
{"XFSZ", SIGXFSZ},
{"VTALRM", SIGVTALRM},
{"PROF", SIGPROF},
{"WINCH", SIGWINCH},
{"XCPU", SIGXCPU},
{"XFSZ", SIGXFSZ},
{"VTALRM", SIGVTALRM},
{"PROF", SIGPROF},
{"WINCH", SIGWINCH},
# ifdef __alpha__
{"INFO", SIGINFO},
{"INFO", SIGINFO},
# else
{"LOST", SIGLOST},
{"LOST", SIGLOST},
# endif
{"USR1", SIGUSR1},
{"USR2", SIGUSR2},
{"USR1", SIGUSR1},
{"USR2", SIGUSR2},
#else
{"STKFLT", SIGSTKFLT},
{"CHLD", SIGCHLD},
{"CONT", SIGCONT},
{"STOP", SIGSTOP},
{"TSTP", SIGTSTP},
{"TTIN", SIGTTIN},
{"TTOU", SIGTTOU},
{"URG", SIGURG},
{"XCPU", SIGXCPU},
{"XFSZ", SIGXFSZ},
{"VTALRM", SIGVTALRM},
{"PROF", SIGPROF},
{"WINCH", SIGWINCH},
{"IO", SIGIO},
{"POLL", SIGPOLL},
{"PWR", SIGPWR},
{"UNUSED", SIGUNUSED},
{"STKFLT", SIGSTKFLT},
{"CHLD", SIGCHLD},
{"CONT", SIGCONT},
{"STOP", SIGSTOP},
{"TSTP", SIGTSTP},
{"TTIN", SIGTTIN},
{"TTOU", SIGTTOU},
{"URG", SIGURG},
{"XCPU", SIGXCPU},
{"XFSZ", SIGXFSZ},
{"VTALRM", SIGVTALRM},
{"PROF", SIGPROF},
{"WINCH", SIGWINCH},
{"IO", SIGIO},
{"POLL", SIGPOLL},
{"PWR", SIGPWR},
{"UNUSED", SIGUNUSED},
#endif
{0, 0}
{0, 0}
};
extern int kill_main (int argc, char **argv)
extern int kill_main(int argc, char **argv)
{
int sig = SIGTERM;
argc--;
argv++;
/* Parse any options */
if (argc < 1)
usage(kill_usage);
int sig = SIGTERM;
while (argc > 0 && **argv == '-') {
while (*++(*argv)) {
switch (**argv) {
case 'l':
{
int col=0;
const struct signal_name *s = signames;
while (s->name != 0) {
col+=fprintf(stderr, "%2d) %-8s", s->number, (s++)->name);
if (col>60) {
fprintf(stderr, "\n");
col=0;
}
}
fprintf(stderr, "\n\n");
exit( TRUE);
}
break;
case '-':
usage(kill_usage);
default:
{
if (isdigit( **argv)) {
sig = atoi (*argv);
if (sig < 0 || sig >= NSIG)
goto end;
else {
argc--;
argv++;
goto do_it_now;
}
}
else {
const struct signal_name *s = signames;
while (s->name != 0) {
if (strcasecmp (s->name, *argv) == 0) {
sig = s->number;
argc--;
argv++;
goto do_it_now;
}
s++;
}
if (s->name == 0)
goto end;
}
}
}
argc--;
argv++;
/* Parse any options */
if (argc < 1)
usage(kill_usage);
while (argc > 0 && **argv == '-') {
while (*++(*argv)) {
switch (**argv) {
case 'l':
{
int col = 0;
const struct signal_name *s = signames;
while (s->name != 0) {
col +=
fprintf(stderr, "%2d) %-8s", s->number,
(s++)->name);
if (col > 60) {
fprintf(stderr, "\n");
col = 0;
}
}
fprintf(stderr, "\n\n");
exit(TRUE);
}
break;
case '-':
usage(kill_usage);
default:
{
if (isdigit(**argv)) {
sig = atoi(*argv);
if (sig < 0 || sig >= NSIG)
goto end;
else {
argc--;
argv++;
goto do_it_now;
}
} else {
const struct signal_name *s = signames;
while (s->name != 0) {
if (strcasecmp(s->name, *argv) == 0) {
sig = s->number;
argc--;
argv++;
goto do_it_now;
}
s++;
}
if (s->name == 0)
goto end;
}
}
}
argc--;
argv++;
}
}
}
do_it_now:
do_it_now:
while (--argc >= 0) {
int pid;
struct stat statbuf;
char pidpath[20]="/proc/";
if (! isdigit( **argv)) {
fprintf(stderr, "bad PID: %s\n", *argv);
exit( FALSE);
}
pid = atoi (*argv);
snprintf(pidpath, 20, "/proc/%s/stat", *argv);
if (stat( pidpath, &statbuf)!=0) {
fprintf(stderr, "kill: (%d) - No such pid\n", pid);
exit( FALSE);
while (--argc >= 0) {
int pid;
struct stat statbuf;
char pidpath[20] = "/proc/";
if (!isdigit(**argv)) {
fprintf(stderr, "bad PID: %s\n", *argv);
exit(FALSE);
}
pid = atoi(*argv);
snprintf(pidpath, 20, "/proc/%s/stat", *argv);
if (stat(pidpath, &statbuf) != 0) {
fprintf(stderr, "kill: (%d) - No such pid\n", pid);
exit(FALSE);
}
fprintf(stderr, "sig = %d\n", sig);
if (kill(pid, sig) != 0) {
perror(*argv);
exit(FALSE);
}
argv++;
}
fprintf(stderr, "sig = %d\n", sig);
if (kill (pid, sig) != 0) {
perror (*argv);
exit ( FALSE);
}
argv++;
}
exit ( TRUE);
exit(TRUE);
end:
fprintf(stderr, "bad signal name: %s\n", *argv);
exit (TRUE);
end:
fprintf(stderr, "bad signal name: %s\n", *argv);
exit(TRUE);
}

View File

@ -1,14 +1,14 @@
/* vi: set sw=4 ts=4: */
#include "internal.h"
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
extern int
length_main(int argc, char * * argv)
extern int length_main(int argc, char **argv)
{
if ( argc != 2 || **(argv+1) == '-' ) {
usage("length string\n");
}
printf("%d\n", strlen(argv[1]));
return( TRUE);
if (argc != 2 || **(argv + 1) == '-') {
usage("length string\n");
}
printf("%d\n", strlen(argv[1]));
return (TRUE);
}

152
ln.c
View File

@ -1,3 +1,4 @@
/* vi: set sw=4 ts=4: */
/*
* Mini ln implementation for busybox
*
@ -30,15 +31,16 @@
#include <stdio.h>
#include <dirent.h>
#include <errno.h>
#include <sys/param.h> /* for PATH_MAX */
#include <sys/param.h> /* for PATH_MAX */
static const char ln_usage[] =
"ln [OPTION] TARGET... LINK_NAME|DIRECTORY\n\n"
"Create a link named LINK_NAME or DIRECTORY to the specified TARGET\n\n"
"Options:\n"
"\t-s\tmake symbolic links instead of hard links\n"
"\t-f\tremove existing destination files\n"
"\t-n\tno dereference symlinks - treat like normal file\n";
"ln [OPTION] TARGET... LINK_NAME|DIRECTORY\n\n"
"Create a link named LINK_NAME or DIRECTORY to the specified TARGET\n\n"
"Options:\n"
"\t-s\tmake symbolic links instead of hard links\n"
"\t-f\tremove existing destination files\n"
"\t-n\tno dereference symlinks - treat like normal file\n";
static int symlinkFlag = FALSE;
static int removeoldFlag = FALSE;
@ -46,83 +48,83 @@ static int followLinks = TRUE;
extern int ln_main(int argc, char **argv)
{
char *linkName;
int linkIntoDirFlag;
char *linkName;
int linkIntoDirFlag;
if (argc < 3) {
usage (ln_usage);
}
argc--;
argv++;
/* Parse any options */
while (**argv == '-') {
while (*++(*argv))
switch (**argv) {
case 's':
symlinkFlag = TRUE;
break;
case 'f':
removeoldFlag = TRUE;
break;
case 'n':
followLinks = FALSE;
break;
default:
usage (ln_usage);
}
if (argc < 3) {
usage(ln_usage);
}
argc--;
argv++;
}
linkName = argv[argc - 1];
if (strlen(linkName) > PATH_MAX) {
fprintf(stderr, name_too_long, "ln");
exit FALSE;
}
linkIntoDirFlag = isDirectory(linkName, TRUE);
if ((argc > 3) && !linkIntoDirFlag) {
fprintf(stderr, not_a_directory, "ln", linkName);
exit FALSE;
}
while (argc-- >= 2) {
char srcName[PATH_MAX + 1];
int nChars, status;
if (strlen(*argv) > PATH_MAX) {
fprintf(stderr, name_too_long, "ln");
exit FALSE;
/* Parse any options */
while (**argv == '-') {
while (*++(*argv))
switch (**argv) {
case 's':
symlinkFlag = TRUE;
break;
case 'f':
removeoldFlag = TRUE;
break;
case 'n':
followLinks = FALSE;
break;
default:
usage(ln_usage);
}
argc--;
argv++;
}
if (followLinks == FALSE) {
strcpy(srcName, *argv);
} else {
/* Warning! This can silently truncate if > PATH_MAX, but
I don't think that there can be one > PATH_MAX anyway. */
nChars = readlink(*argv, srcName, PATH_MAX);
srcName[nChars] = '\0';
}
linkName = argv[argc - 1];
if (removeoldFlag == TRUE) {
status = ( unlink(linkName) && errno != ENOENT );
if (status != 0) {
perror(linkName);
if (strlen(linkName) > PATH_MAX) {
fprintf(stderr, name_too_long, "ln");
exit FALSE;
}
}
if (symlinkFlag == TRUE)
status = symlink(*argv, linkName);
else
status = link(*argv, linkName);
if (status != 0) {
perror(linkName);
exit FALSE;
linkIntoDirFlag = isDirectory(linkName, TRUE);
if ((argc > 3) && !linkIntoDirFlag) {
fprintf(stderr, not_a_directory, "ln", linkName);
exit FALSE;
}
}
exit TRUE;
while (argc-- >= 2) {
char srcName[PATH_MAX + 1];
int nChars, status;
if (strlen(*argv) > PATH_MAX) {
fprintf(stderr, name_too_long, "ln");
exit FALSE;
}
if (followLinks == FALSE) {
strcpy(srcName, *argv);
} else {
/* Warning! This can silently truncate if > PATH_MAX, but
I don't think that there can be one > PATH_MAX anyway. */
nChars = readlink(*argv, srcName, PATH_MAX);
srcName[nChars] = '\0';
}
if (removeoldFlag == TRUE) {
status = (unlink(linkName) && errno != ENOENT);
if (status != 0) {
perror(linkName);
exit FALSE;
}
}
if (symlinkFlag == TRUE)
status = symlink(*argv, linkName);
else
status = link(*argv, linkName);
if (status != 0) {
perror(linkName);
exit FALSE;
}
}
exit TRUE;
}

652
loadacm.c
View File

@ -1,3 +1,4 @@
/* vi: set sw=4 ts=4: */
/*
* Derived from
* mapscrn.c - version 0.92
@ -23,120 +24,115 @@
typedef unsigned short unicode;
static long int ctoi(unsigned char *s, int *is_unicode);
int old_screen_map_read_ascii(FILE *fp, unsigned char buf[]);
int uni_screen_map_read_ascii(FILE *fp, unicode buf[], int* is_unicode);
unicode utf8_to_ucs2 (char* buf);
int screen_map_load(int fd, FILE *fp);
int old_screen_map_read_ascii(FILE * fp, unsigned char buf[]);
int uni_screen_map_read_ascii(FILE * fp, unicode buf[], int *is_unicode);
unicode utf8_to_ucs2(char *buf);
int screen_map_load(int fd, FILE * fp);
int loadacm_main(int argc, char **argv)
{
int fd;
fd = open("/dev/tty", O_RDWR);
if (fd < 0) {
fprintf(stderr, "Error opening /dev/tty1: %s\n", strerror(errno));
return 1;
}
if (screen_map_load(fd, stdin))
{
fprintf(stderr, "Error loading acm: %s\n", strerror(errno));
return 1;
}
write(fd, "\033(K", 3);
return 0;
int fd;
fd = open("/dev/tty", O_RDWR);
if (fd < 0) {
fprintf(stderr, "Error opening /dev/tty1: %s\n", strerror(errno));
return 1;
}
if (screen_map_load(fd, stdin)) {
fprintf(stderr, "Error loading acm: %s\n", strerror(errno));
return 1;
}
write(fd, "\033(K", 3);
return 0;
}
int screen_map_load(int fd, FILE *fp)
int screen_map_load(int fd, FILE * fp)
{
struct stat stbuf;
unicode wbuf[E_TABSZ];
unsigned char buf[E_TABSZ];
int parse_failed = 0;
int is_unicode;
struct stat stbuf;
unicode wbuf[E_TABSZ];
unsigned char buf[E_TABSZ];
int parse_failed = 0;
int is_unicode;
if (fstat(fp->_fileno, &stbuf))
perror("Cannot stat map file"), exit(1);
if (fstat(fp->_fileno, &stbuf))
perror("Cannot stat map file"), exit(1);
/* first try a UTF screen-map: either ASCII (no restriction) or binary (regular file) */
if (!(parse_failed = (-1 == uni_screen_map_read_ascii(fp,wbuf,&is_unicode))) ||
(S_ISREG(stbuf.st_mode) &&
(stbuf.st_size == (sizeof(unicode) * E_TABSZ)))) /* test for binary UTF map by size */
{
if (parse_failed)
{
if (-1 == fseek (fp, 0, SEEK_SET))
{
if (errno == ESPIPE)
fprintf (stderr, "16bit screen-map MUST be a regular file.\n"), exit (1);
else
perror ("fseek failed reading binary 16bit screen-map"), exit (1);
}
if (fread(wbuf, sizeof(unicode) * E_TABSZ, 1, fp) != 1)
perror("Cannot read [new] map from file"), exit(1);
/* first try a UTF screen-map: either ASCII (no restriction) or binary (regular file) */
if (!
(parse_failed =
(-1 == uni_screen_map_read_ascii(fp, wbuf, &is_unicode)))
|| (S_ISREG(stbuf.st_mode) && (stbuf.st_size == (sizeof(unicode) * E_TABSZ)))) { /* test for binary UTF map by size */
if (parse_failed) {
if (-1 == fseek(fp, 0, SEEK_SET)) {
if (errno == ESPIPE)
fprintf(stderr,
"16bit screen-map MUST be a regular file.\n"),
exit(1);
else
perror("fseek failed reading binary 16bit screen-map"),
exit(1);
}
if (fread(wbuf, sizeof(unicode) * E_TABSZ, 1, fp) != 1)
perror("Cannot read [new] map from file"), exit(1);
#if 0
else
fprintf(stderr, "Input screen-map is binary.\n");
else
fprintf(stderr, "Input screen-map is binary.\n");
#endif
}
/* if it was effectively a 16-bit ASCII, OK, else try to read as 8-bit map */
/* same if it was binary, ie. if parse_failed */
if (parse_failed || is_unicode) {
if (ioctl(fd, PIO_UNISCRNMAP, wbuf))
perror("PIO_UNISCRNMAP ioctl"), exit(1);
else
return 0;
}
}
/* if it was effectively a 16-bit ASCII, OK, else try to read as 8-bit map */
/* same if it was binary, ie. if parse_failed */
if (parse_failed || is_unicode)
{
if (ioctl(fd,PIO_UNISCRNMAP,wbuf))
perror("PIO_UNISCRNMAP ioctl"), exit(1);
else
return 0;
/* rewind... */
if (-1 == fseek(fp, 0, SEEK_SET)) {
if (errno == ESPIPE)
fprintf(stderr,
"Assuming 8bit screen-map - MUST be a regular file.\n"),
exit(1);
else
perror("fseek failed assuming 8bit screen-map"), exit(1);
}
}
/* rewind... */
if (-1 == fseek (fp, 0, SEEK_SET))
{
if (errno == ESPIPE)
fprintf (stderr, "Assuming 8bit screen-map - MUST be a regular file.\n"), exit (1);
else
perror ("fseek failed assuming 8bit screen-map"), exit (1);
}
/* ... and try an old 8-bit screen-map */
if (!(parse_failed = (-1 == old_screen_map_read_ascii(fp,buf))) ||
(S_ISREG(stbuf.st_mode) &&
(stbuf.st_size == E_TABSZ))) /* test for binary old 8-bit map by size */
{
if (parse_failed)
{
if (-1 == fseek (fp, 0, SEEK_SET))
{
if (errno == ESPIPE)
/* should not - it succedeed above */
fprintf (stderr, "fseek() returned ESPIPE !\n"), exit (1);
else
perror ("fseek for binary 8bit screen-map"), exit (1);
}
if (fread(buf,E_TABSZ,1,fp) != 1)
perror("Cannot read [old] map from file"), exit(1);
/* ... and try an old 8-bit screen-map */
if (!(parse_failed = (-1 == old_screen_map_read_ascii(fp, buf))) ||
(S_ISREG(stbuf.st_mode) && (stbuf.st_size == E_TABSZ))) { /* test for binary old 8-bit map by size */
if (parse_failed) {
if (-1 == fseek(fp, 0, SEEK_SET)) {
if (errno == ESPIPE)
/* should not - it succedeed above */
fprintf(stderr, "fseek() returned ESPIPE !\n"),
exit(1);
else
perror("fseek for binary 8bit screen-map"), exit(1);
}
if (fread(buf, E_TABSZ, 1, fp) != 1)
perror("Cannot read [old] map from file"), exit(1);
#if 0
else
fprintf(stderr, "Input screen-map is binary.\n");
else
fprintf(stderr, "Input screen-map is binary.\n");
#endif
}
if (ioctl(fd, PIO_SCRNMAP, buf))
perror("PIO_SCRNMAP ioctl"), exit(1);
else
return 0;
} else {
fprintf(stderr, "Error parsing symbolic map\n");
exit(1);
}
if (ioctl(fd,PIO_SCRNMAP,buf))
perror("PIO_SCRNMAP ioctl"), exit(1);
else
return 0;
}
else
{
fprintf(stderr, "Error parsing symbolic map\n");
exit(1);
}
}
@ -149,116 +145,111 @@ int screen_map_load(int fd, FILE *fp)
*
* FIXME: ignores everything after second word
*/
int uni_screen_map_read_ascii(FILE *fp, unicode buf[], int *is_unicode)
int uni_screen_map_read_ascii(FILE * fp, unicode buf[], int *is_unicode)
{
char buffer[256]; /* line buffer reading file */
char *p, *q; /* 1st + 2nd words in line */
int in, on; /* the same, as numbers */
int tmp_is_unicode; /* tmp for is_unicode calculation */
int i; /* loop index - result holder */
int ret_code = 0; /* return code */
sigset_t sigset, old_sigset;
assert (is_unicode);
*is_unicode = 0;
/* first 128 codes defaults to ASCII */
for (i=0; i<128; i++) buf[i] = i;
/* remaining defaults to replacement char (usually E_TABSZ = 256) */
for ( ; i<E_TABSZ; i++) buf[i] = 0xfffd;
/* block SIGCHLD */
sigemptyset (&sigset);
sigaddset (&sigset, SIGCHLD);
sigprocmask (SIG_BLOCK, &sigset, &old_sigset);
char buffer[256]; /* line buffer reading file */
char *p, *q; /* 1st + 2nd words in line */
int in, on; /* the same, as numbers */
int tmp_is_unicode; /* tmp for is_unicode calculation */
int i; /* loop index - result holder */
int ret_code = 0; /* return code */
sigset_t sigset, old_sigset;
do
{
if (NULL == fgets(buffer, sizeof(buffer),fp))
{
if (feof (fp))
break;
else
{
perror ("uni_screen_map_read_ascii() can't read line");
exit (2);
}
assert(is_unicode);
*is_unicode = 0;
/* first 128 codes defaults to ASCII */
for (i = 0; i < 128; i++)
buf[i] = i;
/* remaining defaults to replacement char (usually E_TABSZ = 256) */
for (; i < E_TABSZ; i++)
buf[i] = 0xfffd;
/* block SIGCHLD */
sigemptyset(&sigset);
sigaddset(&sigset, SIGCHLD);
sigprocmask(SIG_BLOCK, &sigset, &old_sigset);
do {
if (NULL == fgets(buffer, sizeof(buffer), fp)) {
if (feof(fp))
break;
else {
perror("uni_screen_map_read_ascii() can't read line");
exit(2);
}
}
/* get "charset-relative charcode", stripping leading spaces */
p = strtok(buffer, " \t\n");
/* skip empty lines and comments */
if (!p || *p == '#')
continue;
/* get unicode mapping */
q = strtok(NULL, " \t\n");
if (q) {
in = ctoi(p, NULL);
if (in < 0 || in > 255) {
ret_code = -1;
break;
}
on = ctoi(q, &tmp_is_unicode);
if (in < 0 && on > 65535) {
ret_code = -1;
break;
}
*is_unicode |= tmp_is_unicode;
buf[in] = on;
} else {
ret_code = -1;
break;
}
}
/* get "charset-relative charcode", stripping leading spaces */
p = strtok(buffer," \t\n");
while (1); /* terminated by break on feof() */
/* skip empty lines and comments */
if (!p || *p == '#')
continue;
/* restore sig mask */
sigprocmask(SIG_SETMASK, &old_sigset, NULL);
/* get unicode mapping */
q = strtok(NULL," \t\n");
if (q)
{
in = ctoi(p, NULL);
if (in < 0 || in > 255)
{
ret_code = -1;
break;
}
on = ctoi(q, &tmp_is_unicode);
if (in < 0 && on > 65535)
{
ret_code = -1;
break;
}
*is_unicode |= tmp_is_unicode;
buf[in] = on;
}
else
{
ret_code = -1;
break;
}
}
while (1); /* terminated by break on feof() */
/* restore sig mask */
sigprocmask (SIG_SETMASK, &old_sigset, NULL);
return ret_code;
return ret_code;
}
int old_screen_map_read_ascii(FILE *fp, unsigned char buf[])
int old_screen_map_read_ascii(FILE * fp, unsigned char buf[])
{
char buffer[256];
int in, on;
char *p, *q;
for (in=0; in<256; in++) buf[in]=in;
while (fgets(buffer,sizeof(buffer)-1,fp))
{
p = strtok(buffer," \t\n");
if (!p || *p == '#')
continue;
char buffer[256];
int in, on;
char *p, *q;
q = strtok(NULL," \t\n#");
if (q)
{
in = ctoi(p, NULL);
if (in < 0 || in > 255) return -1;
on = ctoi(q, NULL);
if (in < 0 && on > 255) return -1;
buf[in] = on;
for (in = 0; in < 256; in++)
buf[in] = in;
while (fgets(buffer, sizeof(buffer) - 1, fp)) {
p = strtok(buffer, " \t\n");
if (!p || *p == '#')
continue;
q = strtok(NULL, " \t\n#");
if (q) {
in = ctoi(p, NULL);
if (in < 0 || in > 255)
return -1;
on = ctoi(q, NULL);
if (in < 0 && on > 255)
return -1;
buf[in] = on;
} else
return -1;
}
else return -1;
}
return(0);
return (0);
}
@ -270,172 +261,145 @@ int old_screen_map_read_ascii(FILE *fp, unsigned char buf[])
*
* CAVEAT: will report valid UTF mappings using only 1 byte as 8-bit ones.
*/
long int ctoi(unsigned char *s, int *is_unicode)
long int ctoi(unsigned char *s, int *is_unicode)
{
int i;
size_t ls;
ls = strlen(s);
if (is_unicode) *is_unicode = 0;
/* hex-specified UCS2 */
if ((strncmp(s,"U+",2) == 0) &&
(strspn(s+2,"0123456789abcdefABCDEF") == ls-2))
{
sscanf(s+2,"%x",&i);
if (is_unicode) *is_unicode = 1;
}
int i;
size_t ls;
/* hex-specified byte */
else if ((ls <= 4) && (strncmp(s,"0x",2) == 0) &&
(strspn(s+2,"0123456789abcdefABCDEF") == ls-2))
sscanf(s+2,"%x",&i);
ls = strlen(s);
if (is_unicode)
*is_unicode = 0;
/* oct-specified number (byte) */
else if ((*s == '0') &&
(strspn(s,"01234567") == ls))
sscanf(s,"%o",&i);
/* dec-specified number (byte) */
else if (strspn(s,"0123456789") == ls)
sscanf(s,"%d",&i);
/* single-byte quoted char */
else if ((strlen(s) == 3) && (s[0] == '\'') && (s[2] == '\''))
i=s[1];
/* multi-byte UTF8 quoted char */
else if ((s[0] == '\'') && (s[ls-1] == '\''))
{
s[ls-1] = 0; /* ensure we'll not "parse UTF too far" */
i = utf8_to_ucs2(s+1);
if (is_unicode) *is_unicode = 1;
}
else
return(-1);
return(i);
/* hex-specified UCS2 */
if ((strncmp(s, "U+", 2) == 0) &&
(strspn(s + 2, "0123456789abcdefABCDEF") == ls - 2)) {
sscanf(s + 2, "%x", &i);
if (is_unicode)
*is_unicode = 1;
}
/* hex-specified byte */
else if ((ls <= 4) && (strncmp(s, "0x", 2) == 0) &&
(strspn(s + 2, "0123456789abcdefABCDEF") == ls - 2))
sscanf(s + 2, "%x", &i);
/* oct-specified number (byte) */
else if ((*s == '0') && (strspn(s, "01234567") == ls))
sscanf(s, "%o", &i);
/* dec-specified number (byte) */
else if (strspn(s, "0123456789") == ls)
sscanf(s, "%d", &i);
/* single-byte quoted char */
else if ((strlen(s) == 3) && (s[0] == '\'') && (s[2] == '\''))
i = s[1];
/* multi-byte UTF8 quoted char */
else if ((s[0] == '\'') && (s[ls - 1] == '\'')) {
s[ls - 1] = 0; /* ensure we'll not "parse UTF too far" */
i = utf8_to_ucs2(s + 1);
if (is_unicode)
*is_unicode = 1;
} else
return (-1);
return (i);
}
void saveoldmap(int fd, char *omfil)
void saveoldmap(int fd, char *omfil)
{
FILE *fp;
char buf[E_TABSZ];
#ifdef GIO_UNISCRNMAP
unicode xbuf[E_TABSZ];
int is_old_map = 0;
if (ioctl(fd,GIO_UNISCRNMAP,xbuf))
{
perror("GIO_UNISCRNMAP ioctl error");
#endif
if (ioctl(fd,GIO_SCRNMAP,buf))
{
perror("GIO_SCRNMAP ioctl error");
exit(1);
}
else
is_old_map = 1;
#ifdef GIO_UNISCRNMAP
}
#endif
if ((fp = fopen(omfil, "w")) == NULL)
{
perror(omfil);
exit(1);
}
FILE *fp;
char buf[E_TABSZ];
#ifdef GIO_UNISCRNMAP
if (is_old_map)
{
unicode xbuf[E_TABSZ];
int is_old_map = 0;
if (ioctl(fd, GIO_UNISCRNMAP, xbuf)) {
perror("GIO_UNISCRNMAP ioctl error");
#endif
if (fwrite(buf,E_TABSZ,1,fp) != 1)
{
perror("Error writing map to file");
exit(1);
if (ioctl(fd, GIO_SCRNMAP, buf)) {
perror("GIO_SCRNMAP ioctl error");
exit(1);
} else
is_old_map = 1;
#ifdef GIO_UNISCRNMAP
}
#endif
if ((fp = fopen(omfil, "w")) == NULL) {
perror(omfil);
exit(1);
}
#ifdef GIO_UNISCRNMAP
}
else
if (fwrite(xbuf, sizeof(unicode) * E_TABSZ,1,fp) != 1)
{
perror("Error writing map to file");
exit(1);
if (is_old_map) {
#endif
if (fwrite(buf, E_TABSZ, 1, fp) != 1) {
perror("Error writing map to file");
exit(1);
}
#ifdef GIO_UNISCRNMAP
} else if (fwrite(xbuf, sizeof(unicode) * E_TABSZ, 1, fp) != 1) {
perror("Error writing map to file");
exit(1);
}
#endif
fclose(fp);
fclose(fp);
}
unicode utf8_to_ucs2 (char* buf)
unicode utf8_to_ucs2(char *buf)
{
int utf_count = 0;
long utf_char;
unicode tc;
unsigned char c;
int utf_count = 0;
long utf_char;
unicode tc;
unsigned char c;
do
{
c = *buf;
buf++;
do {
c = *buf;
buf++;
/* if byte should be part of multi-byte sequence */
if(c & 0x80)
{
/* if we have already started to parse a UTF8 sequence */
if (utf_count > 0 && (c & 0xc0) == 0x80)
{
utf_char = (utf_char << 6) | (c & 0x3f);
utf_count--;
if (utf_count == 0)
tc = utf_char;
else
continue;
}
else /* Possibly 1st char of a UTF8 sequence */
{
if ((c & 0xe0) == 0xc0)
{
utf_count = 1;
utf_char = (c & 0x1f);
}
else if ((c & 0xf0) == 0xe0)
{
utf_count = 2;
utf_char = (c & 0x0f);
}
else if ((c & 0xf8) == 0xf0)
{
utf_count = 3;
utf_char = (c & 0x07);
}
else if ((c & 0xfc) == 0xf8)
{
utf_count = 4;
utf_char = (c & 0x03);
}
else if ((c & 0xfe) == 0xfc)
{
utf_count = 5;
utf_char = (c & 0x01);
}
else
utf_count = 0;
continue;
}
}
else /* not part of multi-byte sequence - treat as ASCII
* this makes incomplete sequences to be ignored
*/
{
tc = c;
utf_count = 0;
}
}
while (utf_count);
/* if byte should be part of multi-byte sequence */
if (c & 0x80) {
/* if we have already started to parse a UTF8 sequence */
if (utf_count > 0 && (c & 0xc0) == 0x80) {
utf_char = (utf_char << 6) | (c & 0x3f);
utf_count--;
if (utf_count == 0)
tc = utf_char;
else
continue;
} else { /* Possibly 1st char of a UTF8 sequence */
return tc;
if ((c & 0xe0) == 0xc0) {
utf_count = 1;
utf_char = (c & 0x1f);
} else if ((c & 0xf0) == 0xe0) {
utf_count = 2;
utf_char = (c & 0x0f);
} else if ((c & 0xf8) == 0xf0) {
utf_count = 3;
utf_char = (c & 0x07);
} else if ((c & 0xfc) == 0xf8) {
utf_count = 4;
utf_char = (c & 0x03);
} else if ((c & 0xfe) == 0xfc) {
utf_count = 5;
utf_char = (c & 0x01);
} else
utf_count = 0;
continue;
}
} else { /* not part of multi-byte sequence - treat as ASCII
* this makes incomplete sequences to be ignored
*/
tc = c;
utf_count = 0;
}
}
while (utf_count);
return tc;
}

View File

@ -1,3 +1,4 @@
/* vi: set sw=4 ts=4: */
/*
* loadfont.c - Eugene Crosser & Andries Brouwer
*
@ -30,72 +31,69 @@
#define PSF_SEPARATOR 0xFFFF
static const char loadfont_usage[] = "loadfont\n"
"\n"
"\tLoad a console font from standard input.\n"
"\n";
"\n" "\tLoad a console font from standard input.\n" "\n";
struct psf_header
{
unsigned char magic1, magic2; /* Magic number */
unsigned char mode; /* PSF font mode */
unsigned char charsize; /* Character size */
struct psf_header {
unsigned char magic1, magic2; /* Magic number */
unsigned char mode; /* PSF font mode */
unsigned char charsize; /* Character size */
};
#define PSF_MAGIC_OK(x) ((x).magic1 == PSF_MAGIC1 && (x).magic2 == PSF_MAGIC2)
static void loadnewfont(int fd);
extern int
loadfont_main(int argc, char **argv)
extern int loadfont_main(int argc, char **argv)
{
int fd;
fd = open("/dev/tty0", O_RDWR);
if (fd < 0) {
fprintf(stderr, "Error opening /dev/tty0: %s\n", strerror(errno));
return 1;
fprintf(stderr, "Error opening /dev/tty0: %s\n", strerror(errno));
return 1;
}
loadnewfont(fd);
return 0;
}
static void
do_loadfont(int fd, char *inbuf, int unit, int fontsize) {
static void do_loadfont(int fd, char *inbuf, int unit, int fontsize)
{
char buf[16384];
int i;
memset(buf,0,sizeof(buf));
memset(buf, 0, sizeof(buf));
if (unit < 1 || unit > 32) {
fprintf(stderr, "Bad character size %d\n", unit);
exit(1);
fprintf(stderr, "Bad character size %d\n", unit);
exit(1);
}
for (i = 0; i < fontsize; i++)
memcpy(buf+(32*i), inbuf+(unit*i), unit);
memcpy(buf + (32 * i), inbuf + (unit * i), unit);
#if defined( PIO_FONTX ) && !defined( __sparc__ )
{
struct consolefontdesc cfd;
struct consolefontdesc cfd;
cfd.charcount = fontsize;
cfd.charheight = unit;
cfd.chardata = buf;
cfd.charcount = fontsize;
cfd.charheight = unit;
cfd.chardata = buf;
if (ioctl(fd, PIO_FONTX, &cfd) == 0)
return; /* success */
perror("PIO_FONTX ioctl error (trying PIO_FONT)");
if (ioctl(fd, PIO_FONTX, &cfd) == 0)
return; /* success */
perror("PIO_FONTX ioctl error (trying PIO_FONT)");
}
#endif
if (ioctl(fd, PIO_FONT, buf)) {
perror("PIO_FONT ioctl error");
exit(1);
perror("PIO_FONT ioctl error");
exit(1);
}
}
static void
do_loadtable(int fd, unsigned char *inbuf, int tailsz, int fontsize) {
do_loadtable(int fd, unsigned char *inbuf, int tailsz, int fontsize)
{
struct unimapinit advice;
struct unimapdesc ud;
struct unipair *up;
@ -103,23 +101,24 @@ do_loadtable(int fd, unsigned char *inbuf, int tailsz, int fontsize) {
int glyph;
u_short unicode;
maxct = tailsz; /* more than enough */
maxct = tailsz; /* more than enough */
up = (struct unipair *) malloc(maxct * sizeof(struct unipair));
if (!up) {
fprintf(stderr, "Out of memory?\n");
exit(1);
fprintf(stderr, "Out of memory?\n");
exit(1);
}
for (glyph = 0; glyph < fontsize; glyph++) {
while (tailsz >= 2) {
unicode = (((u_short) inbuf[1]) << 8) + inbuf[0];
tailsz -= 2;
inbuf += 2;
if (unicode == PSF_SEPARATOR)
break;
up[ct].unicode = unicode;
up[ct].fontpos = glyph;
ct++;
}
while (tailsz >= 2) {
unicode = (((u_short) inbuf[1]) << 8) + inbuf[0];
tailsz -= 2;
inbuf += 2;
if (unicode == PSF_SEPARATOR)
break;
up[ct].unicode = unicode;
up[ct].fontpos = glyph;
ct++;
}
}
/* Note: after PIO_UNIMAPCLR and before PIO_UNIMAP
@ -128,33 +127,33 @@ do_loadtable(int fd, unsigned char *inbuf, int tailsz, int fontsize) {
advice.advised_hashsize = 0;
advice.advised_hashstep = 0;
advice.advised_hashlevel = 0;
if(ioctl(fd, PIO_UNIMAPCLR, &advice)) {
if (ioctl(fd, PIO_UNIMAPCLR, &advice)) {
#ifdef ENOIOCTLCMD
if (errno == ENOIOCTLCMD) {
fprintf(stderr, "It seems this kernel is older than 1.1.92\n");
fprintf(stderr, "No Unicode mapping table loaded.\n");
} else
if (errno == ENOIOCTLCMD) {
fprintf(stderr, "It seems this kernel is older than 1.1.92\n");
fprintf(stderr, "No Unicode mapping table loaded.\n");
} else
#endif
perror("PIO_UNIMAPCLR");
exit(1);
perror("PIO_UNIMAPCLR");
exit(1);
}
ud.entry_ct = ct;
ud.entries = up;
if(ioctl(fd, PIO_UNIMAP, &ud)) {
if (ioctl(fd, PIO_UNIMAP, &ud)) {
#if 0
if (errno == ENOMEM) {
/* change advice parameters */
}
if (errno == ENOMEM) {
/* change advice parameters */
}
#endif
perror("PIO_UNIMAP");
exit(1);
perror("PIO_UNIMAP");
exit(1);
}
}
static void
loadnewfont(int fd) {
static void loadnewfont(int fd)
{
int unit;
char inbuf[32768]; /* primitive */
char inbuf[32768]; /* primitive */
int inputlth, offset;
/*
@ -178,57 +177,58 @@ loadnewfont(int fd) {
/* test for psf first */
{
struct psf_header psfhdr;
int fontsize;
int hastable;
int head0, head;
struct psf_header psfhdr;
int fontsize;
int hastable;
int head0, head;
if (inputlth < sizeof(struct psf_header))
goto no_psf;
if (inputlth < sizeof(struct psf_header))
goto no_psf;
psfhdr = * (struct psf_header *) &inbuf[0];
psfhdr = *(struct psf_header *) &inbuf[0];
if (!PSF_MAGIC_OK(psfhdr))
goto no_psf;
if (!PSF_MAGIC_OK(psfhdr))
goto no_psf;
if (psfhdr.mode > PSF_MAXMODE) {
fprintf(stderr, "Unsupported psf file mode\n");
exit(1);
}
fontsize = ((psfhdr.mode & PSF_MODE512) ? 512 : 256);
if (psfhdr.mode > PSF_MAXMODE) {
fprintf(stderr, "Unsupported psf file mode\n");
exit(1);
}
fontsize = ((psfhdr.mode & PSF_MODE512) ? 512 : 256);
#if !defined( PIO_FONTX ) || defined( __sparc__ )
if (fontsize != 256) {
fprintf(stderr, "Only fontsize 256 supported\n");
exit(1);
}
if (fontsize != 256) {
fprintf(stderr, "Only fontsize 256 supported\n");
exit(1);
}
#endif
hastable = (psfhdr.mode & PSF_MODEHASTAB);
unit = psfhdr.charsize;
head0 = sizeof(struct psf_header);
head = head0 + fontsize*unit;
if (head > inputlth || (!hastable && head != inputlth)) {
fprintf(stderr, "Input file: bad length\n");
exit(1);
}
do_loadfont(fd, inbuf + head0, unit, fontsize);
if (hastable)
do_loadtable(fd, inbuf + head, inputlth-head, fontsize);
return;
hastable = (psfhdr.mode & PSF_MODEHASTAB);
unit = psfhdr.charsize;
head0 = sizeof(struct psf_header);
head = head0 + fontsize * unit;
if (head > inputlth || (!hastable && head != inputlth)) {
fprintf(stderr, "Input file: bad length\n");
exit(1);
}
do_loadfont(fd, inbuf + head0, unit, fontsize);
if (hastable)
do_loadtable(fd, inbuf + head, inputlth - head, fontsize);
return;
}
no_psf:
no_psf:
/* file with three code pages? */
if (inputlth == 9780) {
offset = 40;
unit = 16;
offset = 40;
unit = 16;
} else {
/* bare font */
if (inputlth & 0377) {
fprintf(stderr, "Bad input file size\n");
exit(1);
}
offset = 0;
unit = inputlth/256;
/* bare font */
if (inputlth & 0377) {
fprintf(stderr, "Bad input file size\n");
exit(1);
}
offset = 0;
unit = inputlth / 256;
}
do_loadfont(fd, inbuf+offset, unit, 256);
do_loadfont(fd, inbuf + offset, unit, 256);
}

View File

@ -1,3 +1,4 @@
/* vi: set sw=4 ts=4: */
/*
* Mini loadkmap implementation for busybox
*
@ -29,61 +30,63 @@
static const char loadkmap_usage[] = "loadkmap\n"
"\n"
"\tLoad a binary keyboard translation table from standard input.\n"
"\n";
"\n"
"\tLoad a binary keyboard translation table from standard input.\n"
"\n";
int
loadkmap_main(int argc, char * * argv)
{
struct kbentry ke;
u_short *ibuff;
int i,j,fd,readsz,pos,ibuffsz=NR_KEYS * sizeof(u_short);
char flags[MAX_NR_KEYMAPS],magic[]="bkeymap",buff[7];
int loadkmap_main(int argc, char **argv)
{
struct kbentry ke;
u_short *ibuff;
int i, j, fd, readsz, pos, ibuffsz = NR_KEYS * sizeof(u_short);
char flags[MAX_NR_KEYMAPS], magic[] = "bkeymap", buff[7];
fd = open("/dev/tty0", O_RDWR);
if (fd < 0) {
fprintf(stderr, "Error opening /dev/tty0: %s\n", strerror(errno));
return 1;
}
read(0,buff,7);
if (0 != strncmp(buff,magic,7)) {
fprintf(stderr, "This is not a valid binary keymap.\n");
return 1;
}
if ( MAX_NR_KEYMAPS != read(0,flags,MAX_NR_KEYMAPS) ) {
fprintf(stderr, "Error reading keymap flags: %s\n", strerror(errno));
return 1;
}
ibuff=(u_short *) malloc(ibuffsz);
if (!ibuff) {
fprintf(stderr, "Out of memory.\n");
return 1;
}
for(i=0; i<MAX_NR_KEYMAPS; i++) {
if (flags[i]==1){
pos=0;
while (pos < ibuffsz) {
if ( (readsz = read(0,(char *)ibuff+pos,ibuffsz-pos)) < 0 ) {
fprintf(stderr, "Error reading keymap: %s\n",
strerror(errno));
return 1;
}
pos += readsz;
}
for(j=0; j<NR_KEYS; j++) {
ke.kb_index = j;
ke.kb_table = i;
ke.kb_value = ibuff[j];
ioctl(fd, KDSKBENT, &ke);
}
fd = open("/dev/tty0", O_RDWR);
if (fd < 0) {
fprintf(stderr, "Error opening /dev/tty0: %s\n", strerror(errno));
return 1;
}
}
close (fd);
return 0;
read(0, buff, 7);
if (0 != strncmp(buff, magic, 7)) {
fprintf(stderr, "This is not a valid binary keymap.\n");
return 1;
}
if (MAX_NR_KEYMAPS != read(0, flags, MAX_NR_KEYMAPS)) {
fprintf(stderr, "Error reading keymap flags: %s\n",
strerror(errno));
return 1;
}
ibuff = (u_short *) malloc(ibuffsz);
if (!ibuff) {
fprintf(stderr, "Out of memory.\n");
return 1;
}
for (i = 0; i < MAX_NR_KEYMAPS; i++) {
if (flags[i] == 1) {
pos = 0;
while (pos < ibuffsz) {
if ((readsz = read(0, (char *) ibuff + pos, ibuffsz - pos))
< 0) {
fprintf(stderr, "Error reading keymap: %s\n",
strerror(errno));
return 1;
}
pos += readsz;
}
for (j = 0; j < NR_KEYS; j++) {
ke.kb_index = j;
ke.kb_table = i;
ke.kb_value = ibuff[j];
ioctl(fd, KDSKBENT, &ke);
}
}
}
close(fd);
return 0;
}

191
logger.c
View File

@ -1,3 +1,4 @@
/* vi: set sw=4 ts=4: */
/*
* Mini logger implementation for busybox
*
@ -39,21 +40,22 @@
*/
#include <sys/syslog.h>
typedef struct _code {
char *c_name;
int c_val;
char *c_name;
int c_val;
} CODE;
extern CODE prioritynames[];
extern CODE facilitynames[];
#endif
static const char logger_usage[] =
"logger [OPTION]... [MESSAGE]\n\n"
"Write MESSAGE to the system log. If MESSAGE is '-', log stdin.\n\n"
"Options:\n"
"\t-s\tLog to stderr as well as the system log.\n"
"\t-t\tLog using the specified tag (defaults to user name).\n"
"\t-p\tEnter the message with the specified priority.\n"
"\t\tThis may be numerical or a ``facility.level'' pair.\n";
"logger [OPTION]... [MESSAGE]\n\n"
"Write MESSAGE to the system log. If MESSAGE is '-', log stdin.\n\n"
"Options:\n"
"\t-s\tLog to stderr as well as the system log.\n"
"\t-t\tLog using the specified tag (defaults to user name).\n"
"\t-p\tEnter the message with the specified priority.\n"
"\t\tThis may be numerical or a ``facility.level'' pair.\n";
/* Decode a symbolic name to a numeric value
@ -61,20 +63,19 @@ static const char logger_usage[] =
* Copyright (c) 1983, 1993
* The Regents of the University of California. All rights reserved.
*/
static int
decode(char* name, CODE* codetab)
static int decode(char *name, CODE * codetab)
{
CODE *c;
CODE *c;
if (isdigit(*name))
return (atoi(name));
for (c = codetab; c->c_name; c++) {
if (!strcasecmp(name, c->c_name)) {
return (c->c_val);
if (isdigit(*name))
return (atoi(name));
for (c = codetab; c->c_name; c++) {
if (!strcasecmp(name, c->c_name)) {
return (c->c_val);
}
}
}
return (-1);
return (-1);
}
/* Decode a symbolic name to a numeric value
@ -82,96 +83,94 @@ decode(char* name, CODE* codetab)
* Copyright (c) 1983, 1993
* The Regents of the University of California. All rights reserved.
*/
static int
pencode(char* s)
static int pencode(char *s)
{
char *save;
int lev, fac=LOG_USER;
char *save;
int lev, fac = LOG_USER;
for (save = s; *s && *s != '.'; ++s);
if (*s) {
*s = '\0';
fac = decode(save, facilitynames);
if (fac < 0) {
fprintf(stderr, "unknown facility name: %s\n", save);
exit( FALSE);
for (save = s; *s && *s != '.'; ++s);
if (*s) {
*s = '\0';
fac = decode(save, facilitynames);
if (fac < 0) {
fprintf(stderr, "unknown facility name: %s\n", save);
exit(FALSE);
}
*s++ = '.';
} else {
s = save;
}
*s++ = '.';
}
else {
s = save;
}
lev = decode(s, prioritynames);
if (lev < 0) {
fprintf(stderr, "unknown priority name: %s\n", save);
exit( FALSE);
}
return ((lev & LOG_PRIMASK) | (fac & LOG_FACMASK));
lev = decode(s, prioritynames);
if (lev < 0) {
fprintf(stderr, "unknown priority name: %s\n", save);
exit(FALSE);
}
return ((lev & LOG_PRIMASK) | (fac & LOG_FACMASK));
}
extern int logger_main(int argc, char **argv)
{
int pri = LOG_USER|LOG_NOTICE;
int option = 0;
int fromStdinFlag=FALSE;
int stopLookingAtMeLikeThat=FALSE;
char *message, buf[1024], name[128];
/* Fill out the name string early (may be overwritten later */
my_getpwuid(name, geteuid());
int pri = LOG_USER | LOG_NOTICE;
int option = 0;
int fromStdinFlag = FALSE;
int stopLookingAtMeLikeThat = FALSE;
char *message, buf[1024], name[128];
/* Parse any options */
while (--argc > 0 && **(++argv) == '-') {
if (*((*argv)+1) == '\0') {
fromStdinFlag=TRUE;
}
stopLookingAtMeLikeThat=FALSE;
while (*(++(*argv)) && stopLookingAtMeLikeThat==FALSE) {
switch (**argv) {
case 's':
option |= LOG_PERROR;
break;
case 'p':
if (--argc == 0) {
usage(logger_usage);
}
pri = pencode(*(++argv));
stopLookingAtMeLikeThat=TRUE;
break;
case 't':
if (--argc == 0) {
usage(logger_usage);
}
strncpy(name, *(++argv), sizeof(name));
stopLookingAtMeLikeThat=TRUE;
break;
default:
usage(logger_usage);
}
}
}
/* Fill out the name string early (may be overwritten later */
my_getpwuid(name, geteuid());
if (fromStdinFlag==TRUE) {
/* read from stdin */
int c, i=0;
while ((c = getc(stdin)) != EOF && i<sizeof(buf)) {
buf[i++]=c;
/* Parse any options */
while (--argc > 0 && **(++argv) == '-') {
if (*((*argv) + 1) == '\0') {
fromStdinFlag = TRUE;
}
stopLookingAtMeLikeThat = FALSE;
while (*(++(*argv)) && stopLookingAtMeLikeThat == FALSE) {
switch (**argv) {
case 's':
option |= LOG_PERROR;
break;
case 'p':
if (--argc == 0) {
usage(logger_usage);
}
pri = pencode(*(++argv));
stopLookingAtMeLikeThat = TRUE;
break;
case 't':
if (--argc == 0) {
usage(logger_usage);
}
strncpy(name, *(++argv), sizeof(name));
stopLookingAtMeLikeThat = TRUE;
break;
default:
usage(logger_usage);
}
}
}
message=buf;
} else {
if (argc>=1) {
message = *argv;
if (fromStdinFlag == TRUE) {
/* read from stdin */
int c, i = 0;
while ((c = getc(stdin)) != EOF && i < sizeof(buf)) {
buf[i++] = c;
}
message = buf;
} else {
fprintf(stderr, "No message\n");
exit( FALSE);
if (argc >= 1) {
message = *argv;
} else {
fprintf(stderr, "No message\n");
exit(FALSE);
}
}
}
openlog( name, option, (pri | LOG_FACMASK));
syslog( pri, message);
closelog();
openlog(name, option, (pri | LOG_FACMASK));
syslog(pri, message);
closelog();
exit( TRUE);
exit(TRUE);
}

View File

@ -1,3 +1,4 @@
/* vi: set sw=4 ts=4: */
/*
* Mini logname implementation for busybox
*
@ -23,18 +24,21 @@
#include <stdio.h>
static const char logname_usage[] = "logname\n\n"
"Print the name of the current user.\n";
extern int logname_main(int argc, char **argv) {
"Print the name of the current user.\n";
extern int logname_main(int argc, char **argv)
{
char *cp;
if (argc > 1) usage (logname_usage);
if (argc > 1)
usage(logname_usage);
cp = getlogin ();
cp = getlogin();
if (cp) {
puts (cp);
exit (TRUE);
}
fprintf (stderr, "%s: no login name\n", argv[0]);
exit (FALSE);
puts(cp);
exit(TRUE);
}
fprintf(stderr, "%s: no login name\n", argv[0]);
exit(FALSE);
}

297
ls.c
View File

@ -1,3 +1,4 @@
/* vi: set sw=4 ts=4: */
/*
* tiny-ls.c version 0.1.0: A minimalist 'ls'
* Copyright (C) 1996 Brian Candler <B.Candler@pobox.com>
@ -40,18 +41,18 @@
* 1. requires lstat (BSD) - how do you do it without?
*/
#define TERMINAL_WIDTH 80 /* use 79 if your terminal has linefold bug */
#define COLUMN_WIDTH 14 /* default if AUTOWIDTH not defined */
#define COLUMN_GAP 2 /* includes the file type char, if present */
#define TERMINAL_WIDTH 80 /* use 79 if your terminal has linefold bug */
#define COLUMN_WIDTH 14 /* default if AUTOWIDTH not defined */
#define COLUMN_GAP 2 /* includes the file type char, if present */
#define HAS_REWINDDIR
/************************************************************************/
#include "internal.h"
#if !defined(__GLIBC__) && (__GLIBC__ >= 2) && (__GLIBC_MINOR__ >= 1)
# include <linux/types.h>
# include <linux/types.h>
#else
# include <sys/types.h>
# include <sys/types.h>
#endif
#include <sys/stat.h>
#include <stdio.h>
@ -75,28 +76,28 @@
#endif
#define FMT_AUTO 0
#define FMT_LONG 1 /* one record per line, extended info */
#define FMT_SINGLE 2 /* one record per line */
#define FMT_ROWS 3 /* print across rows */
#define FMT_COLUMNS 3 /* fill columns (same, since we don't sort) */
#define FMT_LONG 1 /* one record per line, extended info */
#define FMT_SINGLE 2 /* one record per line */
#define FMT_ROWS 3 /* print across rows */
#define FMT_COLUMNS 3 /* fill columns (same, since we don't sort) */
#define TIME_MOD 0
#define TIME_CHANGE 1
#define TIME_ACCESS 2
#define DISP_FTYPE 1 /* show character for file type */
#define DISP_EXEC 2 /* show '*' if regular executable file */
#define DISP_HIDDEN 4 /* show files starting . (except . and ..) */
#define DISP_DOT 8 /* show . and .. */
#define DISP_NUMERIC 16 /* numeric uid and gid */
#define DISP_FULLTIME 32 /* show extended time display */
#define DIR_NOLIST 64 /* show directory as itself, not contents */
#define DISP_DIRNAME 128 /* show directory name (for internal use) */
#define DIR_RECURSE 256 /* -R (not yet implemented) */
#define DISP_FTYPE 1 /* show character for file type */
#define DISP_EXEC 2 /* show '*' if regular executable file */
#define DISP_HIDDEN 4 /* show files starting . (except . and ..) */
#define DISP_DOT 8 /* show . and .. */
#define DISP_NUMERIC 16 /* numeric uid and gid */
#define DISP_FULLTIME 32 /* show extended time display */
#define DIR_NOLIST 64 /* show directory as itself, not contents */
#define DISP_DIRNAME 128 /* show directory name (for internal use) */
#define DIR_RECURSE 256 /* -R (not yet implemented) */
static unsigned char display_fmt = FMT_AUTO;
static unsigned short opts = 0;
static unsigned short column = 0;
static unsigned char display_fmt = FMT_AUTO;
static unsigned short opts = 0;
static unsigned short column = 0;
#ifdef BB_FEATURE_AUTOWIDTH
static unsigned short terminal_width = 0, column_width = 0;
@ -113,13 +114,14 @@ static unsigned char time_fmt = TIME_MOD;
static void writenum(long val, short minwidth)
{
char scratch[128];
char scratch[128];
char *p = scratch + sizeof(scratch);
short len = 0;
short neg = (val < 0);
if (neg) val = -val;
if (neg)
val = -val;
do
*--p = (val % 10) + '0', len++, val /= 10;
while (val);
@ -142,8 +144,9 @@ static void newline(void)
static void tab(short col)
{
static const char spaces[] = " ";
#define nspaces ((sizeof spaces)-1) /* null terminator! */
#define nspaces ((sizeof spaces)-1) /* null terminator! */
short n = col - column;
if (n > 0) {
@ -155,7 +158,7 @@ static void tab(short col)
/* must be 1...(sizeof spaces) left */
wr(spaces, n);
}
#undef nspaces
#undef nspaces
}
#ifdef BB_FEATURE_LS_FILETYPES
@ -163,8 +166,8 @@ static char append_char(mode_t mode)
{
if (!(opts & DISP_FTYPE))
return '\0';
if ((opts & DISP_EXEC) && S_ISREG(mode) && (mode & (S_IXUSR|S_IXGRP|S_IXOTH)))
return '*';
if ((opts & DISP_EXEC) && S_ISREG(mode)
&& (mode & (S_IXUSR | S_IXGRP | S_IXOTH))) return '*';
return APPCHAR(mode);
}
#endif
@ -176,89 +179,93 @@ static char append_char(mode_t mode)
**
**/
static void list_single(const char *name, struct stat *info, const char *fullname)
static void list_single(const char *name, struct stat *info,
const char *fullname)
{
char scratch[PATH_MAX + 1];
short len = strlen(name);
#ifdef BB_FEATURE_LS_FILETYPES
char append = append_char(info->st_mode);
#endif
if (display_fmt == FMT_LONG) {
mode_t mode = info->st_mode;
mode_t mode = info->st_mode;
newline();
wr(modeString(mode), 10);
column=10;
writenum((long)info->st_nlink,(short)5);
column = 10;
writenum((long) info->st_nlink, (short) 5);
fputs(" ", stdout);
#ifdef BB_FEATURE_LS_USERNAME
if (!(opts & DISP_NUMERIC)) {
memset ( scratch, 0, sizeof (scratch));
my_getpwuid( scratch, info->st_uid);
memset(scratch, 0, sizeof(scratch));
my_getpwuid(scratch, info->st_uid);
if (*scratch) {
fputs(scratch, stdout);
if ( strlen( scratch) <= 8 )
wr(" ", 9-strlen( scratch));
}
else {
writenum((long) info->st_uid,(short)8);
fputs(scratch, stdout);
if (strlen(scratch) <= 8)
wr(" ", 9 - strlen(scratch));
} else {
writenum((long) info->st_uid, (short) 8);
fputs(" ", stdout);
}
} else
#endif
{
writenum((long) info->st_uid,(short)8);
fputs(" ", stdout);
writenum((long) info->st_uid, (short) 8);
fputs(" ", stdout);
}
#ifdef BB_FEATURE_LS_USERNAME
if (!(opts & DISP_NUMERIC)) {
memset ( scratch, 0, sizeof (scratch));
my_getgrgid( scratch, info->st_gid);
memset(scratch, 0, sizeof(scratch));
my_getgrgid(scratch, info->st_gid);
if (*scratch) {
fputs(scratch, stdout);
if ( strlen( scratch) <= 8 )
wr(" ", 8-strlen( scratch));
}
else
writenum((long) info->st_gid,(short)8);
fputs(scratch, stdout);
if (strlen(scratch) <= 8)
wr(" ", 8 - strlen(scratch));
} else
writenum((long) info->st_gid, (short) 8);
} else
#endif
writenum((long) info->st_gid,(short)8);
writenum((long) info->st_gid, (short) 8);
//tab(26);
if (S_ISBLK(mode) || S_ISCHR(mode)) {
writenum((long)MAJOR(info->st_rdev),(short)3);
writenum((long) MAJOR(info->st_rdev), (short) 3);
fputs(", ", stdout);
writenum((long)MINOR(info->st_rdev),(short)3);
}
else
writenum((long)info->st_size,(short)8);
writenum((long) MINOR(info->st_rdev), (short) 3);
} else
writenum((long) info->st_size, (short) 8);
fputs(" ", stdout);
//tab(32);
#ifdef BB_FEATURE_LS_TIMESTAMPS
{
time_t cal;
char *string;
switch(time_fmt) {
switch (time_fmt) {
case TIME_CHANGE:
cal=info->st_ctime; break;
cal = info->st_ctime;
break;
case TIME_ACCESS:
cal=info->st_atime; break;
cal = info->st_atime;
break;
default:
cal=info->st_mtime; break;
cal = info->st_mtime;
break;
}
string=ctime(&cal);
string = ctime(&cal);
if (opts & DISP_FULLTIME)
wr(string,24);
wr(string, 24);
else {
time_t age = time(NULL) - cal;
wr(string+4,7); /* mmm_dd_ */
if(age < 3600L*24*365/2 && age > -15*60)
wr(string + 4, 7); /* mmm_dd_ */
if (age < 3600L * 24 * 365 / 2 && age > -15 * 60)
/* hh:mm if less than 6 months old */
wr(string+11,5);
wr(string + 11, 5);
else
/* _yyyy otherwise */
wr(string+19,5);
wr(string + 19, 5);
}
wr(" ", 1);
}
@ -269,7 +276,8 @@ static void list_single(const char *name, struct stat *info, const char *fullnam
if (S_ISLNK(mode)) {
wr(" -> ", 4);
len = readlink(fullname, scratch, sizeof scratch);
if (len > 0) fwrite(scratch, 1, len, stdout);
if (len > 0)
fwrite(scratch, 1, len, stdout);
#ifdef BB_FEATURE_LS_FILETYPES
/* show type of destination */
if (opts & DISP_FTYPE) {
@ -287,18 +295,17 @@ static void list_single(const char *name, struct stat *info, const char *fullnam
#endif
} else {
static short nexttab = 0;
/* sort out column alignment */
if (column == 0)
; /* nothing to do */
if (column == 0); /* nothing to do */
else if (display_fmt == FMT_SINGLE)
newline();
else {
if (nexttab + column_width > terminal_width
#ifndef BB_FEATURE_AUTOWIDTH
|| nexttab + len >= terminal_width
|| nexttab + len >= terminal_width
#endif
)
)
newline();
else
tab(nexttab);
@ -336,32 +343,33 @@ static int list_item(const char *name)
struct stat info;
DIR *dir;
struct dirent *entry;
char fullname[MAXNAMLEN+1], *fnend;
char fullname[MAXNAMLEN + 1], *fnend;
if (lstat(name, &info))
goto listerr;
if (!S_ISDIR(info.st_mode) ||
(opts & DIR_NOLIST)) {
if (!S_ISDIR(info.st_mode) || (opts & DIR_NOLIST)) {
list_single(name, &info, name);
return 0;
}
/* Otherwise, it's a directory we want to list the contents of */
if (opts & DISP_DIRNAME) { /* identify the directory */
if (opts & DISP_DIRNAME) { /* identify the directory */
if (column)
wr("\n\n", 2), column = 0;
wr(name, strlen(name));
wr(":\n", 2);
}
dir = opendir(name);
if (!dir) goto listerr;
if (!dir)
goto listerr;
#ifdef BB_FEATURE_AUTOWIDTH
column_width = 0;
while ((entry = readdir(dir)) != NULL) {
short w = strlen(entry->d_name);
if (column_width < w)
column_width = w;
}
@ -370,39 +378,40 @@ static int list_item(const char *name)
#else
closedir(dir);
dir = opendir(name);
if (!dir) goto listerr;
if (!dir)
goto listerr;
#endif
#endif
/* List the contents */
strcpy(fullname,name); /* *** ignore '.' by itself */
fnend=fullname+strlen(fullname);
strcpy(fullname, name); /* *** ignore '.' by itself */
fnend = fullname + strlen(fullname);
if (fnend[-1] != '/')
*fnend++ = '/';
while ((entry = readdir(dir)) != NULL) {
const char *en=entry->d_name;
const char *en = entry->d_name;
if (en[0] == '.') {
if (!en[1] || (en[1] == '.' && !en[2])) { /* . or .. */
if (!en[1] || (en[1] == '.' && !en[2])) { /* . or .. */
if (!(opts & DISP_DOT))
continue;
}
else if (!(opts & DISP_HIDDEN))
} else if (!(opts & DISP_HIDDEN))
continue;
}
/* FIXME: avoid stat if not required */
strcpy(fnend, entry->d_name);
if (lstat(fullname, &info))
goto direrr; /* (shouldn't fail) */
goto direrr; /* (shouldn't fail) */
list_single(entry->d_name, &info, fullname);
}
closedir(dir);
return 0;
direrr:
closedir(dir);
listerr:
direrr:
closedir(dir);
listerr:
newline();
perror(name);
return 1;
@ -432,50 +441,79 @@ static const char ls_usage[] = "ls [-1a"
#endif
"] [filenames...]\n";
extern int
ls_main(int argc, char * * argv)
extern int ls_main(int argc, char **argv)
{
int argi=1, i;
int argi = 1, i;
/* process options */
while (argi < argc && argv[argi][0] == '-') {
const char *p = &argv[argi][1];
if (!*p) goto print_usage_message; /* "-" by itself not allowed */
if (!*p)
goto print_usage_message; /* "-" by itself not allowed */
if (*p == '-') {
if (!p[1]) { /* "--" forces end of options */
if (!p[1]) { /* "--" forces end of options */
argi++;
break;
}
/* it's a long option name - we don't support them */
goto print_usage_message;
}
while (*p)
switch (*p++) {
case 'l': display_fmt = FMT_LONG; break;
case '1': display_fmt = FMT_SINGLE; break;
case 'x': display_fmt = FMT_ROWS; break;
case 'C': display_fmt = FMT_COLUMNS; break;
case 'l':
display_fmt = FMT_LONG;
break;
case '1':
display_fmt = FMT_SINGLE;
break;
case 'x':
display_fmt = FMT_ROWS;
break;
case 'C':
display_fmt = FMT_COLUMNS;
break;
#ifdef BB_FEATURE_LS_FILETYPES
case 'p': opts |= DISP_FTYPE; break;
case 'F': opts |= DISP_FTYPE|DISP_EXEC; break;
case 'p':
opts |= DISP_FTYPE;
break;
case 'F':
opts |= DISP_FTYPE | DISP_EXEC;
break;
#endif
case 'A': opts |= DISP_HIDDEN; break;
case 'a': opts |= DISP_HIDDEN|DISP_DOT; break;
case 'n': opts |= DISP_NUMERIC; break;
case 'd': opts |= DIR_NOLIST; break;
case 'A':
opts |= DISP_HIDDEN;
break;
case 'a':
opts |= DISP_HIDDEN | DISP_DOT;
break;
case 'n':
opts |= DISP_NUMERIC;
break;
case 'd':
opts |= DIR_NOLIST;
break;
#ifdef FEATURE_RECURSIVE
case 'R': opts |= DIR_RECURSE; break;
case 'R':
opts |= DIR_RECURSE;
break;
#endif
#ifdef BB_FEATURE_LS_TIMESTAMPS
case 'u': time_fmt = TIME_ACCESS; break;
case 'c': time_fmt = TIME_CHANGE; break;
case 'e': opts |= DISP_FULLTIME; break;
case 'u':
time_fmt = TIME_ACCESS;
break;
case 'c':
time_fmt = TIME_CHANGE;
break;
case 'e':
opts |= DISP_FULLTIME;
break;
#endif
default: goto print_usage_message;
default:
goto print_usage_message;
}
argi++;
}
@ -483,29 +521,30 @@ ls_main(int argc, char * * argv)
if (display_fmt == FMT_AUTO)
display_fmt = isatty(fileno(stdout)) ? FMT_COLUMNS : FMT_SINGLE;
if (argi < argc - 1)
opts |= DISP_DIRNAME; /* 2 or more items? label directories */
opts |= DISP_DIRNAME; /* 2 or more items? label directories */
#ifdef BB_FEATURE_AUTOWIDTH
/* could add a -w option and/or TIOCGWINSZ call */
if (terminal_width < 1) terminal_width = TERMINAL_WIDTH;
if (terminal_width < 1)
terminal_width = TERMINAL_WIDTH;
for (i = argi; i < argc; i++) {
int len = strlen(argv[i]);
if (column_width < len)
column_width = len;
}
#endif
/* process files specified, or current directory if none */
i=0;
i = 0;
if (argi == argc)
i = list_item(".");
while (argi < argc)
i |= list_item(argv[argi++]);
newline();
exit( i);
exit(i);
print_usage_message:
usage (ls_usage);
exit( FALSE);
print_usage_message:
usage(ls_usage);
exit(FALSE);
}

View File

@ -1,3 +1,4 @@
/* vi: set sw=4 ts=4: */
/*
* Mini lsmod implementation for busybox
*
@ -30,6 +31,7 @@
extern int lsmod_main(int argc, char **argv)
{
char* cmd[] = { "cat", "/proc/modules", "\0" };
exit(cat_main( 3, cmd));
char *cmd[] = { "cat", "/proc/modules", "\0" };
exit(cat_main(3, cmd));
}

View File

@ -1,3 +1,4 @@
/* vi: set sw=4 ts=4: */
/*
* public domain -- Dave 'Kill a Cop' Cinege <dcinege@psychosis.com>
*
@ -5,7 +6,7 @@
* Make ranges of device files quickly.
* known bugs: can't deal with alpha ranges
*/
#include "internal.h"
#include <stdio.h>
#include <stdlib.h>
@ -15,60 +16,64 @@
#include <sys/types.h>
#include <sys/stat.h>
static const char makedevs_usage[] =
"makedevs 0.01 -- Create an entire range of device files\n\n"
"\tmakedevs /dev/ttyS c 4 64 0 63 (ttyS0-ttyS63)\n"
"\tmakedevs /dev/hda b 3 0 0 8 s (hda,hda1-hda8)\n";
static const char makedevs_usage[] =
"makedevs 0.01 -- Create an entire range of device files\n\n"
"\tmakedevs /dev/ttyS c 4 64 0 63 (ttyS0-ttyS63)\n"
int
makedevs_main(int argc, char * * argv)
"\tmakedevs /dev/hda b 3 0 0 8 s (hda,hda1-hda8)\n";
int makedevs_main(int argc, char **argv)
{
const char *basedev = argv[1];
const char *type = argv[2];
int major = atoi(argv[3]);
int Sminor = atoi(argv[4]);
int S = atoi(argv[5]);
int E = atoi(argv[6]);
int sbase = argc == 8 ? 1 : 0;
const char *basedev = argv[1];
const char *type = argv[2];
int major = atoi(argv[3]);
int Sminor = atoi(argv[4]);
int S = atoi(argv[5]);
int E = atoi(argv[6]);
int sbase = argc == 8 ? 1 : 0;
mode_t mode = 0;
dev_t dev = 0;
char devname[255];
char buf[255];
mode_t mode = 0;
dev_t dev = 0;
char devname[255];
char buf[255];
switch (type[0]) {
case 'c':
mode = S_IFCHR; break;
case 'b':
mode = S_IFBLK; break;
case 'f':
mode = S_IFIFO; break;
default:
usage( makedevs_usage);
}
mode |= 0660;
case 'c':
mode = S_IFCHR;
break;
case 'b':
mode = S_IFBLK;
break;
case 'f':
mode = S_IFIFO;
break;
default:
usage(makedevs_usage);
}
mode |= 0660;
while (S <= E) {
while ( S <= E ) {
if (type[0] != 'f')
dev = (major << 8) | Sminor;
strcpy(devname, basedev);
if (sbase == 0) {
sprintf(buf, "%d", S);
sprintf(buf, "%d", S);
strcat(devname, buf);
} else {
sbase = 0;
}
if (mknod (devname, mode, dev))
printf("Failed to create: %s\n", devname);
S++; Sminor++;
if (mknod(devname, mode, dev))
printf("Failed to create: %s\n", devname);
S++;
Sminor++;
}
return 0;
return 0;
}
/*

106
math.c
View File

@ -1,3 +1,4 @@
/* vi: set sw=4 ts=4: */
#include "internal.h"
#include <stdio.h>
#include <stdlib.h>
@ -8,126 +9,114 @@
static const char math_usage[] = "math expression ...";
static double stack[100];
static unsigned int pointer;
static double stack[100];
static unsigned int pointer;
static void
push(double a)
static void push(double a)
{
if ( pointer >= (sizeof(stack) / sizeof(*stack)) ) {
if (pointer >= (sizeof(stack) / sizeof(*stack))) {
fprintf(stderr, "math: stack overflow\n");
exit(-1);
}
else
} else
stack[pointer++] = a;
}
static double
pop()
static double pop()
{
if ( pointer == 0 ) {
if (pointer == 0) {
fprintf(stderr, "math: stack underflow\n");
exit(-1);
}
return stack[--pointer];
}
static void
add()
static void add()
{
push(pop() + pop());
}
static void
sub()
static void sub()
{
double subtrahend = pop();
double subtrahend = pop();
push(pop() - subtrahend);
}
static void
mul()
static void mul()
{
push(pop() * pop());
}
static void
divide()
static void divide()
{
double divisor = pop();
double divisor = pop();
push(pop() / divisor);
}
static void
and()
static void and()
{
push((unsigned int)pop() & (unsigned int)pop());
push((unsigned int) pop() & (unsigned int) pop());
}
static void
or()
static void or()
{
push((unsigned int)pop() | (unsigned int)pop());
push((unsigned int) pop() | (unsigned int) pop());
}
static void
eor()
static void eor()
{
push((unsigned int)pop() ^ (unsigned int)pop());
push((unsigned int) pop() ^ (unsigned int) pop());
}
static void
not()
static void not()
{
push(~(unsigned int)pop());
push(~(unsigned int) pop());
}
static void
print()
static void print()
{
printf("%g\n", pop());
}
struct op {
const char * name;
void (*function)();
const char *name;
void (*function) ();
};
static const struct op operators[] = {
{ "add", add },
{ "and", and },
{ "div", divide },
{ "eor", eor },
{ "mul", mul },
{ "not", not },
{ "or", or },
{ "sub", sub },
{ 0, 0 }
static const struct op operators[] = {
{"add", add},
{"and", and},
{"div", divide},
{"eor", eor},
{"mul", mul},
{"not", not},
{"or", or},
{"sub", sub},
{0, 0}
};
static void
stack_machine(const char * argument)
static void stack_machine(const char *argument)
{
char * endPointer = 0;
double d;
const struct op * o = operators;
char *endPointer = 0;
double d;
const struct op *o = operators;
if ( argument == 0 ) {
if (argument == 0) {
print();
return;
}
d = strtod(argument, &endPointer);
if ( endPointer != argument ) {
if (endPointer != argument) {
push(d);
return;
}
while ( o->name != 0 ) {
if ( strcmp(o->name, argument) == 0 ) {
(*(o->function))();
while (o->name != 0) {
if (strcmp(o->name, argument) == 0) {
(*(o->function)) ();
return;
}
o++;
@ -136,10 +125,9 @@ stack_machine(const char * argument)
exit(-1);
}
int
math_main(int argc, char * * argv)
int math_main(int argc, char **argv)
{
while ( argc >= 2 ) {
while (argc >= 2) {
stack_machine(argv[1]);
argv++;
argc--;

View File

@ -1,3 +1,4 @@
/* vi: set sw=4 ts=4: */
/*
* Copyright (C) 2000 by BitterSweet Enterprises, LLC.
* Written by Karl M. Hegbloom <karlheg@debian.org>
@ -40,25 +41,19 @@
#if defined bb_need_name_too_long || ! defined BB_DECLARE_EXTERN
BB_DEF_MESSAGE(name_too_long, "%s: file name too long\n")
#endif
#if defined bb_need_omitting_directory || ! defined BB_DECLARE_EXTERN
BB_DEF_MESSAGE(omitting_directory, "%s: %s: omitting directory\n")
BB_DEF_MESSAGE(omitting_directory, "%s: %s: omitting directory\n")
#endif
#if defined bb_need_not_a_directory || ! defined BB_DECLARE_EXTERN
BB_DEF_MESSAGE(not_a_directory, "%s: %s: not a directory\n")
BB_DEF_MESSAGE(not_a_directory, "%s: %s: not a directory\n")
#endif
#if defined bb_need_memory_exhausted || ! defined BB_DECLARE_EXTERN
BB_DEF_MESSAGE(memory_exhausted, "%s: memory exhausted\n")
BB_DEF_MESSAGE(memory_exhausted, "%s: memory exhausted\n")
#endif
#if defined bb_need_invalid_date || ! defined BB_DECLARE_EXTERN
BB_DEF_MESSAGE(invalid_date, "%s: invalid date `%s'\n")
BB_DEF_MESSAGE(invalid_date, "%s: invalid date `%s'\n")
#endif
#if defined bb_need_invalid_option || ! defined BB_DECLARE_EXTERN
BB_DEF_MESSAGE(invalid_option, "%s: invalid option -- %c\n")
BB_DEF_MESSAGE(invalid_option, "%s: invalid option -- %c\n")
#endif
#endif /* _BB_MESSAGES_C */
#endif /* _BB_MESSAGES_C */

View File

@ -1,3 +1,4 @@
/* vi: set sw=4 ts=4: */
/*
* public domain -- Dave 'Kill a Cop' Cinege <dcinege@psychosis.com>
*
@ -15,37 +16,38 @@
#include <utmp.h>
static const char dutmp_usage[] = "dutmp\n"
"\n"
"\tDump file or stdin utmp file format to stdout, pipe delimited.\n"
"\tdutmp /var/run/utmp\n";
"\n"
extern int dutmp_main (int argc, char **argv)
"\tDump file or stdin utmp file format to stdout, pipe delimited.\n"
"\tdutmp /var/run/utmp\n";
extern int dutmp_main(int argc, char **argv)
{
FILE *f = stdin;
struct utmp ut;
FILE *f = stdin;
struct utmp ut;
if ((argc < 2) || (**(argv + 1) == '-')) {
usage( dutmp_usage);
}
if ((argc < 2) || (**(argv + 1) == '-')) {
usage(dutmp_usage);
}
if ( **(++argv) == 0 ) {
f = fopen (*(++argv), "r");
if (f < 0 ) {
perror (*argv);
exit (FALSE);
}
}
if (**(++argv) == 0) {
f = fopen(*(++argv), "r");
if (f < 0) {
perror(*argv);
exit(FALSE);
}
}
while (fread (&ut, 1, sizeof (struct utmp), f)) {
// printf("%d:%d:%s:%s:%s:%s:%d:%d:%ld:%ld:%ld:%x\n",
printf ("%d|%d|%s|%s|%s|%s|%d|%d|%ld|%ld|%ld|%x\n",
ut.ut_type, ut.ut_pid, ut.ut_line,
ut.ut_id, ut.ut_user, ut.ut_host,
ut.ut_exit.e_termination, ut.ut_exit.e_exit,
ut.ut_session,
ut.ut_tv.tv_sec, ut.ut_tv.tv_usec, ut.ut_addr);
}
while (fread(&ut, 1, sizeof(struct utmp), f)) {
// printf("%d:%d:%s:%s:%s:%s:%d:%d:%ld:%ld:%ld:%x\n",
printf("%d|%d|%s|%s|%s|%s|%d|%d|%ld|%ld|%ld|%x\n",
ut.ut_type, ut.ut_pid, ut.ut_line,
ut.ut_id, ut.ut_user, ut.ut_host,
ut.ut_exit.e_termination, ut.ut_exit.e_exit,
ut.ut_session,
ut.ut_tv.tv_sec, ut.ut_tv.tv_usec, ut.ut_addr);
}
exit (TRUE);
exit(TRUE);
}

View File

@ -1,3 +1,4 @@
/* vi: set sw=4 ts=4: */
/*
* public domain -- Dave 'Kill a Cop' Cinege <dcinege@psychosis.com>
*
@ -5,7 +6,7 @@
* Make ranges of device files quickly.
* known bugs: can't deal with alpha ranges
*/
#include "internal.h"
#include <stdio.h>
#include <stdlib.h>
@ -15,60 +16,64 @@
#include <sys/types.h>
#include <sys/stat.h>
static const char makedevs_usage[] =
"makedevs 0.01 -- Create an entire range of device files\n\n"
"\tmakedevs /dev/ttyS c 4 64 0 63 (ttyS0-ttyS63)\n"
"\tmakedevs /dev/hda b 3 0 0 8 s (hda,hda1-hda8)\n";
static const char makedevs_usage[] =
"makedevs 0.01 -- Create an entire range of device files\n\n"
"\tmakedevs /dev/ttyS c 4 64 0 63 (ttyS0-ttyS63)\n"
int
makedevs_main(int argc, char * * argv)
"\tmakedevs /dev/hda b 3 0 0 8 s (hda,hda1-hda8)\n";
int makedevs_main(int argc, char **argv)
{
const char *basedev = argv[1];
const char *type = argv[2];
int major = atoi(argv[3]);
int Sminor = atoi(argv[4]);
int S = atoi(argv[5]);
int E = atoi(argv[6]);
int sbase = argc == 8 ? 1 : 0;
const char *basedev = argv[1];
const char *type = argv[2];
int major = atoi(argv[3]);
int Sminor = atoi(argv[4]);
int S = atoi(argv[5]);
int E = atoi(argv[6]);
int sbase = argc == 8 ? 1 : 0;
mode_t mode = 0;
dev_t dev = 0;
char devname[255];
char buf[255];
mode_t mode = 0;
dev_t dev = 0;
char devname[255];
char buf[255];
switch (type[0]) {
case 'c':
mode = S_IFCHR; break;
case 'b':
mode = S_IFBLK; break;
case 'f':
mode = S_IFIFO; break;
default:
usage( makedevs_usage);
}
mode |= 0660;
case 'c':
mode = S_IFCHR;
break;
case 'b':
mode = S_IFBLK;
break;
case 'f':
mode = S_IFIFO;
break;
default:
usage(makedevs_usage);
}
mode |= 0660;
while (S <= E) {
while ( S <= E ) {
if (type[0] != 'f')
dev = (major << 8) | Sminor;
strcpy(devname, basedev);
if (sbase == 0) {
sprintf(buf, "%d", S);
sprintf(buf, "%d", S);
strcat(devname, buf);
} else {
sbase = 0;
}
if (mknod (devname, mode, dev))
printf("Failed to create: %s\n", devname);
S++; Sminor++;
if (mknod(devname, mode, dev))
printf("Failed to create: %s\n", devname);
S++;
Sminor++;
}
return 0;
return 0;
}
/*

View File

@ -1,97 +1,97 @@
/* vi: set sw=4 ts=4: */
#include "internal.h"
#include <stdio.h>
#include <sys/mtio.h>
#include <sys/fcntl.h>
static const char mt_usage[] = "mt [-f device] opcode value\n";
static const char mt_usage[] = "mt [-f device] opcode value\n";
struct mt_opcodes {
char * name;
short value;
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 },
{ "rew", 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 }
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},
{"rew", MTREW},
{"seek", MTSEEK},
{"setblk", MTSETBLK},
{"setdensity", MTSETDENSITY},
{"drvbuffer", MTSETDRVBUFFER},
{"setpart", MTSETPART},
{"tell", MTTELL},
{"wset", MTWSM},
{"unload", MTUNLOAD},
{"unlock", MTUNLOCK},
{"eof", MTWEOF},
{"weof", MTWEOF},
{0, 0}
};
extern int
mt_main(int argc, char** argv)
extern int mt_main(int argc, char **argv)
{
const char * file = "/dev/tape";
const struct mt_opcodes * code = opcodes;
struct mtop op;
int fd;
if ( strcmp(argv[1], "-f") == 0 ) {
if ( argc < 4 ) {
usage (mt_usage);
const char *file = "/dev/tape";
const struct mt_opcodes *code = opcodes;
struct mtop op;
int fd;
if (strcmp(argv[1], "-f") == 0) {
if (argc < 4) {
usage(mt_usage);
}
file = argv[2];
argv += 2;
argc -= 2;
}
while ( code->name != 0 ) {
if ( strcmp(code->name, argv[1]) == 0 )
while (code->name != 0) {
if (strcmp(code->name, argv[1]) == 0)
break;
code++;
}
if ( code->name == 0 ) {
if (code->name == 0) {
fprintf(stderr, "mt: unrecognized opcode %s.\n", argv[1]);
return( FALSE);
return (FALSE);
}
op.mt_op = code->value;
if ( argc >= 3 )
op.mt_count = atoi(argv[2]);
if (argc >= 3)
op.mt_count = atoi(argv[2]);
else
op.mt_count = 1; /* One, not zero, right? */
op.mt_count = 1; /* One, not zero, right? */
if ( (fd = open(file, O_RDONLY, 0)) < 0 ) {
if ((fd = open(file, O_RDONLY, 0)) < 0) {
perror(file);
return( FALSE);
return (FALSE);
}
if ( ioctl(fd, MTIOCTOP, &op) != 0 ) {
if (ioctl(fd, MTIOCTOP, &op) != 0) {
perror(file);
return( FALSE);
return (FALSE);
}
return( TRUE);
return (TRUE);
}

View File

@ -1,3 +1,4 @@
/* vi: set sw=4 ts=4: */
/*
* Mini update implementation for busybox
*
@ -27,20 +28,19 @@
#include <sys/kdaemon.h>
#else
_syscall2(int, bdflush, int, func, int, data);
#endif /* __GLIBC__ */
#endif /* __GLIBC__ */
extern int
update_main(int argc, char** argv)
extern int update_main(int argc, char **argv)
{
/*
* Update is actually two daemons, bdflush and update.
*/
int pid;
int pid;
pid = fork();
if ( pid < 0 )
if (pid < 0)
return pid;
else if ( pid == 0 ) {
else if (pid == 0) {
/*
* This is no longer necessary since 1.3.5x, but it will harmlessly
* exit if that is the case.
@ -52,11 +52,11 @@ update_main(int argc, char** argv)
_exit(0);
}
pid = fork();
if ( pid < 0 )
if (pid < 0)
return pid;
else if ( pid == 0 ) {
else if (pid == 0) {
argv[0] = "update";
for ( ; ; ) {
for (;;) {
sync();
sleep(30);
}

135
mkdir.c
View File

@ -1,3 +1,4 @@
/* vi: set sw=4 ts=4: */
/*
* Mini mkdir implementation for busybox
*
@ -28,14 +29,15 @@
#include <stdio.h>
#include <errno.h>
#include <sys/param.h> /* for PATH_MAX */
#include <sys/param.h> /* for PATH_MAX */
static const char mkdir_usage[] =
"mkdir [OPTION] DIRECTORY...\n\n"
"Create the DIRECTORY(ies), if they do not already exist\n\n"
"Options:\n"
"\t-m\tset permission mode (as in chmod), not rwxrwxrwx - umask\n"
"\t-p\tno error if existing, make parent directories as needed\n";
"mkdir [OPTION] DIRECTORY...\n\n"
"Create the DIRECTORY(ies), if they do not already exist\n\n"
"Options:\n"
"\t-m\tset permission mode (as in chmod), not rwxrwxrwx - umask\n"
"\t-p\tno error if existing, make parent directories as needed\n";
static int parentFlag = FALSE;
@ -44,71 +46,70 @@ static mode_t mode = 0777;
extern int mkdir_main(int argc, char **argv)
{
int i = FALSE;
argc--;
argv++;
int i = FALSE;
/* Parse any options */
while (argc > 0 && **argv == '-') {
while (i == FALSE && *++(*argv)) {
switch (**argv) {
case 'm':
if (--argc == 0)
usage( mkdir_usage);
/* Find the specified modes */
mode = 0;
if (parse_mode(*(++argv), &mode) == FALSE ) {
fprintf(stderr, "Unknown mode: %s\n", *argv);
exit FALSE;
argc--;
argv++;
/* Parse any options */
while (argc > 0 && **argv == '-') {
while (i == FALSE && *++(*argv)) {
switch (**argv) {
case 'm':
if (--argc == 0)
usage(mkdir_usage);
/* Find the specified modes */
mode = 0;
if (parse_mode(*(++argv), &mode) == FALSE) {
fprintf(stderr, "Unknown mode: %s\n", *argv);
exit FALSE;
}
/* Set the umask for this process so it doesn't
* screw up whatever the user just entered. */
umask(0);
i = TRUE;
break;
case 'p':
parentFlag = TRUE;
break;
default:
usage(mkdir_usage);
}
}
/* Set the umask for this process so it doesn't
* screw up whatever the user just entered. */
umask(0);
i = TRUE;
break;
case 'p':
parentFlag = TRUE;
break;
default:
usage( mkdir_usage);
}
argc--;
argv++;
}
argc--;
argv++;
}
if (argc < 1) {
usage( mkdir_usage);
}
if (argc < 1) {
usage(mkdir_usage);
}
while (argc > 0) {
int status;
struct stat statBuf;
char buf[PATH_MAX + 1];
if (strlen(*argv) > PATH_MAX - 1) {
fprintf(stderr, name_too_long, "mkdir");
exit FALSE;
while (argc > 0) {
int status;
struct stat statBuf;
char buf[PATH_MAX + 1];
if (strlen(*argv) > PATH_MAX - 1) {
fprintf(stderr, name_too_long, "mkdir");
exit FALSE;
}
strcpy(buf, *argv);
status = stat(buf, &statBuf);
if (parentFlag == FALSE && status != -1 && errno != ENOENT) {
fprintf(stderr, "%s: File exists\n", buf);
exit FALSE;
}
if (parentFlag == TRUE) {
strcat(buf, "/");
createPath(buf, mode);
} else {
if (mkdir(buf, mode) != 0 && parentFlag == FALSE) {
perror(buf);
exit FALSE;
}
}
argc--;
argv++;
}
strcpy (buf, *argv);
status = stat(buf, &statBuf);
if (parentFlag == FALSE && status != -1 && errno != ENOENT) {
fprintf(stderr, "%s: File exists\n", buf);
exit FALSE;
}
if (parentFlag == TRUE) {
strcat( buf, "/");
createPath(buf, mode);
}
else {
if (mkdir (buf, mode) != 0 && parentFlag == FALSE) {
perror(buf);
exit FALSE;
}
}
argc--;
argv++;
}
exit TRUE;
exit TRUE;
}

View File

@ -1,3 +1,4 @@
/* vi: set sw=4 ts=4: */
/*
* Mini mkfifo implementation for busybox
*
@ -26,36 +27,43 @@
#include <errno.h>
static const char mkfifo_usage[] = "mkfifo [OPTIONS] name\n\n"
"Create the named fifo\n\n"
"Options:\n"
"\t-m\tcreate the fifo with the specified mode; default = a=rw-umask\n";
"Create the named fifo\n\n"
"Options:\n"
"\t-m\tcreate the fifo with the specified mode; default = a=rw-umask\n";
extern int mkfifo_main(int argc, char **argv)
{
char *thisarg;
mode_t mode = 0666;
argc--;
argv++;
char *thisarg;
mode_t mode = 0666;
/* Parse any options */
while (argc > 1) {
if (**argv != '-') usage(mkfifo_usage);
thisarg = *argv; thisarg++;
switch (*thisarg) {
case 'm':
argc--; argv++;
parse_mode(*argv, &mode);
break;
default:
usage (mkfifo_usage);
}
argc--; argv++;
}
if (argc < 1) usage (mkfifo_usage);
if (mkfifo(*argv, mode) < 0) {
perror("mkfifo");
exit(255);
} else {
exit(TRUE);
}
argc--;
argv++;
/* Parse any options */
while (argc > 1) {
if (**argv != '-')
usage(mkfifo_usage);
thisarg = *argv;
thisarg++;
switch (*thisarg) {
case 'm':
argc--;
argv++;
parse_mode(*argv, &mode);
break;
default:
usage(mkfifo_usage);
}
argc--;
argv++;
}
if (argc < 1)
usage(mkfifo_usage);
if (mkfifo(*argv, mode) < 0) {
perror("mkfifo");
exit(255);
} else {
exit(TRUE);
}
}

View File

@ -1,3 +1,4 @@
/* vi: set sw=4 ts=4: */
/*
* mkfs.c - make a linux (minix) file-system.
*
@ -107,27 +108,30 @@
#define BITS_PER_BLOCK (BLOCK_SIZE<<3)
static char * program_name = "mkfs";
static char * device_name = NULL;
static char *program_name = "mkfs";
static char *device_name = NULL;
static int DEV = -1;
static long BLOCKS = 0;
static int check = 0;
static int badblocks = 0;
static int namelen = 30; /* default (changed to 30, per Linus's
suggestion, Sun Nov 21 08:05:07 1993) */
static int namelen = 30; /* default (changed to 30, per Linus's
suggestion, Sun Nov 21 08:05:07 1993) */
static int dirsize = 32;
static int magic = MINIX_SUPER_MAGIC2;
static int version2 = 0;
static char root_block[BLOCK_SIZE] = "\0";
static char * inode_buffer = NULL;
static char *inode_buffer = NULL;
#define Inode (((struct minix_inode *) inode_buffer)-1)
#ifdef HAVE_MINIX2
#define Inode2 (((struct minix2_inode *) inode_buffer)-1)
#endif
static char super_block_buffer[BLOCK_SIZE];
static char boot_block_buffer[512];
#define Super (*(struct minix_super_block *)super_block_buffer)
#define INODES ((unsigned long)Super.s_ninodes)
#ifdef HAVE_MINIX2
@ -164,21 +168,28 @@ static unsigned long req_nr_inodes = 0;
* to compile this under minix, volatile gives a warning, as
* exit() isn't defined as volatile under minix.
*/
static volatile void die(char *str) {
static volatile void die(char *str)
{
fprintf(stderr, "%s: %s\n", program_name, str);
exit(8);
}
static volatile void show_usage()
{
fprintf(stderr, "BusyBox v%s (%s) multi-call binary -- GPL2\n\n", BB_VER, BB_BT);
fprintf(stderr, "Usage: %s [-c | -l filename] [-nXX] [-iXX] /dev/name [blocks]\n\n", program_name);
fprintf(stderr, "BusyBox v%s (%s) multi-call binary -- GPL2\n\n",
BB_VER, BB_BT);
fprintf(stderr,
"Usage: %s [-c | -l filename] [-nXX] [-iXX] /dev/name [blocks]\n\n",
program_name);
fprintf(stderr, "Make a MINIX filesystem.\n\n");
fprintf(stderr, "OPTIONS:\n");
fprintf(stderr, "\t-c\t\tCheck the device for bad blocks\n");
fprintf(stderr, "\t-n [14|30]\tSpecify the maximum length of filenames\n");
fprintf(stderr, "\t-i\t\tSpecify the number of inodes for the filesystem\n");
fprintf(stderr, "\t-l FILENAME\tRead the bad blocks list from FILENAME\n");
fprintf(stderr,
"\t-n [14|30]\tSpecify the maximum length of filenames\n");
fprintf(stderr,
"\t-i\t\tSpecify the number of inodes for the filesystem\n");
fprintf(stderr,
"\t-l FILENAME\tRead the bad blocks list from FILENAME\n");
fprintf(stderr, "\t-v\t\tMake a Minix version 2 filesystem\n\n");
exit(16);
}
@ -190,56 +201,55 @@ static volatile void show_usage()
*/
static void check_mount(void)
{
FILE * f;
struct mntent * mnt;
FILE *f;
struct mntent *mnt;
if ((f = setmntent (MOUNTED, "r")) == NULL)
if ((f = setmntent(MOUNTED, "r")) == NULL)
return;
while ((mnt = getmntent (f)) != NULL)
if (strcmp (device_name, mnt->mnt_fsname) == 0)
while ((mnt = getmntent(f)) != NULL)
if (strcmp(device_name, mnt->mnt_fsname) == 0)
break;
endmntent (f);
endmntent(f);
if (!mnt)
return;
die("%s is mounted; will not make a filesystem here!");
}
static long valid_offset (int fd, int offset)
static long valid_offset(int fd, int offset)
{
char ch;
if (lseek (fd, offset, 0) < 0)
if (lseek(fd, offset, 0) < 0)
return 0;
if (read (fd, &ch, 1) < 1)
if (read(fd, &ch, 1) < 1)
return 0;
return 1;
}
static int count_blocks (int fd)
static int count_blocks(int fd)
{
int high, low;
low = 0;
for (high = 1; valid_offset (fd, high); high *= 2)
for (high = 1; valid_offset(fd, high); high *= 2)
low = high;
while (low < high - 1)
{
while (low < high - 1) {
const int mid = (low + high) / 2;
if (valid_offset (fd, mid))
if (valid_offset(fd, mid))
low = mid;
else
high = mid;
}
valid_offset (fd, 0);
valid_offset(fd, 0);
return (low + 1);
}
static int get_size(const char *file)
static int get_size(const char *file)
{
int fd;
long size;
int fd;
long size;
fd = open(file, O_RDWR);
if (fd < 0) {
@ -250,7 +260,7 @@ static int get_size(const char *file)
close(fd);
return (size * 512);
}
size = count_blocks(fd);
close(fd);
return size;
@ -270,18 +280,18 @@ static void write_tables(void)
die("seek failed in write_tables");
if (BLOCK_SIZE != write(DEV, super_block_buffer, BLOCK_SIZE))
die("unable to write super-block");
if (IMAPS*BLOCK_SIZE != write(DEV,inode_map,IMAPS*BLOCK_SIZE))
if (IMAPS * BLOCK_SIZE != write(DEV, inode_map, IMAPS * BLOCK_SIZE))
die("unable to write inode map");
if (ZMAPS*BLOCK_SIZE != write(DEV,zone_map,ZMAPS*BLOCK_SIZE))
if (ZMAPS * BLOCK_SIZE != write(DEV, zone_map, ZMAPS * BLOCK_SIZE))
die("unable to write zone map");
if (INODE_BUFFER_SIZE != write(DEV,inode_buffer,INODE_BUFFER_SIZE))
if (INODE_BUFFER_SIZE != write(DEV, inode_buffer, INODE_BUFFER_SIZE))
die("unable to write inodes");
}
static void write_block(int blk, char * buffer)
static void write_block(int blk, char *buffer)
{
if (blk*BLOCK_SIZE != lseek(DEV, blk*BLOCK_SIZE, SEEK_SET))
if (blk * BLOCK_SIZE != lseek(DEV, blk * BLOCK_SIZE, SEEK_SET))
die("seek failed in write_block");
if (BLOCK_SIZE != write(DEV, buffer, BLOCK_SIZE))
die("write failed in write_block");
@ -291,10 +301,10 @@ static int get_free_block(void)
{
int blk;
if (used_good_blocks+1 >= MAX_GOOD_BLOCKS)
if (used_good_blocks + 1 >= MAX_GOOD_BLOCKS)
die("too many bad blocks");
if (used_good_blocks)
blk = good_blocks_table[used_good_blocks-1]+1;
blk = good_blocks_table[used_good_blocks - 1] + 1;
else
blk = FIRSTZONE;
while (blk < ZONES && zone_in_use(blk))
@ -310,14 +320,14 @@ static void mark_good_blocks(void)
{
int blk;
for (blk=0 ; blk < used_good_blocks ; blk++)
for (blk = 0; blk < used_good_blocks; blk++)
mark_zone(good_blocks_table[blk]);
}
inline int next(int zone)
{
if (!zone)
zone = FIRSTZONE-1;
zone = FIRSTZONE - 1;
while (++zone < ZONES)
if (zone_in_use(zone))
return zone;
@ -326,11 +336,11 @@ inline int next(int zone)
static void make_bad_inode(void)
{
struct minix_inode * inode = &Inode[MINIX_BAD_INO];
int i,j,zone;
int ind=0,dind=0;
unsigned short ind_block[BLOCK_SIZE>>1];
unsigned short dind_block[BLOCK_SIZE>>1];
struct minix_inode *inode = &Inode[MINIX_BAD_INO];
int i, j, zone;
int ind = 0, dind = 0;
unsigned short ind_block[BLOCK_SIZE >> 1];
unsigned short dind_block[BLOCK_SIZE >> 1];
#define NEXT_BAD (zone = next(zone))
@ -340,34 +350,34 @@ static void make_bad_inode(void)
inode->i_nlinks = 1;
inode->i_time = time(NULL);
inode->i_mode = S_IFREG + 0000;
inode->i_size = badblocks*BLOCK_SIZE;
inode->i_size = badblocks * BLOCK_SIZE;
zone = next(0);
for (i=0 ; i<7 ; i++) {
for (i = 0; i < 7; i++) {
inode->i_zone[i] = zone;
if (!NEXT_BAD)
goto end_bad;
}
inode->i_zone[7] = ind = get_free_block();
memset(ind_block,0,BLOCK_SIZE);
for (i=0 ; i<512 ; i++) {
memset(ind_block, 0, BLOCK_SIZE);
for (i = 0; i < 512; i++) {
ind_block[i] = zone;
if (!NEXT_BAD)
goto end_bad;
}
inode->i_zone[8] = dind = get_free_block();
memset(dind_block,0,BLOCK_SIZE);
for (i=0 ; i<512 ; i++) {
write_block(ind,(char *) ind_block);
memset(dind_block, 0, BLOCK_SIZE);
for (i = 0; i < 512; i++) {
write_block(ind, (char *) ind_block);
dind_block[i] = ind = get_free_block();
memset(ind_block,0,BLOCK_SIZE);
for (j=0 ; j<512 ; j++) {
memset(ind_block, 0, BLOCK_SIZE);
for (j = 0; j < 512; j++) {
ind_block[j] = zone;
if (!NEXT_BAD)
goto end_bad;
}
}
die("too many bad blocks");
end_bad:
end_bad:
if (ind)
write_block(ind, (char *) ind_block);
if (dind)
@ -375,8 +385,7 @@ end_bad:
}
#ifdef HAVE_MINIX2
static void
make_bad_inode2 (void)
static void make_bad_inode2(void)
{
struct minix2_inode *inode = &Inode2[MINIX_BAD_INO];
int i, j, zone;
@ -386,30 +395,30 @@ make_bad_inode2 (void)
if (!badblocks)
return;
mark_inode (MINIX_BAD_INO);
mark_inode(MINIX_BAD_INO);
inode->i_nlinks = 1;
inode->i_atime = inode->i_mtime = inode->i_ctime = time (NULL);
inode->i_atime = inode->i_mtime = inode->i_ctime = time(NULL);
inode->i_mode = S_IFREG + 0000;
inode->i_size = badblocks * BLOCK_SIZE;
zone = next (0);
zone = next(0);
for (i = 0; i < 7; i++) {
inode->i_zone[i] = zone;
if (!NEXT_BAD)
goto end_bad;
}
inode->i_zone[7] = ind = get_free_block ();
memset (ind_block, 0, BLOCK_SIZE);
inode->i_zone[7] = ind = get_free_block();
memset(ind_block, 0, BLOCK_SIZE);
for (i = 0; i < 256; i++) {
ind_block[i] = zone;
if (!NEXT_BAD)
goto end_bad;
}
inode->i_zone[8] = dind = get_free_block ();
memset (dind_block, 0, BLOCK_SIZE);
inode->i_zone[8] = dind = get_free_block();
memset(dind_block, 0, BLOCK_SIZE);
for (i = 0; i < 256; i++) {
write_block (ind, (char *) ind_block);
dind_block[i] = ind = get_free_block ();
memset (ind_block, 0, BLOCK_SIZE);
write_block(ind, (char *) ind_block);
dind_block[i] = ind = get_free_block();
memset(ind_block, 0, BLOCK_SIZE);
for (j = 0; j < 256; j++) {
ind_block[j] = zone;
if (!NEXT_BAD)
@ -417,47 +426,23 @@ make_bad_inode2 (void)
}
}
/* Could make triple indirect block here */
die ("too many bad blocks");
end_bad:
die("too many bad blocks");
end_bad:
if (ind)
write_block (ind, (char *) ind_block);
write_block(ind, (char *) ind_block);
if (dind)
write_block (dind, (char *) dind_block);
write_block(dind, (char *) dind_block);
}
#endif
static void make_root_inode(void)
{
struct minix_inode * inode = &Inode[MINIX_ROOT_INO];
struct minix_inode *inode = &Inode[MINIX_ROOT_INO];
mark_inode(MINIX_ROOT_INO);
inode->i_zone[0] = get_free_block();
inode->i_nlinks = 2;
inode->i_time = time(NULL);
if (badblocks)
inode->i_size = 3*dirsize;
else {
root_block[2*dirsize] = '\0';
root_block[2*dirsize+1] = '\0';
inode->i_size = 2*dirsize;
}
inode->i_mode = S_IFDIR + 0755;
inode->i_uid = getuid();
if (inode->i_uid)
inode->i_gid = getgid();
write_block(inode->i_zone[0],root_block);
}
#ifdef HAVE_MINIX2
static void
make_root_inode2 (void)
{
struct minix2_inode *inode = &Inode2[MINIX_ROOT_INO];
mark_inode (MINIX_ROOT_INO);
inode->i_zone[0] = get_free_block ();
inode->i_nlinks = 2;
inode->i_atime = inode->i_mtime = inode->i_ctime = time (NULL);
if (badblocks)
inode->i_size = 3 * dirsize;
else {
@ -469,7 +454,30 @@ make_root_inode2 (void)
inode->i_uid = getuid();
if (inode->i_uid)
inode->i_gid = getgid();
write_block (inode->i_zone[0], root_block);
write_block(inode->i_zone[0], root_block);
}
#ifdef HAVE_MINIX2
static void make_root_inode2(void)
{
struct minix2_inode *inode = &Inode2[MINIX_ROOT_INO];
mark_inode(MINIX_ROOT_INO);
inode->i_zone[0] = get_free_block();
inode->i_nlinks = 2;
inode->i_atime = inode->i_mtime = inode->i_ctime = time(NULL);
if (badblocks)
inode->i_size = 3 * dirsize;
else {
root_block[2 * dirsize] = '\0';
root_block[2 * dirsize + 1] = '\0';
inode->i_size = 2 * dirsize;
}
inode->i_mode = S_IFDIR + 0755;
inode->i_uid = getuid();
if (inode->i_uid)
inode->i_gid = getgid();
write_block(inode->i_zone[0], root_block);
}
#endif
@ -478,34 +486,38 @@ static void setup_tables(void)
int i;
unsigned long inodes;
memset(super_block_buffer,0,BLOCK_SIZE);
memset(boot_block_buffer,0,512);
memset(super_block_buffer, 0, BLOCK_SIZE);
memset(boot_block_buffer, 0, 512);
MAGIC = magic;
ZONESIZE = 0;
MAXSIZE = version2 ? 0x7fffffff : (7+512+512*512)*1024;
MAXSIZE = version2 ? 0x7fffffff : (7 + 512 + 512 * 512) * 1024;
ZONES = BLOCKS;
/* some magic nrs: 1 inode / 3 blocks */
if ( req_nr_inodes == 0 )
inodes = BLOCKS/3;
if (req_nr_inodes == 0)
inodes = BLOCKS / 3;
else
inodes = req_nr_inodes;
/* Round up inode count to fill block size */
#ifdef HAVE_MINIX2
if (version2)
inodes = ((inodes + MINIX2_INODES_PER_BLOCK - 1) &
~(MINIX2_INODES_PER_BLOCK - 1));
~(MINIX2_INODES_PER_BLOCK - 1));
else
#endif
inodes = ((inodes + MINIX_INODES_PER_BLOCK - 1) &
~(MINIX_INODES_PER_BLOCK - 1));
~(MINIX_INODES_PER_BLOCK - 1));
if (inodes > 65535)
inodes = 65535;
INODES = inodes;
IMAPS = UPPER(INODES + 1,BITS_PER_BLOCK);
IMAPS = UPPER(INODES + 1, BITS_PER_BLOCK);
ZMAPS = 0;
i=0;
while (ZMAPS != UPPER(BLOCKS - (2+IMAPS+ZMAPS+INODE_BLOCKS) + 1,BITS_PER_BLOCK) && i<1000) {
ZMAPS = UPPER(BLOCKS - (2+IMAPS+ZMAPS+INODE_BLOCKS) + 1,BITS_PER_BLOCK);
i = 0;
while (ZMAPS !=
UPPER(BLOCKS - (2 + IMAPS + ZMAPS + INODE_BLOCKS) + 1,
BITS_PER_BLOCK) && i < 1000) {
ZMAPS =
UPPER(BLOCKS - (2 + IMAPS + ZMAPS + INODE_BLOCKS) + 1,
BITS_PER_BLOCK);
i++;
}
/* Real bad hack but overwise mkfs.minix can be thrown
@ -514,50 +526,51 @@ static void setup_tables(void)
* dd if=/dev/zero of=test.fs count=10 bs=1024
* /sbin/mkfs.minix -i 200 test.fs
* */
if (i>=999) {
die ("unable to allocate buffers for maps");
if (i >= 999) {
die("unable to allocate buffers for maps");
}
FIRSTZONE = NORM_FIRSTZONE;
inode_map = malloc(IMAPS * BLOCK_SIZE);
zone_map = malloc(ZMAPS * BLOCK_SIZE);
if (!inode_map || !zone_map)
die("unable to allocate buffers for maps");
memset(inode_map,0xff,IMAPS * BLOCK_SIZE);
memset(zone_map,0xff,ZMAPS * BLOCK_SIZE);
for (i = FIRSTZONE ; i<ZONES ; i++)
memset(inode_map, 0xff, IMAPS * BLOCK_SIZE);
memset(zone_map, 0xff, ZMAPS * BLOCK_SIZE);
for (i = FIRSTZONE; i < ZONES; i++)
unmark_zone(i);
for (i = MINIX_ROOT_INO ; i<=INODES ; i++)
for (i = MINIX_ROOT_INO; i <= INODES; i++)
unmark_inode(i);
inode_buffer = malloc(INODE_BUFFER_SIZE);
if (!inode_buffer)
die("unable to allocate buffer for inodes");
memset(inode_buffer,0,INODE_BUFFER_SIZE);
printf("%ld inodes\n",INODES);
printf("%ld blocks\n",ZONES);
printf("Firstdatazone=%ld (%ld)\n",FIRSTZONE,NORM_FIRSTZONE);
printf("Zonesize=%d\n",BLOCK_SIZE<<ZONESIZE);
printf("Maxsize=%ld\n\n",MAXSIZE);
memset(inode_buffer, 0, INODE_BUFFER_SIZE);
printf("%ld inodes\n", INODES);
printf("%ld blocks\n", ZONES);
printf("Firstdatazone=%ld (%ld)\n", FIRSTZONE, NORM_FIRSTZONE);
printf("Zonesize=%d\n", BLOCK_SIZE << ZONESIZE);
printf("Maxsize=%ld\n\n", MAXSIZE);
}
/*
* Perform a test of a block; return the number of
* blocks readable/writeable.
*/
long do_check(char * buffer, int try, unsigned int current_block)
long do_check(char *buffer, int try, unsigned int current_block)
{
long got;
/* Seek to the correct loc. */
if (lseek(DEV, current_block * BLOCK_SIZE, SEEK_SET) !=
current_block * BLOCK_SIZE ) {
die("seek failed during testing of blocks");
current_block * BLOCK_SIZE) {
die("seek failed during testing of blocks");
}
/* Try the read */
got = read(DEV, buffer, try * BLOCK_SIZE);
if (got < 0) got = 0;
if (got & (BLOCK_SIZE - 1 )) {
if (got < 0)
got = 0;
if (got & (BLOCK_SIZE - 1)) {
printf("Weird values in do_check: probably bugs\n");
}
got /= BLOCK_SIZE;
@ -570,7 +583,7 @@ static void alarm_intr(int alnum)
{
if (currently_testing >= ZONES)
return;
signal(SIGALRM,alarm_intr);
signal(SIGALRM, alarm_intr);
alarm(5);
if (!currently_testing)
return;
@ -580,19 +593,19 @@ static void alarm_intr(int alnum)
static void check_blocks(void)
{
int try,got;
int try, got;
static char buffer[BLOCK_SIZE * TEST_BUFFER_BLOCKS];
currently_testing=0;
signal(SIGALRM,alarm_intr);
currently_testing = 0;
signal(SIGALRM, alarm_intr);
alarm(5);
while (currently_testing < ZONES) {
if (lseek(DEV,currently_testing*BLOCK_SIZE,SEEK_SET) !=
currently_testing*BLOCK_SIZE)
if (lseek(DEV, currently_testing * BLOCK_SIZE, SEEK_SET) !=
currently_testing * BLOCK_SIZE)
die("seek failed in check_blocks");
try = TEST_BUFFER_BLOCKS;
if (currently_testing + try > ZONES)
try = ZONES-currently_testing;
try = ZONES - currently_testing;
got = do_check(buffer, try, currently_testing);
currently_testing += got;
if (got == try)
@ -613,139 +626,141 @@ static void get_list_blocks(filename)
char *filename;
{
FILE *listfile;
unsigned long blockno;
FILE *listfile;
unsigned long blockno;
listfile=fopen(filename,"r");
if(listfile == (FILE *)NULL) {
die("can't open file of bad blocks");
}
while(!feof(listfile)) {
fscanf(listfile,"%ld\n", &blockno);
mark_zone(blockno);
badblocks++;
}
if(badblocks > 1)
printf("%d bad blocks\n", badblocks);
else if (badblocks == 1)
printf("one bad block\n");
listfile = fopen(filename, "r");
if (listfile == (FILE *) NULL) {
die("can't open file of bad blocks");
}
while (!feof(listfile)) {
fscanf(listfile, "%ld\n", &blockno);
mark_zone(blockno);
badblocks++;
}
if (badblocks > 1)
printf("%d bad blocks\n", badblocks);
else if (badblocks == 1)
printf("one bad block\n");
}
extern int
mkfs_minix_main(int argc, char ** argv)
extern int mkfs_minix_main(int argc, char **argv)
{
int i;
char * tmp;
struct stat statbuf;
char * listfile = NULL;
int i;
char *tmp;
struct stat statbuf;
char *listfile = NULL;
if (argc && *argv)
program_name = *argv;
if (INODE_SIZE * MINIX_INODES_PER_BLOCK != BLOCK_SIZE)
die("bad inode size");
if (argc && *argv)
program_name = *argv;
if (INODE_SIZE * MINIX_INODES_PER_BLOCK != BLOCK_SIZE)
die("bad inode size");
#ifdef HAVE_MINIX2
if (INODE_SIZE2 * MINIX2_INODES_PER_BLOCK != BLOCK_SIZE)
die("bad inode size");
if (INODE_SIZE2 * MINIX2_INODES_PER_BLOCK != BLOCK_SIZE)
die("bad inode size");
#endif
opterr = 0;
while ((i = getopt(argc, argv, "ci:l:n:v")) != EOF)
switch (i) {
case 'c':
check=1; break;
case 'i':
req_nr_inodes = (unsigned long) atol(optarg);
break;
case 'l':
listfile = optarg; break;
case 'n':
i = strtoul(optarg,&tmp,0);
if (*tmp)
show_usage();
if (i == 14)
magic = MINIX_SUPER_MAGIC;
else if (i == 30)
magic = MINIX_SUPER_MAGIC2;
else
show_usage();
namelen = i;
dirsize = i+2;
break;
case 'v':
opterr = 0;
while ((i = getopt(argc, argv, "ci:l:n:v")) != EOF)
switch (i) {
case 'c':
check = 1;
break;
case 'i':
req_nr_inodes = (unsigned long) atol(optarg);
break;
case 'l':
listfile = optarg;
break;
case 'n':
i = strtoul(optarg, &tmp, 0);
if (*tmp)
show_usage();
if (i == 14)
magic = MINIX_SUPER_MAGIC;
else if (i == 30)
magic = MINIX_SUPER_MAGIC2;
else
show_usage();
namelen = i;
dirsize = i + 2;
break;
case 'v':
#ifdef HAVE_MINIX2
version2 = 1;
version2 = 1;
#else
fprintf(stderr,"%s: not compiled with minix v2 support\n",program_name,device_name);
exit(-1);
fprintf(stderr, "%s: not compiled with minix v2 support\n",
program_name, device_name);
exit(-1);
#endif
break;
default:
show_usage();
}
argc -= optind;
argv += optind;
if (argc > 0 && !device_name) {
device_name = argv[0];
argc--;
argv++;
}
if (argc > 0) {
BLOCKS = strtol(argv[0],&tmp,0);
if (*tmp) {
printf("strtol error: number of blocks not specified");
show_usage();
}
}
break;
default:
show_usage();
}
argc -= optind;
argv += optind;
if (argc > 0 && !device_name) {
device_name = argv[0];
argc--;
argv++;
}
if (argc > 0) {
BLOCKS = strtol(argv[0], &tmp, 0);
if (*tmp) {
printf("strtol error: number of blocks not specified");
show_usage();
}
}
if (device_name && !BLOCKS)
BLOCKS = get_size (device_name) / 1024;
if (!device_name || BLOCKS<10) {
show_usage();
}
if (device_name && !BLOCKS)
BLOCKS = get_size(device_name) / 1024;
if (!device_name || BLOCKS < 10) {
show_usage();
}
#ifdef HAVE_MINIX2
if (version2) {
if (namelen == 14)
magic = MINIX2_SUPER_MAGIC;
else
magic = MINIX2_SUPER_MAGIC2;
} else
if (version2) {
if (namelen == 14)
magic = MINIX2_SUPER_MAGIC;
else
magic = MINIX2_SUPER_MAGIC2;
} else
#endif
if (BLOCKS > 65535)
BLOCKS = 65535;
check_mount(); /* is it already mounted? */
tmp = root_block;
*(short *)tmp = 1;
strcpy(tmp+2,".");
tmp += dirsize;
*(short *)tmp = 1;
strcpy(tmp+2,"..");
tmp += dirsize;
*(short *)tmp = 2;
strcpy(tmp+2,".badblocks");
DEV = open(device_name,O_RDWR );
if (DEV<0)
die("unable to open %s");
if (fstat(DEV,&statbuf)<0)
die("unable to stat %s");
if (!S_ISBLK(statbuf.st_mode))
check=0;
else if (statbuf.st_rdev == 0x0300 || statbuf.st_rdev == 0x0340)
die("will not try to make filesystem on '%s'");
setup_tables();
if (check)
check_blocks();
else if (listfile)
get_list_blocks(listfile);
if (BLOCKS > 65535)
BLOCKS = 65535;
check_mount(); /* is it already mounted? */
tmp = root_block;
*(short *) tmp = 1;
strcpy(tmp + 2, ".");
tmp += dirsize;
*(short *) tmp = 1;
strcpy(tmp + 2, "..");
tmp += dirsize;
*(short *) tmp = 2;
strcpy(tmp + 2, ".badblocks");
DEV = open(device_name, O_RDWR);
if (DEV < 0)
die("unable to open %s");
if (fstat(DEV, &statbuf) < 0)
die("unable to stat %s");
if (!S_ISBLK(statbuf.st_mode))
check = 0;
else if (statbuf.st_rdev == 0x0300 || statbuf.st_rdev == 0x0340)
die("will not try to make filesystem on '%s'");
setup_tables();
if (check)
check_blocks();
else if (listfile)
get_list_blocks(listfile);
#ifdef HAVE_MINIX2
if (version2) {
make_root_inode2 ();
make_bad_inode2 ();
} else
if (version2) {
make_root_inode2();
make_bad_inode2();
} else
#endif
{
make_root_inode();
make_bad_inode();
}
mark_good_blocks();
write_tables();
return 0;
{
make_root_inode();
make_bad_inode();
}
mark_good_blocks();
write_tables();
return 0;
}

39
mknod.c
View File

@ -1,3 +1,4 @@
/* vi: set sw=4 ts=4: */
/*
* Mini mknod implementation for busybox
*
@ -28,22 +29,22 @@
#include <unistd.h>
static const char mknod_usage[] = "mknod NAME TYPE MAJOR MINOR\n\n"
"Make block or character special files.\n\n"
"TYPEs include:\n"
"\tb:\tMake a block (buffered) device.\n"
"\tc or u:\tMake a character (un-buffered) device.\n"
"\tp:\tMake a named pipe. Major and minor are ignored for named pipes.\n";
"Make block or character special files.\n\n"
"TYPEs include:\n"
"\tb:\tMake a block (buffered) device.\n"
int
mknod_main(int argc, char** argv)
"\tc or u:\tMake a character (un-buffered) device.\n"
"\tp:\tMake a named pipe. Major and minor are ignored for named pipes.\n";
int mknod_main(int argc, char **argv)
{
mode_t mode = 0;
dev_t dev = 0;
mode_t mode = 0;
dev_t dev = 0;
if ( argc != 5 || **(argv+1) == '-' ) {
usage (mknod_usage);
if (argc != 5 || **(argv + 1) == '-') {
usage(mknod_usage);
}
switch(argv[2][0]) {
switch (argv[2][0]) {
case 'c':
case 'u':
mode = S_IFCHR;
@ -55,21 +56,21 @@ mknod_main(int argc, char** argv)
mode = S_IFIFO;
break;
default:
usage (mknod_usage);
usage(mknod_usage);
}
if ( mode == S_IFCHR || mode == S_IFBLK ) {
if (mode == S_IFCHR || mode == S_IFBLK) {
dev = (atoi(argv[3]) << 8) | atoi(argv[4]);
if ( argc != 5 ) {
usage (mknod_usage);
if (argc != 5) {
usage(mknod_usage);
}
}
mode |= 0666;
if ( mknod(argv[1], mode, dev) != 0 ) {
if (mknod(argv[1], mode, dev) != 0) {
perror(argv[1]);
return( FALSE);
return (FALSE);
}
return( TRUE);
return (TRUE);
}

197
mkswap.c
View File

@ -1,3 +1,4 @@
/* vi: set sw=4 ts=4: */
/*
* mkswap.c - set up a linux swap device
*
@ -40,20 +41,21 @@
#include <string.h>
#include <fcntl.h>
#include <stdlib.h>
#include <sys/ioctl.h> /* for _IO */
#include <sys/ioctl.h> /* for _IO */
#include <sys/utsname.h>
#include <sys/stat.h>
#include <asm/page.h> /* for PAGE_SIZE and PAGE_SHIFT */
#include <asm/page.h> /* for PAGE_SIZE and PAGE_SHIFT */
/* we also get PAGE_SIZE via getpagesize() */
static const char mkswap_usage[] = "mkswap [-c] [-v0|-v1] device [block-count]\n\n"
"Prepare a disk partition to be used as a swap partition.\n\n"
"Options:\n"
"\t-c\t\tCheck for read-ability.\n"
"\t-v0\t\tMake version 0 swap [max 128 Megs].\n"
"\t-v1\t\tMake version 1 swap [big!] (default for kernels > 2.1.117).\n"
"\tblock-count\tNumber of block to use (default is entire partition).\n";
static const char mkswap_usage[] =
"mkswap [-c] [-v0|-v1] device [block-count]\n\n"
"Prepare a disk partition to be used as a swap partition.\n\n"
"Options:\n" "\t-c\t\tCheck for read-ability.\n"
"\t-v0\t\tMake version 0 swap [max 128 Megs].\n"
"\t-v1\t\tMake version 1 swap [big!] (default for kernels > 2.1.117).\n"
"\tblock-count\tNumber of block to use (default is entire partition).\n";
#ifndef _IO
@ -64,8 +66,8 @@ static const char mkswap_usage[] = "mkswap [-c] [-v0|-v1] device [block-count]\n
#define BLKGETSIZE _IO(0x12,96)
#endif
static char * program_name = "mkswap";
static char * device_name = NULL;
static char *program_name = "mkswap";
static char *device_name = NULL;
static int DEV = -1;
static long PAGES = 0;
static int check = 0;
@ -74,8 +76,8 @@ static int version = -1;
#define MAKE_VERSION(p,q,r) (65536*(p) + 256*(q) + (r))
static int
linux_version_code(void) {
static int linux_version_code(void)
{
struct utsname my_utsname;
int p, q, r;
@ -83,7 +85,7 @@ linux_version_code(void) {
p = atoi(strtok(my_utsname.release, "."));
q = atoi(strtok(NULL, "."));
r = atoi(strtok(NULL, "."));
return MAKE_VERSION(p,q,r);
return MAKE_VERSION(p, q, r);
}
return 0;
}
@ -98,7 +100,7 @@ static int pagesize;
static int *signature_page;
struct swap_header_v1 {
char bootbits[1024]; /* Space for disklabel etc. */
char bootbits[1024]; /* Space for disklabel etc. */
unsigned int version;
unsigned int last_page;
unsigned int nr_badpages;
@ -106,8 +108,8 @@ struct swap_header_v1 {
unsigned int badpages[1];
} *p;
static void
init_signature_page() {
static void init_signature_page()
{
pagesize = getpagesize();
#ifdef PAGE_SIZE
@ -115,15 +117,15 @@ init_signature_page() {
fprintf(stderr, "Assuming pages of size %d\n", pagesize);
#endif
signature_page = (int *) malloc(pagesize);
memset(signature_page,0,pagesize);
memset(signature_page, 0, pagesize);
p = (struct swap_header_v1 *) signature_page;
}
static void
write_signature(char *sig) {
static void write_signature(char *sig)
{
char *sp = (char *) signature_page;
strncpy(sp+pagesize-10, sig, 10);
strncpy(sp + pagesize - 10, sig, 10);
}
#define V0_MAX_PAGES (8 * (pagesize - 10))
@ -172,42 +174,46 @@ It is roughly 2GB on i386, PPC, m68k, ARM, 1GB on sparc, 512MB on mips,
#define MAX_BADPAGES ((pagesize-1024-128*sizeof(int)-10)/sizeof(int))
static void bit_set (unsigned int *addr, unsigned int nr)
static void bit_set(unsigned int *addr, unsigned int nr)
{
unsigned int r, m;
addr += nr / (8 * sizeof(int));
r = *addr;
m = 1 << (nr & (8 * sizeof(int) - 1));
*addr = r | m;
}
static int bit_test_and_clear (unsigned int *addr, unsigned int nr)
static int bit_test_and_clear(unsigned int *addr, unsigned int nr)
{
unsigned int r, m;
addr += nr / (8 * sizeof(int));
r = *addr;
m = 1 << (nr & (8 * sizeof(int) - 1));
*addr = r & ~m;
return (r & m) != 0;
}
void
die(const char *str) {
void die(const char *str)
{
fprintf(stderr, "%s: %s\n", program_name, str);
exit( FALSE);
exit(FALSE);
}
void
page_ok(int page) {
if (version==0)
void page_ok(int page)
{
if (version == 0)
bit_set(signature_page, page);
}
void
page_bad(int page) {
void page_bad(int page)
{
if (version == 0)
bit_test_and_clear(signature_page, page);
else {
@ -218,8 +224,8 @@ page_bad(int page) {
badpages++;
}
void
check_blocks(void) {
void check_blocks(void)
{
unsigned int current_page;
int do_seek = 1;
char *buffer;
@ -233,8 +239,8 @@ check_blocks(void) {
page_ok(current_page++);
continue;
}
if (do_seek && lseek(DEV,current_page*pagesize,SEEK_SET) !=
current_page*pagesize)
if (do_seek && lseek(DEV, current_page * pagesize, SEEK_SET) !=
current_page * pagesize)
die("seek failed in check_blocks");
if ((do_seek = (pagesize != read(DEV, buffer, pagesize)))) {
page_bad(current_page++);
@ -248,30 +254,28 @@ check_blocks(void) {
printf("%d bad pages\n", badpages);
}
static long valid_offset (int fd, int offset)
static long valid_offset(int fd, int offset)
{
char ch;
if (lseek (fd, offset, 0) < 0)
if (lseek(fd, offset, 0) < 0)
return 0;
if (read (fd, &ch, 1) < 1)
if (read(fd, &ch, 1) < 1)
return 0;
return 1;
}
static int
find_size (int fd)
static int find_size(int fd)
{
unsigned int high, low;
low = 0;
for (high = 1; high > 0 && valid_offset (fd, high); high *= 2)
for (high = 1; high > 0 && valid_offset(fd, high); high *= 2)
low = high;
while (low < high - 1)
{
while (low < high - 1) {
const int mid = (low + high) / 2;
if (valid_offset (fd, mid))
if (valid_offset(fd, mid))
low = mid;
else
high = mid;
@ -280,11 +284,10 @@ find_size (int fd)
}
/* return size in pages, to avoid integer overflow */
static long
get_size(const char *file)
static long get_size(const char *file)
{
int fd;
long size;
int fd;
long size;
fd = open(file, O_RDONLY);
if (fd < 0) {
@ -292,7 +295,8 @@ get_size(const char *file)
exit(1);
}
if (ioctl(fd, BLKGETSIZE, &size) >= 0) {
int sectors_per_page = pagesize/512;
int sectors_per_page = pagesize / 512;
size /= sectors_per_page;
} else {
size = find_size(fd) / pagesize;
@ -301,9 +305,9 @@ get_size(const char *file)
return size;
}
int mkswap_main(int argc, char ** argv)
int mkswap_main(int argc, char **argv)
{
char * tmp;
char *tmp;
struct stat statbuf;
int sz;
int maxpages;
@ -314,56 +318,56 @@ int mkswap_main(int argc, char ** argv)
if (argc && *argv)
program_name = *argv;
init_signature_page(); /* get pagesize */
init_signature_page(); /* get pagesize */
while (argc-- > 1) {
argv++;
if (argv[0][0] != '-') {
if (device_name) {
int blocks_per_page = pagesize/1024;
PAGES = strtol(argv[0],&tmp,0)/blocks_per_page;
int blocks_per_page = pagesize / 1024;
PAGES = strtol(argv[0], &tmp, 0) / blocks_per_page;
if (*tmp)
usage( mkswap_usage);
usage(mkswap_usage);
} else
device_name = argv[0];
} else {
switch (argv[0][1]) {
case 'c':
check=1;
break;
case 'f':
force=1;
break;
case 'v':
version=atoi(argv[0]+2);
break;
default:
usage( mkswap_usage);
case 'c':
check = 1;
break;
case 'f':
force = 1;
break;
case 'v':
version = atoi(argv[0] + 2);
break;
default:
usage(mkswap_usage);
}
}
}
if (!device_name) {
fprintf(stderr,
"%s: error: Nowhere to set up swap on?\n",
program_name);
usage( mkswap_usage);
"%s: error: Nowhere to set up swap on?\n", program_name);
usage(mkswap_usage);
}
sz = get_size(device_name);
if (!PAGES) {
PAGES = sz;
} else if (PAGES > sz && !force) {
fprintf(stderr,
"%s: error: "
"size %ld is larger than device size %d\n",
program_name,
PAGES*(pagesize/1024), sz*(pagesize/1024));
exit( FALSE);
"%s: error: "
"size %ld is larger than device size %d\n",
program_name,
PAGES * (pagesize / 1024), sz * (pagesize / 1024));
exit(FALSE);
}
if (version == -1) {
if (PAGES <= V0_MAX_PAGES)
version = 0;
else if (linux_version_code() < MAKE_VERSION(2,1,117))
else if (linux_version_code() < MAKE_VERSION(2, 1, 117))
version = 0;
else if (pagesize < 2048)
version = 0;
@ -372,21 +376,21 @@ int mkswap_main(int argc, char ** argv)
}
if (version != 0 && version != 1) {
fprintf(stderr, "%s: error: unknown version %d\n",
program_name, version);
usage( mkswap_usage);
program_name, version);
usage(mkswap_usage);
}
if (PAGES < 10) {
fprintf(stderr,
"%s: error: swap area needs to be at least %ldkB\n",
program_name, (long)(10 * pagesize / 1024));
usage( mkswap_usage);
"%s: error: swap area needs to be at least %ldkB\n",
program_name, (long) (10 * pagesize / 1024));
usage(mkswap_usage);
}
#if 0
maxpages = ((version == 0) ? V0_MAX_PAGES : V1_MAX_PAGES);
#else
if (!version)
maxpages = V0_MAX_PAGES;
else if (linux_version_code() >= MAKE_VERSION(2,2,1))
else if (linux_version_code() >= MAKE_VERSION(2, 2, 1))
maxpages = V1_MAX_PAGES;
else {
maxpages = V1_OLD_MAX_PAGES;
@ -397,29 +401,29 @@ int mkswap_main(int argc, char ** argv)
if (PAGES > maxpages) {
PAGES = maxpages;
fprintf(stderr, "%s: warning: truncating swap area to %ldkB\n",
program_name, PAGES * pagesize / 1024);
program_name, PAGES * pagesize / 1024);
}
DEV = open(device_name,O_RDWR);
DEV = open(device_name, O_RDWR);
if (DEV < 0 || fstat(DEV, &statbuf) < 0) {
perror(device_name);
exit( FALSE);
exit(FALSE);
}
if (!S_ISBLK(statbuf.st_mode))
check=0;
check = 0;
else if (statbuf.st_rdev == 0x0300 || statbuf.st_rdev == 0x0340)
die("Will not try to make swapdevice on '%s'");
#ifdef __sparc__
if (!force && version == 0) {
/* Don't overwrite partition table unless forced */
unsigned char *buffer = (unsigned char *)signature_page;
unsigned char *buffer = (unsigned char *) signature_page;
unsigned short *q, sum;
if (read(DEV, buffer, 512) != 512)
die("fatal: first page unreadable");
if (buffer[508] == 0xDA && buffer[509] == 0xBE) {
q = (unsigned short *)(buffer + 510);
q = (unsigned short *) (buffer + 510);
for (sum = 0; q >= (unsigned short *) buffer;)
sum ^= *q--;
if (!sum) {
@ -427,9 +431,8 @@ int mkswap_main(int argc, char ** argv)
%s: Device '%s' contains a valid Sun disklabel.\n\
This probably means creating v0 swap would destroy your partition table\n\
No swap created. If you really want to create swap v0 on that device, use\n\
the -f option to force it.\n",
program_name, device_name);
exit( FALSE);
the -f option to force it.\n", program_name, device_name);
exit(FALSE);
}
}
}
@ -437,11 +440,11 @@ the -f option to force it.\n",
if (version == 0 || check)
check_blocks();
if (version == 0 && !bit_test_and_clear(signature_page,0))
if (version == 0 && !bit_test_and_clear(signature_page, 0))
die("fatal: first page unreadable");
if (version == 1) {
p->version = version;
p->last_page = PAGES-1;
p->last_page = PAGES - 1;
p->nr_badpages = badpages;
}
@ -449,14 +452,14 @@ the -f option to force it.\n",
if (goodpages <= 0)
die("Unable to set up swap-space: unreadable");
printf("Setting up swapspace version %d, size = %ld bytes\n",
version, (long)(goodpages*pagesize));
version, (long) (goodpages * pagesize));
write_signature((version == 0) ? "SWAP-SPACE" : "SWAPSPACE2");
offset = ((version == 0) ? 0 : 1024);
if (lseek(DEV, offset, SEEK_SET) != offset)
die("unable to rewind swap-device");
if (write(DEV,(char*)signature_page+offset, pagesize-offset)
!= pagesize-offset)
if (write(DEV, (char *) signature_page + offset, pagesize - offset)
!= pagesize - offset)
die("unable to write signature page");
/*
@ -464,6 +467,6 @@ the -f option to force it.\n",
* is not actually on disk. (This is a kernel bug.)
*/
if (fsync(DEV))
die("fsync failed");
exit ( TRUE);
die("fsync failed");
exit(TRUE);
}

Some files were not shown because too many files have changed in this diff Show More