Compare commits

..
Author SHA1 Message Date
Denys Vlasenko db726ae0c6 Bump version to 1.33.2
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-11-24 14:27:03 +01:00
Denys Vlasenko bb61205290 hush: fix handling of "cmd && &"
function                                             old     new   delta
done_pipe                                            213     231     +18

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
(cherry picked from commit 83a4967e50)
2021-11-23 05:31:30 +01:00
Denys Vlasenko 56a335378a hush: fix handling of \^C and "^C"
function                                             old     new   delta
parse_stream                                        2238    2252     +14
encode_string                                        243     256     +13
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 2/0 up/down: 27/0)               Total: 27 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
(cherry picked from commit 1b7a9b68d0)
2021-11-23 05:31:30 +01:00
Denys Vlasenko 5b939a6d29 ash: parser: Fix VSLENGTH parsing with trailing garbage
Let's adopt Herbert Xu's patch, not waiting for it to reach dash git:
hush already has a similar fix.

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
(cherry picked from commit 53a7a9cd8c)
2021-11-23 05:31:30 +01:00
Denys Vlasenko d326be2850 unlzma: fix a case where we could read before beginning of buffer
Testcase:

  21 01 01 00 00 00 00 00 e7 01 01 01 ef 00 df b6
  00 17 02 10 11 0f ff 00 16 00 00

Unfortunately, the bug is not reliably causing a segfault,
the behavior depends on what's in memory before the buffer.

function                                             old     new   delta
unpack_lzma_stream                                  2762    2768      +6

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
(cherry picked from commit 04f052c56d)
2021-11-23 05:31:30 +01:00
Denys Vlasenko bcc5b0e6ca Bump version to 1.33.1
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-05-03 20:07:13 +02:00
Denys Vlasenko 611bbfc148 ash: fix ${unset_var/pattern/repl}
function                                             old     new   delta
subevalvar                                          1349    1353      +4

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-05-03 20:06:49 +02:00
Samuel Sapalski 23dd1c75b7 decompress_gunzip: Fix DoS if gzip is corrupt
On certain corrupt gzip files, huft_build will set the error bit on
the result pointer. If afterwards abort_unzip is called huft_free
might run into a segmentation fault or an invalid pointer to
free(p).

In order to mitigate this, we check in huft_free if the error bit
is set and clear it before the linked list is freed.

Signed-off-by: Samuel Sapalski <samuel.sapalski@nokia.com>
Signed-off-by: Peter Kaestle <peter.kaestle@nokia.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-05-03 14:50:09 +02:00
Denys Vlasenko 89358a7131 traceroute: fix option parsing
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-03-09 00:28:26 +01:00
Bernd Kuhls 39b71881b8 update_passwd: fix context variable
Commit
https://git.busybox.net/busybox/commit/libbb/update_passwd.c?id=2496616b0a8d1c80cd1416b73a4847b59b9f969a

changed the variable used from context to seuser but forgot this
change resulting in build errors detected by buildroot autobuilders:

http://autobuild.buildroot.net/results/b89/b89b7d0f0601bb706e76cea31cf4e43326e5540c//build-end.log

libbb/update_passwd.c:51:11: error: 'context' undeclared (first use in
 this function); did you mean 'ucontext'?
   freecon(context);

Signed-off-by: Bernd Kuhls <bernd.kuhls@t-online.de>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-03-09 00:28:26 +01:00
Denys Vlasenko 67cc582d42 ash: make a strdup copy of $HISTFILE for line editing
Otherwise if $HISTFILE is unset or reassigned, bad things can happen.

function                                             old     new   delta
ash_main                                            1210    1218      +8

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-03-09 00:28:26 +01:00
Maxim Storchak ee1e0987e4 httpd: fix offset for sendfile
If the Range: header is not present it the request,
the offset passed to sendfile is wrong,
and httpd falls back to the read-write loop.

function                                             old     new   delta
send_file_and_exit                                   857     865      +8
handle_incoming_and_exit                            2239    2230      -9
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 1/1 up/down: 8/-9)               Total: -1 bytes

Signed-off-by: Maxim Storchak <m.storchak@gmail.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-03-09 00:28:26 +01:00
370 changed files with 6170 additions and 10770 deletions

No files matched your search

+2 -3
View File
@@ -1,6 +1,6 @@
VERSION = 1
PATCHLEVEL = 35
SUBLEVEL = 0
PATCHLEVEL = 33
SUBLEVEL = 2
EXTRAVERSION =
NAME = Unnamed
@@ -612,7 +612,6 @@ quiet_cmd_busybox__ ?= LINK $@
"$(core-y)" \
"$(libs-y)" \
"$(LDLIBS)" \
"$(CONFIG_EXTRA_LDLIBS)" \
&& $(srctree)/scripts/generate_BUFSIZ.sh --post include/common_bufsiz.h
# Generate System.map
+10 -10
View File
@@ -145,21 +145,18 @@ CFLAGS += --sysroot=$(CONFIG_SYSROOT)
export SYSROOT=$(CONFIG_SYSROOT)
endif
# libm may be needed for dc, awk, ntpd
LDLIBS += m
# Android has no separate crypt library
# gcc-4.2.1 fails if we try to feed C source on stdin:
# echo 'int main(void){return 0;}' | $(CC) $(CFLAGS) -lcrypt -o /dev/null -xc -
# fall back to using a temp file:
CRYPT_AVAILABLE := $(shell echo 'int main(void){return 0;}' >bb_libtest.c; $(CC) $(CFLAGS) $(CFLAGS_busybox) -lcrypt -o /dev/null bb_libtest.c >/dev/null 2>&1 && echo "y"; rm bb_libtest.c)
RT_AVAILABLE := $(shell echo 'int main(void){return 0;}' >bb_libtest.c; $(CC) $(CFLAGS) $(CFLAGS_busybox) -lrt -o /dev/null bb_libtest.c >/dev/null 2>&1 && echo "y"; rm bb_libtest.c)
CRYPT_AVAILABLE := $(shell echo 'int main(void){return 0;}' >crypttest.c; $(CC) $(CFLAGS) -lcrypt -o /dev/null crypttest.c >/dev/null 2>&1 && echo "y"; rm crypttest.c)
ifeq ($(CRYPT_AVAILABLE),y)
LDLIBS += crypt
LDLIBS += m rt crypt
else
LDLIBS += m rt
endif
# libm may be needed for dc, awk, ntpd
# librt may be needed for clock_gettime()
ifeq ($(RT_AVAILABLE),y)
LDLIBS += rt
endif
# libpam may use libpthread, libdl and/or libaudit.
# On some platforms that requires an explicit -lpthread, -ldl, -laudit.
@@ -184,10 +181,8 @@ LDLIBS += $(if $(SELINUX_LIBS),$(SELINUX_LIBS:-l%=%),$(SELINUX_PC_MODULES:lib%=%
endif
ifeq ($(CONFIG_FEATURE_NSLOOKUP_BIG),y)
ifneq (,$(findstring linux,$(shell $(CC) $(CFLAGS) -dumpmachine)))
LDLIBS += resolv
endif
endif
ifeq ($(CONFIG_EFENCE),y)
LDLIBS += efence
@@ -212,6 +207,11 @@ LDFLAGS += $(strip $(subst ",,$(CONFIG_EXTRA_LDFLAGS)))
#"))
endif
ifneq ($(CONFIG_EXTRA_LDLIBS),)
LDLIBS += $(strip $(subst ",,$(CONFIG_EXTRA_LDLIBS)))
#"))
endif
# Busybox is a stack-fatty so make sure we increase default size
# TODO: use "make stksizes" to find & fix big stack users
# (we stole scripts/checkstack.pl from the kernel... thanks guys!)
+1 -1
View File
@@ -56,7 +56,7 @@ static int cmp_name(const void *a, const void *b)
static int str_isalnum_(const char *s)
{
while (*s) {
if (!isalnum((unsigned char)*s) && *s != '_')
if (!isalnum(*s) && *s != '_')
return 0;
s++;
}
+1 -1
View File
@@ -19,6 +19,6 @@ int main(int argc, char **argv)
void bb_show_usage(void)
{
fputs_stdout(APPLET_full_usage "\n");
fputs(APPLET_full_usage "\n", stdout);
exit(EXIT_FAILURE);
}
+1 -1
View File
@@ -71,7 +71,7 @@ int main(void)
} else {
printf(", ");
}
printf("%s", usage_array[i].aname);
printf(usage_array[i].aname);
col += len2;
}
printf("\n\n");
+1 -2
View File
@@ -196,10 +196,9 @@ static int write_ar_archive(archive_handle_t *handle)
static void FAST_FUNC header_verbose_list_ar(const file_header_t *file_header)
{
char mode[12];
const char *mode = bb_mode_string(file_header->mode);
char *mtime;
bb_mode_string(mode, file_header->mode);
mtime = ctime(&file_header->mtime);
mtime[16] = ' ';
memmove(&mtime[17], &mtime[20], 4);
+3 -7
View File
@@ -284,7 +284,7 @@ int uncompress_main(int argc UNUSED_PARAM, char **argv)
//usage: "\n -c Write to stdout"
//usage: "\n -f Force"
//usage: "\n -k Keep input files"
//usage: "\n -t Test integrity"
//usage: "\n -t Test file integrity"
//usage:
//usage:#define gunzip_example_usage
//usage: "$ ls -la /tmp/BusyBox*\n"
@@ -407,8 +407,6 @@ int gunzip_main(int argc UNUSED_PARAM, char **argv)
//usage: "\n -c Write to stdout"
//usage: "\n -f Force"
//usage: "\n -k Keep input files"
//usage: "\n -t Test integrity"
//usage:
//usage:#define bzcat_trivial_usage
//usage: "[FILE]..."
//usage:#define bzcat_full_usage "\n\n"
@@ -467,7 +465,6 @@ int bunzip2_main(int argc UNUSED_PARAM, char **argv)
//usage: "\n -c Write to stdout"
//usage: "\n -f Force"
//usage: "\n -k Keep input files"
//usage: "\n -t Test integrity"
//usage:
//usage:#define lzma_trivial_usage
//usage: "-d [-cfk] [FILE]..."
@@ -477,7 +474,6 @@ int bunzip2_main(int argc UNUSED_PARAM, char **argv)
//usage: "\n -c Write to stdout"
//usage: "\n -f Force"
//usage: "\n -k Keep input files"
//usage: "\n -t Test integrity"
//usage:
//usage:#define lzcat_trivial_usage
//usage: "[FILE]..."
@@ -540,7 +536,7 @@ int unlzma_main(int argc UNUSED_PARAM, char **argv)
//usage: "\n -c Write to stdout"
//usage: "\n -f Force"
//usage: "\n -k Keep input files"
//usage: "\n -t Test integrity"
//usage: "\n -t Test file integrity"
//usage:
//usage:#define xz_trivial_usage
//usage: "-d [-cfk] [FILE]..."
@@ -550,7 +546,7 @@ int unlzma_main(int argc UNUSED_PARAM, char **argv)
//usage: "\n -c Write to stdout"
//usage: "\n -f Force"
//usage: "\n -k Keep input files"
//usage: "\n -t Test integrity"
//usage: "\n -t Test file integrity"
//usage:
//usage:#define xzcat_trivial_usage
//usage: "[FILE]..."
+1 -3
View File
@@ -56,13 +56,11 @@
//usage: "\n -1..9 Compression level"
//usage: IF_FEATURE_BZIP2_DECOMPRESS(
//usage: "\n -d Decompress"
//usage: "\n -t Test file integrity"
//usage: )
//usage: "\n -c Write to stdout"
//usage: "\n -f Force"
//usage: "\n -k Keep input files"
//usage: IF_FEATURE_BZIP2_DECOMPRESS(
//usage: "\n -t Test integrity"
//usage: )
#include "libbb.h"
#include "bb_archive.h"
-35
View File
@@ -1,35 +0,0 @@
/*
* Copyright (C) 2021 Denys Vlasenko <vda.linux@googlemail.com>
*
* Licensed under GPLv2, see file LICENSE in this source tree.
*/
//kbuild:lib-$(CONFIG_FEATURE_TAR_CREATE) += chksum_and_xwrite_tar_header.o
//kbuild:lib-$(CONFIG_SMEMCAP) += chksum_and_xwrite_tar_header.o
#include "libbb.h"
#include "bb_archive.h"
void FAST_FUNC chksum_and_xwrite_tar_header(int fd, struct tar_header_t *hp)
{
/* POSIX says that checksum is done on unsigned bytes
* (Sun and HP-UX gets it wrong... more details in
* GNU tar source) */
const unsigned char *cp;
unsigned int chksum, size;
strcpy(hp->magic, "ustar ");
/* Calculate and store the checksum (the sum of all of the bytes of
* the header). The checksum field must be filled with blanks for the
* calculation. The checksum field is formatted differently from the
* other fields: it has 6 digits, a NUL, then a space -- rather than
* digits, followed by a NUL like the other fields... */
memset(hp->chksum, ' ', sizeof(hp->chksum));
cp = (const unsigned char *) hp;
chksum = 0;
size = sizeof(*hp);
do { chksum += *cp++; } while (--size);
sprintf(hp->chksum, "%06o", chksum);
xwrite(fd, hp, sizeof(*hp));
}
+2 -60
View File
@@ -38,20 +38,6 @@
//config: depends on FEATURE_CPIO_O
//config: help
//config: Passthrough mode. Rarely used.
//config:
//config:config FEATURE_CPIO_IGNORE_DEVNO
//config: bool "Support --ignore-devno like GNU cpio"
//config: default y
//config: depends on FEATURE_CPIO_O && LONG_OPTS
//config: help
//config: Optionally ignore device numbers when creating archives.
//config:
//config:config FEATURE_CPIO_RENUMBER_INODES
//config: bool "Support --renumber-inodes like GNU cpio"
//config: default y
//config: depends on FEATURE_CPIO_O && LONG_OPTS
//config: help
//config: Optionally renumber inodes when creating archives.
//applet:IF_CPIO(APPLET(cpio, BB_DIR_BIN, BB_SUID_DROP))
@@ -88,13 +74,7 @@
//usage: "\n -F FILE Input (-t,-i,-p) or output (-o) file"
//usage: "\n -R USER[:GRP] Set owner of created files"
//usage: "\n -L Dereference symlinks"
//usage: "\n -0 NUL terminated input"
//usage: IF_FEATURE_CPIO_IGNORE_DEVNO(
//usage: "\n --ignore-devno"
//usage: )
//usage: IF_FEATURE_CPIO_RENUMBER_INODES(
//usage: "\n --renumber-inodes"
//usage: )
//usage: "\n -0 Input is separated by NULs"
/* GNU cpio 2.9 --help (abridged):
@@ -182,22 +162,17 @@ enum {
IF_FEATURE_CPIO_P(OPTBIT_PASSTHROUGH,)
IF_LONG_OPTS( OPTBIT_QUIET ,)
IF_LONG_OPTS( OPTBIT_2STDOUT ,)
IF_FEATURE_CPIO_IGNORE_DEVNO(OPTBIT_IGNORE_DEVNO,)
IF_FEATURE_CPIO_RENUMBER_INODES(OPTBIT_RENUMBER_INODES,)
OPT_CREATE = IF_FEATURE_CPIO_O((1 << OPTBIT_CREATE )) + 0,
OPT_FORMAT = IF_FEATURE_CPIO_O((1 << OPTBIT_FORMAT )) + 0,
OPT_PASSTHROUGH = IF_FEATURE_CPIO_P((1 << OPTBIT_PASSTHROUGH)) + 0,
OPT_QUIET = IF_LONG_OPTS( (1 << OPTBIT_QUIET )) + 0,
OPT_2STDOUT = IF_LONG_OPTS( (1 << OPTBIT_2STDOUT )) + 0,
OPT_IGNORE_DEVNO = IF_FEATURE_CPIO_IGNORE_DEVNO((1 << OPTBIT_IGNORE_DEVNO)) + 0,
OPT_RENUMBER_INODES = IF_FEATURE_CPIO_RENUMBER_INODES((1 << OPTBIT_RENUMBER_INODES)) + 0,
};
#define OPTION_STR "it0uvdmLF:R:"
struct globals {
struct bb_uidgid_t owner_ugid;
ino_t next_inode;
} FIX_ALIASING;
#define G (*(struct globals*)bb_common_bufsiz1)
void BUG_cpio_globals_too_big(void);
@@ -231,9 +206,6 @@ static NOINLINE int cpio_o(void)
struct inodes_s *next;
struct name_s *names;
struct stat st;
#if ENABLE_FEATURE_CPIO_RENUMBER_INODES
ino_t mapped_inode;
#endif
};
struct inodes_s *links = NULL;
@@ -288,10 +260,6 @@ static NOINLINE int cpio_o(void)
l = xzalloc(sizeof(*l));
l->st = st;
l->next = links;
#if ENABLE_FEATURE_CPIO_RENUMBER_INODES
if (option_mask32 & OPT_RENUMBER_INODES)
l->mapped_inode = ++G.next_inode;
#endif
links = l;
break;
}
@@ -310,11 +278,6 @@ static NOINLINE int cpio_o(void)
free(line);
continue;
}
#if ENABLE_FEATURE_CPIO_RENUMBER_INODES
else if (option_mask32 & OPT_RENUMBER_INODES) {
st.st_ino = ++G.next_inode;
}
#endif
} else { /* line == NULL: EOF */
next_link:
if (links) {
@@ -322,10 +285,6 @@ static NOINLINE int cpio_o(void)
st = links->st;
name = links->names->name;
links->names = links->names->next;
#if ENABLE_FEATURE_CPIO_RENUMBER_INODES
if (links->mapped_inode)
st.st_ino = links->mapped_inode;
#endif
/* GNU cpio is reported to emit file data
* only for the last instance. Mimic that. */
if (links->names == NULL)
@@ -345,11 +304,6 @@ static NOINLINE int cpio_o(void)
}
}
#if ENABLE_FEATURE_CPIO_IGNORE_DEVNO
if (option_mask32 & OPT_IGNORE_DEVNO)
st.st_dev = st.st_rdev = 0;
#endif
bytes += printf("070701"
"%08X%08X%08X%08X%08X%08X%08X"
"%08X%08X%08X%08X" /* GNU cpio uses uppercase hex */
@@ -425,12 +379,6 @@ int cpio_main(int argc UNUSED_PARAM, char **argv)
"null\0" No_argument "0"
"quiet\0" No_argument "\xff"
"to-stdout\0" No_argument "\xfe"
#if ENABLE_FEATURE_CPIO_IGNORE_DEVNO
"ignore-devno\0" No_argument "\xfd"
#endif
#if ENABLE_FEATURE_CPIO_RENUMBER_INODES
"renumber-inodes\0" No_argument "\xfc"
#endif
;
#endif
@@ -470,8 +418,7 @@ int cpio_main(int argc UNUSED_PARAM, char **argv)
if (argv[0] == NULL)
bb_show_usage();
if (opt & OPT_CREATE_LEADING_DIR)
/* GNU cpio 2.13: "cpio -d -p a/b/c" works */
bb_make_directory(argv[0], -1, FILEUTILS_RECUR);
mkdir(argv[0], 0777);
/* Crude existence check:
* close(xopen(argv[0], O_RDONLY | O_DIRECTORY));
* We can also xopen, fstat, IS_DIR, later fchdir.
@@ -481,11 +428,6 @@ int cpio_main(int argc UNUSED_PARAM, char **argv)
* a diffrerent problem earlier.
* This is good enough for now.
*/
//FIXME: GNU cpio -d -p DIR does not immediately create DIR -
//it just prepends "DIR/" to the names of files to be created.
//The first file (fails to) be copied, and then the -d logic
//triggers and creates all necessary directories.
//IOW: bare "cpio -d -p DIR" + ^C shouldn't create anything.
#if !BB_MMU
pp.rd = 3;
pp.wr = 4;
+1 -3
View File
@@ -77,13 +77,11 @@ aa: 85.1% -- replaced with aa.gz
//usage: )
//usage: IF_FEATURE_GZIP_DECOMPRESS(
//usage: "\n -d Decompress"
//usage: "\n -t Test file integrity"
//usage: )
//usage: "\n -c Write to stdout"
//usage: "\n -f Force"
//usage: "\n -k Keep input files"
//usage: IF_FEATURE_GZIP_DECOMPRESS(
//usage: "\n -t Test integrity"
//usage: )
//usage:
//usage:#define gzip_example_usage
//usage: "$ ls -la /tmp/busybox*\n"
+1 -1
View File
@@ -107,7 +107,7 @@ void fallbackSimpleSort(uint32_t* fmap,
#define FALLBACK_QSORT_SMALL_THRESH 10
#define FALLBACK_QSORT_STACK_SIZE 100
static NOINLINE
static
void fallbackQSort3(uint32_t* fmap,
uint32_t* eclass,
int32_t loSt,
+4 -3
View File
@@ -99,8 +99,9 @@ void BZ2_bzCompressInit(bz_stream *strm, int blockSize100k)
s->ptr = (uint32_t*)s->arr1;
s->arr2 = xmalloc((n + BZ_N_OVERSHOOT) * sizeof(uint32_t));
s->block = (uint8_t*)s->arr2;
s->ftab = xmalloc(65537 * sizeof(uint32_t));
crc32_filltable(s->crc32table, 1);
s->crc32table = crc32_filltable(NULL, 1);
s->state = BZ_S_INPUT;
s->mode = BZ_M_RUNNING;
@@ -368,8 +369,8 @@ void BZ2_bzCompressEnd(bz_stream *strm)
s = strm->state;
free(s->arr1);
free(s->arr2);
//free(s->ftab); // made it array member of s
//free(s->crc32table); // ditto
free(s->ftab);
free(s->crc32table);
free(s);
}
+4 -7
View File
@@ -134,7 +134,7 @@ typedef struct EState {
/* for doing the block sorting */
uint32_t *arr1;
uint32_t *arr2;
//uint32_t *ftab; //moved into this struct, see below
uint32_t *ftab;
uint16_t *quadrant;
int32_t budget;
@@ -160,6 +160,9 @@ typedef struct EState {
uint32_t bsBuff;
int32_t bsLive;
/* guess what */
uint32_t *crc32table;
/* block and combined CRCs */
uint32_t blockCRC;
uint32_t combinedCRC;
@@ -182,12 +185,6 @@ typedef struct EState {
uint8_t len[BZ_N_GROUPS][BZ_MAX_ALPHA_SIZE];
/* guess what */
uint32_t crc32table[256];
/* for doing the block sorting */
uint32_t ftab[65537];
/* stack-saving measures: these can be local, but they are too big */
int32_t sendMTFValues__code [BZ_N_GROUPS][BZ_MAX_ALPHA_SIZE];
int32_t sendMTFValues__rfreq[BZ_N_GROUPS][BZ_MAX_ALPHA_SIZE];
-4
View File
@@ -159,10 +159,6 @@ void FAST_FUNC data_extract_all(archive_handle_t *archive_handle)
break;
}
case S_IFDIR:
//TODO: this causes problems if tarball contains a r-xr-xr-x directory:
// we create this directory, and then fail to create files inside it
// (if tar xf isn't run as root).
// GNU tar works around this by chmod-ing directories *after* all files are extracted.
res = mkdir(dst_name, file_header->mode);
if ((res != 0)
&& (errno != EISDIR) /* btw, Linux doesn't return this */
+3 -2
View File
@@ -230,8 +230,9 @@ static void huft_free(huft_t *p)
* If 'p' has the error bit set we have to clear it, otherwise we might run
* into a segmentation fault or an invalid pointer to free(p)
*/
//if (BAD_HUFT(p)) // commented out, since bit clearing has effect only if condition is true
p = (huft_t*)((uintptr_t)p & ~(uintptr_t)ERR_RET);
if (BAD_HUFT(p)) {
p = (huft_t*)((uintptr_t)(p) ^ (uintptr_t)(ERR_RET));
}
/* Go through linked list, freeing from the malloced (t[-1]) address. */
while (p) {
+1 -5
View File
@@ -92,12 +92,8 @@ char FAST_FUNC get_header_ar(archive_handle_t *archive_handle)
/* Only size is always present, the rest may be missing in
* long filename pseudo file. Thus we decode the rest
* after dealing with long filename pseudo file.
*
* GNU binutils in deterministic mode hard codes mode to 0644 (NOT
* 0100644). AR archives can only contain files, so force file
* mode.
*/
typed->mode = read_num(ar.formatted.mode, 8, sizeof(ar.formatted.mode)) | S_IFREG;
typed->mode = read_num(ar.formatted.mode, 8, sizeof(ar.formatted.mode));
typed->gid = read_num(ar.formatted.gid, 10, sizeof(ar.formatted.gid));
typed->uid = read_num(ar.formatted.uid, 10, sizeof(ar.formatted.uid));
typed->mtime = read_num(ar.formatted.date, 10, sizeof(ar.formatted.date));
+1 -2
View File
@@ -20,7 +20,7 @@ typedef struct hardlinks_t {
char FAST_FUNC get_header_cpio(archive_handle_t *archive_handle)
{
file_header_t *file_header = archive_handle->file_header;
char cpio_header[111];
char cpio_header[110];
int namesize;
int major, minor, nlink, mode, inode;
unsigned size, uid, gid, mtime;
@@ -43,7 +43,6 @@ char FAST_FUNC get_header_cpio(archive_handle_t *archive_handle)
bb_simple_error_msg_and_die("unsupported cpio format, use newc or crc");
}
cpio_header[110] = '\0'; /* sscanf may call strlen which may break without this */
if (sscanf(cpio_header + 6,
"%8x" "%8x" "%8x" "%8x"
"%8x" "%8x" "%8x" /*maj,min:*/ "%*16c"
+3 -9
View File
@@ -147,12 +147,6 @@ static void process_pax_hdr(archive_handle_t *archive_handle, unsigned sz, int g
#endif
}
static void die_if_bad_fnamesize(off_t sz)
{
if ((uoff_t)sz > 0xfff) /* more than 4k?! no funny business please */
bb_simple_error_msg_and_die("bad archive");
}
char FAST_FUNC get_header_tar(archive_handle_t *archive_handle)
{
file_header_t *file_header = archive_handle->file_header;
@@ -337,6 +331,8 @@ char FAST_FUNC get_header_tar(archive_handle_t *archive_handle)
file_header->name = xstrdup(tar.name);
}
/* Set bits 12-15 of the files mode */
/* (typeflag was not trashed because chksum does not use getOctal) */
switch (tar_typeflag) {
case '1': /* hardlink */
/* we mark hardlinks as regular files with zero size and a link name */
@@ -345,7 +341,7 @@ char FAST_FUNC get_header_tar(archive_handle_t *archive_handle)
* ... For tar archives written by pre POSIX.1-1988
* implementations, the size field usually contains the size of
* the file and needs to be ignored as no data may follow this
* header type. For POSIX.1-1988 compliant archives, the size
* header type. For POSIX.1- 1988 compliant archives, the size
* field needs to be 0. For POSIX.1-2001 compliant archives,
* the size field may be non zero, indicating that file data is
* included in the archive.
@@ -394,7 +390,6 @@ char FAST_FUNC get_header_tar(archive_handle_t *archive_handle)
/* free: paranoia: tar with several consecutive longnames */
free(p_longname);
/* For paranoia reasons we allocate extra NUL char */
die_if_bad_fnamesize(file_header->size);
p_longname = xzalloc(file_header->size + 1);
/* We read ASCIZ string, including NUL */
xread(archive_handle->src_fd, p_longname, file_header->size);
@@ -405,7 +400,6 @@ char FAST_FUNC get_header_tar(archive_handle_t *archive_handle)
goto again;
case 'K':
free(p_linkname);
die_if_bad_fnamesize(file_header->size);
p_linkname = xzalloc(file_header->size + 1);
xread(archive_handle->src_fd, p_linkname, file_header->size);
archive_handle->offset += file_header->size;
+2 -3
View File
@@ -9,7 +9,6 @@ void FAST_FUNC header_verbose_list(const file_header_t *file_header)
{
struct tm tm_time;
struct tm *ptm = &tm_time; //localtime(&file_header->mtime);
char modestr[12];
#if ENABLE_FEATURE_TAR_UNAME_GNAME
char uid[sizeof(int)*3 + 2];
@@ -30,7 +29,7 @@ void FAST_FUNC header_verbose_list(const file_header_t *file_header)
group = utoa(file_header->gid);
}
printf("%s %s/%s %9"OFF_FMT"u %4u-%02u-%02u %02u:%02u:%02u %s",
bb_mode_string(modestr, file_header->mode),
bb_mode_string(file_header->mode),
user,
group,
file_header->size,
@@ -47,7 +46,7 @@ void FAST_FUNC header_verbose_list(const file_header_t *file_header)
localtime_r(&file_header->mtime, ptm);
printf("%s %u/%u %9"OFF_FMT"u %4u-%02u-%02u %02u:%02u:%02u %s",
bb_mode_string(modestr, file_header->mode),
bb_mode_string(file_header->mode),
(unsigned)file_header->uid,
(unsigned)file_header->gid,
file_header->size,
+1 -1
View File
@@ -545,7 +545,7 @@ static enum xz_ret XZ_FUNC dec_block_header(struct xz_dec *s)
return XZ_OK;
}
static NOINLINE enum xz_ret XZ_FUNC dec_main(struct xz_dec *s, struct xz_buf *b)
static enum xz_ret XZ_FUNC dec_main(struct xz_dec *s, struct xz_buf *b)
{
enum xz_ret ret;
-1
View File
@@ -86,7 +86,6 @@
//usage: "\n -f Force"
//usage: "\n -U Delete input files"
///////: "\n -k Keep input files" (default, so why bother documenting?)
//usage: "\n -t Test integrity"
//usage: "\n -v Verbose"
//usage: "\n -F Don't verify checksum"
+41 -15
View File
@@ -254,6 +254,32 @@ static void putOctal(char *cp, int len, off_t value)
}
#define PUT_OCTAL(a, b) putOctal((a), sizeof(a), (b))
static void chksum_and_xwrite(int fd, struct tar_header_t* hp)
{
/* POSIX says that checksum is done on unsigned bytes
* (Sun and HP-UX gets it wrong... more details in
* GNU tar source) */
const unsigned char *cp;
int chksum, size;
strcpy(hp->magic, "ustar ");
/* Calculate and store the checksum (i.e., the sum of all of the bytes of
* the header). The checksum field must be filled with blanks for the
* calculation. The checksum field is formatted differently from the
* other fields: it has 6 digits, a null, then a space -- rather than
* digits, followed by a null like the other fields... */
memset(hp->chksum, ' ', sizeof(hp->chksum));
cp = (const unsigned char *) hp;
chksum = 0;
size = sizeof(*hp);
do { chksum += *cp++; } while (--size);
putOctal(hp->chksum, sizeof(hp->chksum)-1, chksum);
/* Now write the header out to disk */
xwrite(fd, hp, sizeof(*hp));
}
# if ENABLE_FEATURE_TAR_GNU_EXTENSIONS
static void writeLongname(int fd, int type, const char *name, int dir)
{
@@ -284,7 +310,7 @@ static void writeLongname(int fd, int type, const char *name, int dir)
/* + dir: account for possible '/' */
PUT_OCTAL(header.size, size);
chksum_and_xwrite_tar_header(fd, &header);
chksum_and_xwrite(fd, &header);
/* Write filename[/] and pad the block. */
/* dir=0: writes 'name<NUL>', pads */
@@ -415,7 +441,8 @@ static int writeTarHeader(struct TarBallInfo *tbInfo,
header_name, S_ISDIR(statbuf->st_mode));
# endif
chksum_and_xwrite_tar_header(tbInfo->tarFd, &header);
/* Now write the header out to disk */
chksum_and_xwrite(tbInfo->tarFd, &header);
/* Now do the verbose thing (or not) */
if (tbInfo->verboseFlag) {
@@ -480,9 +507,6 @@ static int FAST_FUNC writeFileToTarball(struct recursive_state *state,
if (header_name[0] == '\0')
return TRUE;
if (exclude_file(tbInfo->excludeList, header_name))
return SKIP; /* "do not recurse on this directory", no error message printed */
/* It is against the rules to archive a socket */
if (S_ISSOCK(statbuf->st_mode)) {
bb_error_msg("%s: socket ignored", fileName);
@@ -516,6 +540,9 @@ static int FAST_FUNC writeFileToTarball(struct recursive_state *state,
return TRUE;
}
if (exclude_file(tbInfo->excludeList, header_name))
return SKIP;
# if !ENABLE_FEATURE_TAR_GNU_EXTENSIONS
if (strlen(header_name) >= NAME_SIZE) {
bb_simple_error_msg("names longer than "NAME_SIZE_STR" chars not supported");
@@ -528,13 +555,13 @@ static int FAST_FUNC writeFileToTarball(struct recursive_state *state,
/* open the file we want to archive, and make sure all is well */
inputFileFd = open_or_warn(fileName, O_RDONLY);
if (inputFileFd < 0) {
return FALSE; /* make recursive_action() return FALSE */
return FALSE;
}
}
/* Add an entry to the tarball */
if (writeTarHeader(tbInfo, header_name, fileName, statbuf) == FALSE) {
return FALSE; /* make recursive_action() return FALSE */
return FALSE;
}
/* If it was a regular file, write out the body */
@@ -748,7 +775,7 @@ static llist_t *append_file_list_to_list(llist_t *list)
//usage: IF_FEATURE_TAR_NOPRESERVE_TIME("m")
//usage: "vokO] "
//usage: "[-f TARFILE] [-C DIR] "
//usage: IF_FEATURE_TAR_FROM("[-T FILE] [-X FILE] "IF_FEATURE_TAR_LONG_OPTIONS("[LONGOPT]... "))
//usage: IF_FEATURE_TAR_FROM("[-T FILE] [-X FILE] "IF_FEATURE_TAR_LONG_OPTIONS("[OPTION]... "))
//usage: "[FILE]..."
//usage:#define tar_full_usage "\n\n"
//usage: IF_FEATURE_TAR_CREATE("Create, extract, ")
@@ -1105,15 +1132,14 @@ int tar_main(int argc UNUSED_PARAM, char **argv)
tar_handle->ah_flags &= ~ARCHIVE_RESTORE_DATE;
#if ENABLE_FEATURE_TAR_FROM
/* Convert each -X EXCLFILE to list of to-be-rejected glob patterns */
tar_handle->reject = append_file_list_to_list(tar_handle->reject);
# if ENABLE_FEATURE_TAR_LONG_OPTIONS
/* Append --exclude=GLOBPATTERNs to reject */
if (excludes) {
llist_t **p2next = &tar_handle->reject;
while (*p2next)
p2next = &((*p2next)->link);
*p2next = excludes;
/* Append excludes to reject */
while (excludes) {
llist_t *next = excludes->link;
excludes->link = tar_handle->reject;
tar_handle->reject = excludes;
excludes = next;
}
# endif
tar_handle->accept = append_file_list_to_list(tar_handle->accept);
+7 -31
View File
@@ -56,15 +56,14 @@
//kbuild:lib-$(CONFIG_UNZIP) += unzip.o
//usage:#define unzip_trivial_usage
//usage: "[-lnojpq] FILE[.zip] [FILE]... [-x FILE]... [-d DIR]"
//usage: "[-lnojpq] FILE[.zip] [FILE]... [-x FILE...] [-d DIR]"
//usage:#define unzip_full_usage "\n\n"
//usage: "Extract FILEs from ZIP archive\n"
//usage: "\n -l List contents (with -q for short form)"
//usage: "\n -n Never overwrite files (default: ask)"
//usage: "\n -o Overwrite"
//usage: "\n -j Do not restore paths"
//usage: "\n -p Write to stdout"
//usage: "\n -t Test"
//usage: "\n -p Print to stdout"
//usage: "\n -q Quiet"
//usage: "\n -x FILE Exclude FILEs"
//usage: "\n -d DIR Extract into DIR"
@@ -83,13 +82,11 @@ enum {
ZIP_FILEHEADER_MAGIC = 0x504b0304,
ZIP_CDF_MAGIC = 0x504b0102, /* CDF item */
ZIP_CDE_MAGIC = 0x504b0506, /* End of CDF */
ZIP64_CDE_MAGIC = 0x504b0606, /* End of Zip64 CDF */
ZIP_DD_MAGIC = 0x504b0708,
#else
ZIP_FILEHEADER_MAGIC = 0x04034b50,
ZIP_CDF_MAGIC = 0x02014b50,
ZIP_CDE_MAGIC = 0x06054b50,
ZIP64_CDE_MAGIC = 0x06064b50,
ZIP_DD_MAGIC = 0x08074b50,
#endif
};
@@ -263,12 +260,6 @@ static uint32_t find_cdf_offset(void)
continue;
/* we found CDE! */
memcpy(cde.raw, p + 1, CDE_LEN);
dbg("cde.this_disk_no:%d", cde.fmt.this_disk_no );
dbg("cde.disk_with_cdf_no:%d", cde.fmt.disk_with_cdf_no );
dbg("cde.cdf_entries_on_this_disk:%d", cde.fmt.cdf_entries_on_this_disk);
dbg("cde.cdf_entries_total:%d", cde.fmt.cdf_entries_total );
dbg("cde.cdf_size:%d", cde.fmt.cdf_size );
dbg("cde.cdf_offset:%x", cde.fmt.cdf_offset );
FIX_ENDIANNESS_CDE(cde);
/*
* I've seen .ZIP files with seemingly valid CDEs
@@ -311,27 +302,19 @@ static uint32_t read_next_cdf(uint32_t cdf_offset, cdf_header_t *cdf)
dbg("got ZIP_CDE_MAGIC");
return 0; /* EOF */
}
if (magic == ZIP64_CDE_MAGIC) { /* seen in .zip with >4GB files */
dbg("got ZIP64_CDE_MAGIC");
return 0; /* EOF */
}
xread(zip_fd, cdf->raw, CDF_HEADER_LEN);
FIX_ENDIANNESS_CDF(*cdf);
dbg(" magic:%08x filename_len:%u extra_len:%u file_comment_length:%u",
magic,
dbg(" filename_len:%u extra_len:%u file_comment_length:%u",
(unsigned)cdf->fmt.filename_len,
(unsigned)cdf->fmt.extra_len,
(unsigned)cdf->fmt.file_comment_length
);
//TODO: require that magic == ZIP_CDF_MAGIC?
cdf_offset += 4 + CDF_HEADER_LEN
+ cdf->fmt.filename_len
+ cdf->fmt.extra_len
+ cdf->fmt.file_comment_length;
dbg("Next cdf_offset 0x%x", cdf_offset);
return cdf_offset;
};
#endif
@@ -453,9 +436,7 @@ static void unzip_extract(zip_header_t *zip, int dst_fd)
}
/* Validate decompression - size */
if (zip->fmt.ucmpsize != 0xffffffff /* seen on files with >4GB uncompressed data */
&& zip->fmt.ucmpsize != xstate.bytes_out
) {
if (zip->fmt.ucmpsize != xstate.bytes_out) {
/* Don't die. Who knows, maybe len calculation
* was botched somewhere. After all, crc matched! */
bb_simple_error_msg("bad length");
@@ -557,7 +538,7 @@ int unzip_main(int argc, char **argv)
opts = 0;
/* '-' makes getopt return 1 for non-options */
while ((i = getopt(argc, argv, "-d:lnotpqxjv")) != -1) {
while ((i = getopt(argc, argv, "-d:lnopqxjv")) != -1) {
switch (i) {
case 'd': /* Extract to base directory */
base_dir = optarg;
@@ -575,13 +556,8 @@ int unzip_main(int argc, char **argv)
overwrite = O_ALWAYS;
break;
case 't': /* Extract files to /dev/null */
xmove_fd(xopen("/dev/null", O_WRONLY), STDOUT_FILENO);
/*fallthrough*/
case 'p': /* Extract files to stdout */
case 'p': /* Extract files to stdout and fall through to set verbosity */
dst_fd = STDOUT_FILENO;
/*fallthrough*/
case 'q': /* Be quiet */
quiet++;
@@ -990,6 +966,7 @@ int unzip_main(int argc, char **argv)
/* O_NOFOLLOW defends against symlink attacks */
dst_fd = xopen(dst_fn, O_WRONLY | O_CREAT | O_TRUNC | O_NOFOLLOW);
#endif
do_extract:
if (!quiet) {
printf(/* zip.fmt.method == 0
? " extracting: %s\n"
@@ -997,7 +974,6 @@ int unzip_main(int argc, char **argv)
printable_string(dst_fn)
);
}
do_extract:
#if ENABLE_FEATURE_UNZIP_CDF
if (S_ISLNK(file_mode)) {
if (dst_fd != STDOUT_FILENO) /* not -p? */
+2
View File
@@ -33,6 +33,7 @@
## Assorted header problems:
## # CONFIG_HOSTID is not set
## # CONFIG_FEATURE_SYNC_FANCY is not set - syncfs()
## # CONFIG_FEATURE_TOUCH_NODEREF is not set - lutimes()
## # CONFIG_LOGNAME is not set - getlogin_r()
## # CONFIG_LOADFONT is not set
## # CONFIG_SETFONT is not set
@@ -268,6 +269,7 @@ CONFIG_SYNC=y
CONFIG_TEST=y
CONFIG_FEATURE_TEST_64=y
CONFIG_TOUCH=y
# CONFIG_FEATURE_TOUCH_NODEREF is not set
CONFIG_FEATURE_TOUCH_SUSV3=y
CONFIG_TR=y
CONFIG_FEATURE_TR_CLASSES=y
+1
View File
@@ -193,6 +193,7 @@ CONFIG_SYNC=y
CONFIG_TEST=y
CONFIG_FEATURE_TEST_64=y
CONFIG_TOUCH=y
# CONFIG_FEATURE_TOUCH_NODEREF is not set
CONFIG_FEATURE_TOUCH_SUSV3=y
CONFIG_TR=y
CONFIG_FEATURE_TR_CLASSES=y
+1 -1
View File
@@ -399,7 +399,7 @@ setfont [-O font+umap.orig] [-o font.orig] [-om cmap.orig]
-V Version
*/
//usage:#define setfont_trivial_usage
//usage: "[-m MAPFILE] [-C TTY] FILE"
//usage: "FONT [-m MAPFILE] [-C TTY]"
//usage:#define setfont_full_usage "\n\n"
//usage: "Load a console font\n"
//usage: "\n -m MAPFILE Load console screen map"
+1 -13
View File
@@ -74,19 +74,7 @@ int resize_main(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
+ (1 << SIGTERM)
+ (1 << SIGALRM)
, onintr);
/* Users report:
* The resize command messes up the terminal.
* In my case it looks like it is hanging and
* I need to press ctrl-c to get a prompt.
* Actually the program does not hang but just
* the terminal is messed up.
* Replaced TCSANOW with TCSAFLUSH:
* "the change occurs after all output written to fd
* has been transmitted, and all input that has been
* received but not read will be discarded before
* the change is made.
*/
tcsetattr(STDERR_FILENO, TCSAFLUSH, &new);
tcsetattr(STDERR_FILENO, TCSANOW, &new);
/* save_cursor_pos 7
* scroll_whole_screen [r
+1 -1
View File
@@ -106,7 +106,7 @@ int showkey_main(int argc UNUSED_PARAM, char **argv)
xioctl(STDIN_FILENO, KDSKBMODE, (void *)(ptrdiff_t)((option_mask32 & OPT_k) ? K_MEDIUMRAW : K_RAW));
// we should exit on any signal; signals should interrupt read
bb_signals_norestart(BB_FATAL_SIGS, record_signo);
bb_signals_recursive_norestart(BB_FATAL_SIGS, record_signo);
// inform user that program ends after time of inactivity
printf(press_keys, "10s after last keypress");
+4 -15
View File
@@ -5,6 +5,10 @@
menu "Coreutils"
INSERT
comment "Common options"
config FEATURE_VERBOSE
bool "Support verbose options (usually -v) for various applets"
default y
@@ -13,19 +17,6 @@ config FEATURE_VERBOSE
Also enables long option (--verbose) if it exists.
Without this option, -v is accepted but ignored.
comment "Common options for date and touch"
config FEATURE_TIMEZONE
bool "Allow timezone in dates"
default y
depends on DESKTOP
help
Permit the use of timezones when parsing user-provided data
strings, e.g. '1996-04-09 12:45:00 -0500'.
This requires support for the '%z' extension to strptime() which
may not be available in all implementations.
comment "Common options for cp and mv"
depends on CP || MV
@@ -46,6 +37,4 @@ config FEATURE_HUMAN_READABLE
help
Allow df, du, and ls to have human readable output.
INSERT
endmenu
+24 -38
View File
@@ -29,11 +29,9 @@
/* http://www.opengroup.org/onlinepubs/007904975/utilities/basename.html */
//usage:#define basename_trivial_usage
//usage: "FILE [SUFFIX] | -a FILE... | -s SUFFIX FILE..."
//usage: "FILE [SUFFIX]"
//usage:#define basename_full_usage "\n\n"
//usage: "Strip directory path and SUFFIX from FILE\n"
//usage: "\n -a All arguments are FILEs"
//usage: "\n -s SUFFIX Remove SUFFIX (implies -a)"
//usage: "Strip directory path and .SUFFIX from FILE"
//usage:
//usage:#define basename_example_usage
//usage: "$ basename /usr/local/bin/foo\n"
@@ -50,43 +48,31 @@
int basename_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
int basename_main(int argc UNUSED_PARAM, char **argv)
{
unsigned opts;
const char *suffix = NULL;
size_t m, n;
char *s;
/* '+': stop at first non-option */
opts = getopt32(argv, "^+" "as:"
"\0" "-1" /* At least one argument */
, &suffix
);
argv += optind;
if (argv[1] && strcmp(argv[1], "--") == 0) {
argv++;
}
if (!argv[1])
bb_show_usage();
do {
char *s;
size_t m;
/* It should strip slash: /abc/def/ -> def */
s = bb_get_last_path_component_strip(*++argv);
/* It should strip slash: /abc/def/ -> def */
s = bb_get_last_path_component_strip(*argv++);
m = strlen(s);
if (!opts) {
if (*argv) {
suffix = *argv;
if (argv[1])
bb_show_usage();
}
m = strlen(s);
if (*++argv) {
if (argv[1])
bb_show_usage();
n = strlen(*argv);
if ((m > n) && (strcmp(s+m-n, *argv) == 0)) {
m -= n;
/*s[m] = '\0'; - redundant */
}
if (suffix) {
size_t n = strlen(suffix);
if ((m > n) && (strcmp(s + m - n, suffix) == 0)) {
m -= n;
/*s[m] = '\0'; - redundant */
}
}
/* puts(s) will do, but we can do without stdio this way: */
s[m++] = '\n';
/* NB: != is correct here: */
if (full_write(STDOUT_FILENO, s, m) != (ssize_t)m)
return EXIT_FAILURE;
} while (opts && *argv);
}
return EXIT_SUCCESS;
/* puts(s) will do, but we can do without stdio this way: */
s[m++] = '\n';
/* NB: != is correct here: */
return full_write(STDOUT_FILENO, s, m) != (ssize_t)m;
}
+2 -2
View File
@@ -152,7 +152,7 @@ static int catv(unsigned opts, char **argv)
eol_seen = (c == eol_char);
#endif
visible(c, buf, opts);
fputs_stdout(buf);
fputs(buf, stdout);
}
}
if (ENABLE_FEATURE_CLEAN_UP && fd)
@@ -201,7 +201,7 @@ int cat_main(int argc UNUSED_PARAM, char **argv)
ns.start = 1;
ns.inc = 1;
ns.sep = "\t";
ns.empty_str = NULL;
ns.empty_str = "\n";
ns.all = !(opts & CAT_OPT_b); /* -n without -b */
ns.nonempty = (opts & CAT_OPT_b); /* -b (with or without -n) */
exitcode = EXIT_SUCCESS;
+2 -6
View File
@@ -23,17 +23,13 @@
//usage:#define chgrp_trivial_usage
//usage: "[-Rh"IF_DESKTOP("LHPcvf")"]... GROUP FILE..."
//usage:#define chgrp_full_usage "\n\n"
//usage: "Change the group membership of FILEs to GROUP"
//usage: "\n"
//usage: "Change the group membership of each FILE to GROUP\n"
//usage: "\n -R Recurse"
//usage: "\n -h Affect symlinks instead of symlink targets"
//usage: IF_DESKTOP(
//usage: "\n -L Traverse all symlinks to directories"
//usage: "\n -H Traverse symlinks on command line only"
//usage: "\n -P Don't traverse symlinks (default)"
//usage: )
//next 4 options are the same for chmod/chown/chgrp:
//usage: "\n -R Recurse"
//usage: IF_DESKTOP(
//usage: "\n -c List changed files"
//usage: "\n -v Verbose"
//usage: "\n -f Hide errors"
+5 -8
View File
@@ -26,13 +26,12 @@
//usage:#define chmod_trivial_usage
//usage: "[-R"IF_DESKTOP("cvf")"] MODE[,MODE]... FILE..."
//usage:#define chmod_full_usage "\n\n"
//usage: "MODE is octal number (bit pattern sstrwxrwxrwx) or [ugoa]{+|-|=}[rwxXst]"
//usage: "\n"
//next 4 options are the same for chmod/chown/chgrp:
//usage: "Each MODE is one or more of the letters ugoa, one of the\n"
//usage: "symbols +-= and one or more of the letters rwxst\n"
//usage: "\n -R Recurse"
//usage: IF_DESKTOP(
//usage: "\n -c List changed files"
//usage: "\n -v Verbose"
//usage: "\n -v List all files"
//usage: "\n -f Hide errors"
//usage: )
//usage:
@@ -88,12 +87,10 @@ static int FAST_FUNC fileAction(struct recursive_state *state,
if (chmod(fileName, newmode) == 0) {
if (OPT_VERBOSE
|| (OPT_CHANGED
&& (statbuf->st_mode & 07777) != (newmode & 07777))
|| (OPT_CHANGED && statbuf->st_mode != newmode)
) {
char modestr[12];
printf("mode of '%s' changed to %04o (%s)\n", fileName,
newmode & 07777, bb_mode_string(modestr, newmode)+1);
newmode & 07777, bb_mode_string(newmode)+1);
}
return TRUE;
}
+3 -7
View File
@@ -28,19 +28,15 @@
//usage:#define chown_trivial_usage
//usage: "[-Rh"IF_DESKTOP("LHPcvf")"]... USER[:[GRP]] FILE..."
//usage:#define chown_full_usage "\n\n"
//usage: "Change the owner and/or group of FILEs to USER and/or GRP"
//usage: "\n"
//usage: "Change the owner and/or group of each FILE to USER and/or GRP\n"
//usage: "\n -R Recurse"
//usage: "\n -h Affect symlinks instead of symlink targets"
//usage: IF_DESKTOP(
//usage: "\n -L Traverse all symlinks to directories"
//usage: "\n -H Traverse symlinks on command line only"
//usage: "\n -P Don't traverse symlinks (default)"
//usage: )
//next 4 options are the same for chmod/chown/chgrp:
//usage: "\n -R Recurse"
//usage: IF_DESKTOP(
//usage: "\n -c List changed files"
//usage: "\n -v Verbose"
//usage: "\n -v List all files"
//usage: "\n -f Hide errors"
//usage: )
//usage:
+16 -38
View File
@@ -9,40 +9,32 @@
//config:config CKSUM
//config: bool "cksum (4.1 kb)"
//config: default y
//config:
//config:config CRC32
//config: bool "crc32 (4.1 kb)"
//config: default y
//config: help
//config: cksum is used to calculate the CRC32 checksum of a file.
// APPLET_NOEXEC:name main location suid_type help
//applet:IF_CKSUM(APPLET_NOEXEC(cksum, cksum, BB_DIR_USR_BIN, BB_SUID_DROP, cksum))
//applet:IF_CRC32(APPLET_NOEXEC(crc32, cksum, BB_DIR_USR_BIN, BB_SUID_DROP, cksum))
/* bb_common_bufsiz1 usage here is safe wrt NOEXEC: not expecting it to be zeroed. */
//kbuild:lib-$(CONFIG_CKSUM) += cksum.o
//kbuild:lib-$(CONFIG_CRC32) += cksum.o
//usage:#define cksum_trivial_usage
//usage: "FILE..."
//usage:#define cksum_full_usage "\n\n"
//usage: "Calculate CRC32 checksum of FILEs"
//usage: "Calculate the CRC32 checksums of FILEs"
#include "libbb.h"
#include "common_bufsiz.h"
/* This is a NOEXEC applet. Be very careful! */
#define IS_CKSUM (ENABLE_CKSUM && (!ENABLE_CRC32 || applet_name[1] == 'k'))
#define IS_CRC32 (ENABLE_CRC32 && (!ENABLE_CKSUM || applet_name[1] == 'r'))
int cksum_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
int cksum_main(int argc UNUSED_PARAM, char **argv)
{
uint32_t *crc32_table = crc32_filltable(NULL, IS_CKSUM);
uint32_t *crc32_table = crc32_filltable(NULL, 1);
int exit_code = EXIT_SUCCESS;
#if ENABLE_DESKTOP
getopt32(argv, ""); /* cksum coreutils 6.9 compat */
getopt32(argv, ""); /* coreutils 6.9 compat */
argv += optind;
#else
argv++;
@@ -51,55 +43,41 @@ int cksum_main(int argc UNUSED_PARAM, char **argv)
setup_common_bufsiz();
do {
uint32_t crc;
IF_CKSUM(off_t filesize;)
const char *fname = *argv ? *argv : bb_msg_standard_input;
int fd = open_or_warn_stdin(fname);
off_t filesize;
int fd = open_or_warn_stdin(*argv ? *argv : bb_msg_standard_input);
if (fd < 0) {
exit_code = EXIT_FAILURE;
continue;
}
crc = IS_CKSUM ? 0 : 0xffffffff;
IF_CKSUM(filesize = 0;)
crc = 0;
filesize = 0;
#define read_buf bb_common_bufsiz1
for (;;) {
uoff_t t;
int bytes_read = safe_read(fd, read_buf, COMMON_BUFSIZE);
if (bytes_read < 0)
bb_simple_perror_msg_and_die(fname);
if (bytes_read > 0) {
IF_CKSUM(filesize += bytes_read;)
filesize += bytes_read;
} else {
IF_CKSUM(uoff_t t;)
/* Checksum filesize bytes, LSB first, and exit */
close(fd);
if (IS_CRC32)
break;
#if ENABLE_CKSUM
fd = -1; /* break flag */
/* Checksum filesize bytes, LSB first */
t = filesize;
/*bytes_read = 0; - already is */
bytes_read = 0;
while (t != 0) {
read_buf[bytes_read++] = (uint8_t)t;
t >>= 8;
}
#endif
}
crc = (IS_CKSUM ? crc32_block_endian1 : crc32_block_endian0)(crc, read_buf, bytes_read, crc32_table);
if (ENABLE_CKSUM && fd < 0)
crc = crc32_block_endian1(crc, read_buf, bytes_read, crc32_table);
if (fd < 0)
break;
}
crc = ~crc;
#if ENABLE_CKSUM
if (IS_CKSUM)
printf((*argv ? "%u %"OFF_FMT"u %s\n" : "%u %"OFF_FMT"u\n"),
printf((*argv ? "%u %"OFF_FMT"u %s\n" : "%u %"OFF_FMT"u\n"),
(unsigned)crc, filesize, *argv);
else
#endif
printf((*argv ? "%08x %s\n" : "%08x\n"),
(unsigned)crc, *argv);
} while (*argv && *++argv);
fflush_stdout_and_exit(exit_code);
+98 -111
View File
@@ -37,57 +37,10 @@
/* http://www.opengroup.org/onlinepubs/007904975/utilities/cp.html */
// Options of cp from GNU coreutils 6.10:
// -a, --archive
// -f, --force
// -i, --interactive
// -l, --link
// -L, --dereference
// -P, --no-dereference
// -R, -r, --recursive
// -s, --symbolic-link
// -v, --verbose
// -H follow command-line symbolic links in SOURCE
// -d same as --no-dereference --preserve=links
// -p same as --preserve=mode,ownership,timestamps
// -c same as --preserve=context
// -u, --update
// copy only when the SOURCE file is newer than the destination
// file or when the destination file is missing
// --remove-destination
// remove each existing destination file before attempting to open
// --parents
// use full source file name under DIRECTORY
// -T, --no-target-directory
// treat DEST as a normal file
// NOT SUPPORTED IN BBOX:
// --backup[=CONTROL]
// make a backup of each existing destination file
// -b like --backup but does not accept an argument
// --copy-contents
// copy contents of special files when recursive
// --preserve[=ATTR_LIST]
// preserve attributes (default: mode,ownership,timestamps),
// if possible additional attributes: security context,links,all
// --no-preserve=ATTR_LIST
// --sparse=WHEN
// control creation of sparse files
// --strip-trailing-slashes
// remove any trailing slashes from each SOURCE argument
// -S, --suffix=SUFFIX
// override the usual backup suffix
// -t, --target-directory=DIRECTORY
// copy all SOURCE arguments into DIRECTORY
// -x, --one-file-system
// stay on this file system
// -Z, --context=CONTEXT
// (SELinux) set SELinux security context of copy to CONTEXT
//usage:#define cp_trivial_usage
//usage: "[-arPLHpfinlsTu] SOURCE DEST\n"
//usage: "or: cp [-arPLHpfinlsu] SOURCE... { -t DIRECTORY | DIRECTORY }"
//usage: "[-arPLHpfilsTu] SOURCE... DEST"
//usage:#define cp_full_usage "\n\n"
//usage: "Copy SOURCEs to DEST\n"
//usage: "Copy SOURCE(s) to DEST\n"
//usage: "\n -a Same as -dpR"
//usage: IF_SELINUX(
//usage: "\n -c Preserve security context"
@@ -99,10 +52,8 @@
//usage: "\n -p Preserve file attributes if possible"
//usage: "\n -f Overwrite"
//usage: "\n -i Prompt before overwrite"
//usage: "\n -n Don't overwrite"
//usage: "\n -l,-s Create (sym)links"
//usage: "\n -T Refuse to copy if DEST is a directory"
//usage: "\n -t DIR Copy all SOURCEs into DIR"
//usage: "\n -T Treat DEST as a normal file"
//usage: "\n -u Copy only newer files"
#include "libbb.h"
@@ -121,46 +72,44 @@ int cp_main(int argc, char **argv)
int d_flags;
int flags;
int status;
#if ENABLE_FEATURE_CP_LONG_OPTIONS
enum {
/*OPT_rmdest = FILEUTILS_RMDEST = 1 << FILEUTILS_CP_OPTBITS */
OPT_parents = 1 << (FILEUTILS_CP_OPTBITS+1),
OPT_reflink = 1 << (FILEUTILS_CP_OPTBITS+2),
FILEUTILS_CP_OPTNUM = sizeof(FILEUTILS_CP_OPTSTR)-1,
#if ENABLE_FEATURE_CP_LONG_OPTIONS
/*OPT_rmdest = FILEUTILS_RMDEST = 1 << FILEUTILS_CP_OPTNUM */
OPT_parents = 1 << (FILEUTILS_CP_OPTNUM+1),
OPT_reflink = 1 << (FILEUTILS_CP_OPTNUM+2),
#endif
};
#if ENABLE_FEATURE_CP_LONG_OPTIONS
# if ENABLE_FEATURE_CP_REFLINK
char *reflink = NULL;
# endif
flags = getopt32long(argv, "^"
FILEUTILS_CP_OPTSTR
"\0"
// Need at least one argument. (Usually two+, but -t DIR can have only one)
// Need at least two arguments
// Soft- and hardlinking doesn't mix
// -P and -d are the same (-P is POSIX, -d is GNU)
// -r and -R are the same
// -R (and therefore -r) turns on -d (coreutils does this)
// -a = -pdR
// -i overrides -n and vice versa (last wins)
"-1:l--s:s--l:Pd:rRd:Rd:apdR:i-n:n-i",
"-2:l--s:s--l:Pd:rRd:Rd:apdR",
"archive\0" No_argument "a"
"force\0" No_argument "f"
"interactive\0" No_argument "i"
"no-clobber\0" No_argument "n"
"link\0" No_argument "l"
"dereference\0" No_argument "L"
"no-dereference\0" No_argument "P"
"recursive\0" No_argument "R"
"symbolic-link\0" No_argument "s"
"no-target-directory\0" No_argument "T"
"target-directory\0" Required_argument "t"
"verbose\0" No_argument "v"
"update\0" No_argument "u"
"remove-destination\0" No_argument "\xff"
"parents\0" No_argument "\xfe"
# if ENABLE_FEATURE_CP_REFLINK
"reflink\0" Optional_argument "\xfd"
# endif
, &last
# if ENABLE_FEATURE_CP_REFLINK
, &reflink
# endif
);
@@ -179,10 +128,55 @@ int cp_main(int argc, char **argv)
flags = getopt32(argv, "^"
FILEUTILS_CP_OPTSTR
"\0"
"-1:l--s:s--l:Pd:rRd:Rd:apdR"
, &last
"-2:l--s:s--l:Pd:rRd:Rd:apdR"
);
#endif
/* Options of cp from GNU coreutils 6.10:
* -a, --archive
* -f, --force
* -i, --interactive
* -l, --link
* -L, --dereference
* -P, --no-dereference
* -R, -r, --recursive
* -s, --symbolic-link
* -v, --verbose
* -H follow command-line symbolic links in SOURCE
* -d same as --no-dereference --preserve=links
* -p same as --preserve=mode,ownership,timestamps
* -c same as --preserve=context
* -u, --update
* copy only when the SOURCE file is newer than the destination
* file or when the destination file is missing
* --remove-destination
* remove each existing destination file before attempting to open
* --parents
* use full source file name under DIRECTORY
* -T, --no-target-directory
* treat DEST as a normal file
* NOT SUPPORTED IN BBOX:
* --backup[=CONTROL]
* make a backup of each existing destination file
* -b like --backup but does not accept an argument
* --copy-contents
* copy contents of special files when recursive
* --preserve[=ATTR_LIST]
* preserve attributes (default: mode,ownership,timestamps),
* if possible additional attributes: security context,links,all
* --no-preserve=ATTR_LIST
* --sparse=WHEN
* control creation of sparse files
* --strip-trailing-slashes
* remove any trailing slashes from each SOURCE argument
* -S, --suffix=SUFFIX
* override the usual backup suffix
* -t, --target-directory=DIRECTORY
* copy all SOURCE arguments into DIRECTORY
* -x, --one-file-system
* stay on this file system
* -Z, --context=CONTEXT
* (SELinux) set SELinux security context of copy to CONTEXT
*/
argc -= optind;
argv += optind;
/* Reverse this bit. If there is -d, bit is not set: */
@@ -201,56 +195,49 @@ int cp_main(int argc, char **argv)
#endif
status = EXIT_SUCCESS;
if (!(flags & FILEUTILS_TARGET_DIR)) {
last = argv[argc - 1];
if (argc < 2)
bb_show_usage();
if (argc != 2) {
if (flags & FILEUTILS_NO_TARGET_DIR)
bb_show_usage();
/* "cp A B C... DIR" - target must be dir */
} else /* argc == 2 */ {
/* "cp A B" - only case where target can be not a dir */
s_flags = cp_mv_stat2(*argv, &source_stat,
(flags & FILEUTILS_DEREFERENCE) ? stat : lstat);
if (s_flags < 0) /* error other than ENOENT */
return EXIT_FAILURE;
d_flags = cp_mv_stat(last, &dest_stat);
if (d_flags < 0) /* error other than ENOENT */
return EXIT_FAILURE;
last = argv[argc - 1];
/* If there are only two arguments and... */
if (argc == 2) {
s_flags = cp_mv_stat2(*argv, &source_stat,
(flags & FILEUTILS_DEREFERENCE) ? stat : lstat);
if (s_flags < 0)
return EXIT_FAILURE;
d_flags = cp_mv_stat(last, &dest_stat);
if (d_flags < 0)
return EXIT_FAILURE;
if (flags & FILEUTILS_NO_TARGET_DIR) { /* -T */
if (!(s_flags & 2) && (d_flags & 2))
/* cp -T NOTDIR DIR */
bb_error_msg_and_die("'%s' is a directory", last);
}
if (flags & FILEUTILS_NO_TARGET_DIR) { /* -T */
if (!(s_flags & 2) && (d_flags & 2))
/* cp -T NOTDIR DIR */
bb_error_msg_and_die("'%s' is a directory", last);
}
#if ENABLE_FEATURE_CP_LONG_OPTIONS
//bb_error_msg("flags:%x FILEUTILS_RMDEST:%x OPT_parents:%x",
// flags, FILEUTILS_RMDEST, OPT_parents);
if (flags & OPT_parents) {
if (!(d_flags & 2)) {
bb_simple_error_msg_and_die("with --parents, the destination must be a directory");
}
}
if (flags & FILEUTILS_RMDEST) {
flags |= FILEUTILS_FORCE;
}
#endif
/* ...if neither is a directory... */
if (!((s_flags | d_flags) & 2)
/* ...or: recursing, the 1st is a directory, and the 2nd doesn't exist... */
|| ((flags & FILEUTILS_RECUR) && (s_flags & 2) && !d_flags)
|| (flags & FILEUTILS_NO_TARGET_DIR)
) {
/* Do a simple copy */
dest = last;
goto DO_COPY; /* NB: argc==2 -> *++argv==last */
//bb_error_msg("flags:%x FILEUTILS_RMDEST:%x OPT_parents:%x",
// flags, FILEUTILS_RMDEST, OPT_parents);
if (flags & OPT_parents) {
if (!(d_flags & 2)) {
bb_simple_error_msg_and_die("with --parents, the destination must be a directory");
}
}
if (flags & FILEUTILS_RMDEST) {
flags |= FILEUTILS_FORCE;
}
#endif
/* ...if neither is a directory... */
if (!((s_flags | d_flags) & 2)
/* ...or: recursing, the 1st is a directory, and the 2nd doesn't exist... */
|| ((flags & FILEUTILS_RECUR) && (s_flags & 2) && !d_flags)
|| (flags & FILEUTILS_NO_TARGET_DIR)
) {
/* Do a simple copy */
dest = last;
goto DO_COPY; /* NB: argc==2 -> *++argv==last */
}
} else if (flags & FILEUTILS_NO_TARGET_DIR) {
bb_simple_error_msg_and_die("too many arguments");
}
/* else: last is DIR from "-t DIR" */
while (1) {
#if ENABLE_FEATURE_CP_LONG_OPTIONS
@@ -272,7 +259,7 @@ int cp_main(int argc, char **argv)
if (copy_file(*argv, dest, flags) < 0) {
status = EXIT_FAILURE;
}
if (!*++argv || *argv == last) {
if (*++argv == last) {
/* possibly leaking dest... */
break;
}
+96 -110
View File
@@ -14,13 +14,6 @@
//config: help
//config: cut is used to print selected parts of lines from
//config: each file to stdout.
//config:
//config:config FEATURE_CUT_REGEX
//config: bool "cut -F"
//config: default y
//config: depends on CUT
//config: help
//config: Allow regex based delimiters.
//applet:IF_CUT(APPLET_NOEXEC(cut, cut, BB_DIR_USR_BIN, BB_SUID_DROP, cut))
@@ -29,19 +22,13 @@
//usage:#define cut_trivial_usage
//usage: "[OPTIONS] [FILE]..."
//usage:#define cut_full_usage "\n\n"
//usage: "Print selected fields from FILEs to stdout\n"
//usage: "Print selected fields from each input FILE to stdout\n"
//usage: "\n -b LIST Output only bytes from LIST"
//usage: "\n -c LIST Output only characters from LIST"
//usage: "\n -d SEP Field delimiter for input (default -f TAB, -F run of whitespace)"
//usage: "\n -O SEP Field delimeter for output (default = -d for -f, one space for -F)"
//usage: "\n -D Don't sort/collate sections or match -fF lines without delimeter"
//usage: "\n -f LIST Print only these fields (-d is single char)"
//usage: IF_FEATURE_CUT_REGEX(
//usage: "\n -F LIST Print only these fields (-d is regex)"
//usage: )
//usage: "\n -s Output only lines containing delimiter"
//usage: "\n -d CHAR Use CHAR instead of tab as the field delimiter"
//usage: "\n -s Output only the lines containing delimiter"
//usage: "\n -f N Print only these fields"
//usage: "\n -n Ignored"
//(manpage:-n with -b: don't split multibyte characters)
//usage:
//usage:#define cut_example_usage
//usage: "$ echo \"Hello world\" | cut -f 1 -d ' '\n"
@@ -51,49 +38,38 @@
#include "libbb.h"
#if ENABLE_FEATURE_CUT_REGEX
#include "xregex.h"
#else
#define regex_t int
typedef struct { int rm_eo, rm_so; } regmatch_t;
#define xregcomp(x, ...) *(x) = 0
#define regexec(...) 0
#endif
/* This is a NOEXEC applet. Be very careful! */
/* option vars */
#define OPT_STR "b:c:f:d:O:sD"IF_FEATURE_CUT_REGEX("F:")"n"
#define OPT_STR "b:c:f:d:sn"
#define CUT_OPT_BYTE_FLGS (1 << 0)
#define CUT_OPT_CHAR_FLGS (1 << 1)
#define CUT_OPT_FIELDS_FLGS (1 << 2)
#define CUT_OPT_DELIM_FLGS (1 << 3)
#define CUT_OPT_ODELIM_FLGS (1 << 4)
#define CUT_OPT_SUPPRESS_FLGS (1 << 5)
#define CUT_OPT_NOSORT_FLGS (1 << 6)
#define CUT_OPT_REGEX_FLGS ((1 << 7) * ENABLE_FEATURE_CUT_REGEX)
#define CUT_OPT_SUPPRESS_FLGS (1 << 4)
struct cut_list {
int startpos;
int endpos;
};
enum {
BOL = 0,
EOL = INT_MAX,
NON_RANGE = -1
};
static int cmpfunc(const void *a, const void *b)
{
return (((struct cut_list *) a)->startpos -
((struct cut_list *) b)->startpos);
}
static void cut_file(FILE *file, const char *delim, const char *odelim,
const struct cut_list *cut_lists, unsigned nlists)
static void cut_file(FILE *file, char delim, const struct cut_list *cut_lists, unsigned nlists)
{
char *line;
unsigned linenum = 0; /* keep these zero-based to be consistent */
regex_t reg;
int spos, shoe = option_mask32 & CUT_OPT_REGEX_FLGS;
if (shoe) xregcomp(&reg, delim, REG_EXTENDED);
/* go through every line in the file */
while ((line = xmalloc_fgetline(file)) != NULL) {
@@ -103,22 +79,29 @@ static void cut_file(FILE *file, const char *delim, const char *odelim,
char *printed = xzalloc(linelen + 1);
char *orig_line = line;
unsigned cl_pos = 0;
int spos;
/* cut based on chars/bytes XXX: only works when sizeof(char) == byte */
if (option_mask32 & (CUT_OPT_CHAR_FLGS | CUT_OPT_BYTE_FLGS)) {
/* print the chars specified in each cut list */
for (; cl_pos < nlists; cl_pos++) {
for (spos = cut_lists[cl_pos].startpos; spos < linelen;) {
spos = cut_lists[cl_pos].startpos;
while (spos < linelen) {
if (!printed[spos]) {
printed[spos] = 'X';
putchar(line[spos]);
}
if (++spos > cut_lists[cl_pos].endpos) {
spos++;
if (spos > cut_lists[cl_pos].endpos
/* NON_RANGE is -1, so if below is true,
* the above was true too (spos is >= 0) */
/* || cut_lists[cl_pos].endpos == NON_RANGE */
) {
break;
}
}
}
} else if (*delim == '\n') { /* cut by lines */
} else if (delim == '\n') { /* cut by lines */
spos = cut_lists[cl_pos].startpos;
/* get out if we have no more lists to process or if the lines
@@ -131,7 +114,9 @@ static void cut_file(FILE *file, const char *delim, const char *odelim,
while (spos < (int)linenum) {
spos++;
/* go to the next list if we're at the end of this one */
if (spos > cut_lists[cl_pos].endpos) {
if (spos > cut_lists[cl_pos].endpos
|| cut_lists[cl_pos].endpos == NON_RANGE
) {
cl_pos++;
/* get out if there's no more lists to process */
if (cl_pos >= nlists)
@@ -149,56 +134,55 @@ static void cut_file(FILE *file, const char *delim, const char *odelim,
puts(line);
goto next_line;
} else { /* cut by fields */
unsigned uu = 0, start = 0, end = 0, out = 0;
int dcount = 0;
int ndelim = -1; /* zero-based / one-based problem */
int nfields_printed = 0;
char *field = NULL;
char delimiter[2];
/* Loop through bytes, finding next delimiter */
for (;;) {
/* End of current range? */
if (end == linelen || dcount > cut_lists[cl_pos].endpos) {
if (++cl_pos >= nlists) break;
if (option_mask32 & CUT_OPT_NOSORT_FLGS)
start = dcount = uu = 0;
end = 0;
}
/* End of current line? */
if (uu == linelen) {
/* If we've seen no delimiters, check -s */
if (!cl_pos && !dcount && !shoe) {
if (option_mask32 & CUT_OPT_SUPPRESS_FLGS)
goto next_line;
} else if (dcount<cut_lists[cl_pos].startpos)
start = linelen;
end = linelen;
} else {
/* Find next delimiter */
if (shoe) {
regmatch_t rr = {-1, -1};
delimiter[0] = delim;
delimiter[1] = 0;
if (!regexec(&reg, line+uu, 1, &rr, REG_NOTBOL|REG_NOTEOL)) {
end = uu + rr.rm_so;
uu += rr.rm_eo;
} else {
uu = linelen;
continue;
}
} else if (line[end = uu++] != *delim)
continue;
/* does this line contain any delimiters? */
if (strchr(line, delim) == NULL) {
if (!(option_mask32 & CUT_OPT_SUPPRESS_FLGS))
puts(line);
goto next_line;
}
/* Got delimiter. Loop if not yet within range. */
if (dcount++ < cut_lists[cl_pos].startpos) {
start = uu;
continue;
/* process each list on this line, for as long as we've got
* a line to process */
for (; cl_pos < nlists && line; cl_pos++) {
spos = cut_lists[cl_pos].startpos;
do {
/* find the field we're looking for */
while (line && ndelim < spos) {
field = strsep(&line, delimiter);
ndelim++;
}
}
if (end != start || !shoe)
printf("%s%.*s", out++ ? odelim : "", end-start, line + start);
start = uu;
if (!dcount)
break;
/* we found it, and it hasn't been printed yet */
if (field && ndelim == spos && !printed[ndelim]) {
/* if this isn't our first time through, we need to
* print the delimiter after the last field that was
* printed */
if (nfields_printed > 0)
putchar(delim);
fputs(field, stdout);
printed[ndelim] = 'X';
nfields_printed++; /* shouldn't overflow.. */
}
spos++;
/* keep going as long as we have a line to work with,
* this is a list, and we're not at the end of that
* list */
} while (spos <= cut_lists[cl_pos].endpos && line
&& cut_lists[cl_pos].endpos != NON_RANGE);
}
}
/* if we printed anything, finish with newline */
/* if we printed anything at all, we need to finish it with a
* newline cuz we were handed a chomped line */
putchar('\n');
next_line:
linenum++;
@@ -213,35 +197,37 @@ int cut_main(int argc UNUSED_PARAM, char **argv)
/* growable array holding a series of lists */
struct cut_list *cut_lists = NULL;
unsigned nlists = 0; /* number of elements in above list */
char delim = '\t'; /* delimiter, default is tab */
char *sopt, *ltok;
const char *delim = NULL;
const char *odelim = NULL;
unsigned opt;
#define ARG "bcf"IF_FEATURE_CUT_REGEX("F")
opt = getopt32(argv, "^"
OPT_STR // = "b:c:f:d:O:sD"IF_FEATURE_CUT_REGEX("F:")"n"
"\0" "b--"ARG":c--"ARG":f--"ARG IF_FEATURE_CUT_REGEX("F--"ARG),
&sopt, &sopt, &sopt, &delim, &odelim IF_FEATURE_CUT_REGEX(, &sopt)
OPT_STR
"\0" "b--bcf:c--bcf:f--bcf",
&sopt, &sopt, &sopt, &ltok
);
if (!delim || !*delim)
delim = (opt & CUT_OPT_REGEX_FLGS) ? "[[:space:]]+" : "\t";
if (!odelim) odelim = (opt & CUT_OPT_REGEX_FLGS) ? " " : delim;
// argc -= optind;
argv += optind;
if (!(opt & (CUT_OPT_BYTE_FLGS | CUT_OPT_CHAR_FLGS | CUT_OPT_FIELDS_FLGS | CUT_OPT_REGEX_FLGS)))
if (!(opt & (CUT_OPT_BYTE_FLGS | CUT_OPT_CHAR_FLGS | CUT_OPT_FIELDS_FLGS)))
bb_simple_error_msg_and_die("expected a list of bytes, characters, or fields");
if (opt & CUT_OPT_DELIM_FLGS) {
if (ltok[0] && ltok[1]) { /* more than 1 char? */
bb_simple_error_msg_and_die("the delimiter must be a single character");
}
delim = ltok[0];
}
/* non-field (char or byte) cutting has some special handling */
if (!(opt & (CUT_OPT_FIELDS_FLGS|CUT_OPT_REGEX_FLGS))) {
if (!(opt & CUT_OPT_FIELDS_FLGS)) {
static const char _op_on_field[] ALIGN1 = " only when operating on fields";
if (opt & CUT_OPT_SUPPRESS_FLGS) {
bb_error_msg_and_die
("suppressing non-delimited lines makes sense%s", _op_on_field);
("suppressing non-delimited lines makes sense%s",
_op_on_field);
}
if (opt & CUT_OPT_DELIM_FLGS) {
if (delim != '\t') {
bb_error_msg_and_die
("a delimiter may be specified%s", _op_on_field);
}
@@ -266,7 +252,7 @@ int cut_main(int argc UNUSED_PARAM, char **argv)
/* get the start pos */
ntok = strsep(&ltok, "-");
if (!ntok[0]) {
s = 0;
s = BOL;
} else {
s = xatoi_positive(ntok);
/* account for the fact that arrays are zero based, while
@@ -277,23 +263,24 @@ int cut_main(int argc UNUSED_PARAM, char **argv)
/* get the end pos */
if (ltok == NULL) {
e = s;
e = NON_RANGE;
} else if (!ltok[0]) {
e = INT_MAX;
e = EOL;
} else {
e = xatoi_positive(ltok);
/* if the user specified and end position of 0,
* that means "til the end of the line" */
if (!*ltok)
e = INT_MAX;
else if (e < s)
bb_error_msg_and_die("%d<%d", e, s);
if (e == 0)
e = EOL;
e--; /* again, arrays are zero based, lines are 1 based */
if (e == s)
e = NON_RANGE;
}
/* add the new list */
cut_lists = xrealloc_vector(cut_lists, 4, nlists);
/* NB: startpos is always >= 0 */
/* NB: startpos is always >= 0,
* while endpos may be = NON_RANGE (-1) */
cut_lists[nlists].startpos = s;
cut_lists[nlists].endpos = e;
nlists++;
@@ -306,8 +293,7 @@ int cut_main(int argc UNUSED_PARAM, char **argv)
/* now that the lists are parsed, we need to sort them to make life
* easier on us when it comes time to print the chars / fields / lines
*/
if (!(opt & CUT_OPT_NOSORT_FLGS))
qsort(cut_lists, nlists, sizeof(cut_lists[0]), cmpfunc);
qsort(cut_lists, nlists, sizeof(cut_lists[0]), cmpfunc);
}
{
@@ -322,7 +308,7 @@ int cut_main(int argc UNUSED_PARAM, char **argv)
retval = EXIT_FAILURE;
continue;
}
cut_file(file, delim, odelim, cut_lists, nlists);
cut_file(file, delim, cut_lists, nlists);
fclose_if_not_stdin(file);
} while (*++argv);
+3 -4
View File
@@ -266,7 +266,6 @@ int date_main(int argc UNUSED_PARAM, char **argv)
/* If date string is given, update tm_time, and maybe set date */
if (date_str != NULL) {
int check_dst = 1;
/* Zero out fields - take her back to midnight! */
tm_time.tm_sec = 0;
tm_time.tm_min = 0;
@@ -277,12 +276,12 @@ int date_main(int argc UNUSED_PARAM, char **argv)
if (strptime(date_str, fmt_str2dt, &tm_time) == NULL)
bb_error_msg_and_die(bb_msg_invalid_date, date_str);
} else {
check_dst = parse_datestr(date_str, &tm_time);
parse_datestr(date_str, &tm_time);
}
/* Correct any day of week and day of year etc. fields */
/* Be sure to recheck dst (but not if date is UTC) */
if (check_dst)
/* Be sure to recheck dst (but not if date is time_t format) */
if (date_str[0] != '@')
tm_time.tm_isdst = -1;
ts.tv_sec = validate_tm_time(date_str, &tm_time);
ts.tv_nsec = 0;
+20 -34
View File
@@ -56,10 +56,10 @@
//kbuild:lib-$(CONFIG_DD) += dd.o
//usage:#define dd_trivial_usage
//usage: "[if=FILE] [of=FILE] [" IF_FEATURE_DD_IBS_OBS("ibs=N obs=N/") "bs=N] [count=N] [skip=N] [seek=N]"
//usage: IF_FEATURE_DD_IBS_OBS("\n"
//usage: "[if=FILE] [of=FILE] [" IF_FEATURE_DD_IBS_OBS("ibs=N obs=N/") "bs=N] [count=N] [skip=N] [seek=N]\n"
//usage: IF_FEATURE_DD_IBS_OBS(
//usage: " [conv=notrunc|noerror|sync|fsync]\n"
//usage: " [iflag=skip_bytes|count_bytes|fullblock|direct] [oflag=seek_bytes|append|direct]"
//usage: " [iflag=skip_bytes|fullblock|direct] [oflag=seek_bytes|append|direct]"
//usage: )
//usage:#define dd_full_usage "\n\n"
//usage: "Copy a file with converting and formatting\n"
@@ -82,7 +82,6 @@
//usage: "\n conv=fsync Physically write data out before finishing"
//usage: "\n conv=swab Swap every pair of bytes"
//usage: "\n iflag=skip_bytes skip=N is in bytes"
//usage: "\n iflag=count_bytes count=N is in bytes"
//usage: "\n oflag=seek_bytes seek=N is in bytes"
//usage: "\n iflag=direct O_DIRECT input"
//usage: "\n oflag=direct O_DIRECT output"
@@ -137,22 +136,21 @@ enum {
FLAG_SWAB = (1 << 4) * ENABLE_FEATURE_DD_IBS_OBS,
/* end of conv flags */
/* start of input flags */
FLAG_IFLAG_SHIFT = 5,
FLAG_SKIP_BYTES = (1 << 5) * ENABLE_FEATURE_DD_IBS_OBS,
FLAG_COUNT_BYTES = (1 << 6) * ENABLE_FEATURE_DD_IBS_OBS,
FLAG_FULLBLOCK = (1 << 7) * ENABLE_FEATURE_DD_IBS_OBS,
FLAG_IDIRECT = (1 << 8) * ENABLE_FEATURE_DD_IBS_OBS,
FLAG_IFLAG_SHIFT = 5,
FLAG_SKIP_BYTES = (1 << 5) * ENABLE_FEATURE_DD_IBS_OBS,
FLAG_FULLBLOCK = (1 << 6) * ENABLE_FEATURE_DD_IBS_OBS,
FLAG_IDIRECT = (1 << 7) * ENABLE_FEATURE_DD_IBS_OBS,
/* end of input flags */
/* start of output flags */
FLAG_OFLAG_SHIFT = 9,
FLAG_SEEK_BYTES = (1 << 9) * ENABLE_FEATURE_DD_IBS_OBS,
FLAG_APPEND = (1 << 10) * ENABLE_FEATURE_DD_IBS_OBS,
FLAG_ODIRECT = (1 << 11) * ENABLE_FEATURE_DD_IBS_OBS,
FLAG_OFLAG_SHIFT = 8,
FLAG_SEEK_BYTES = (1 << 8) * ENABLE_FEATURE_DD_IBS_OBS,
FLAG_APPEND = (1 << 9) * ENABLE_FEATURE_DD_IBS_OBS,
FLAG_ODIRECT = (1 << 10) * ENABLE_FEATURE_DD_IBS_OBS,
/* end of output flags */
FLAG_TWOBUFS = (1 << 12) * ENABLE_FEATURE_DD_IBS_OBS,
FLAG_COUNT = 1 << 13,
FLAG_STATUS_NONE = 1 << 14,
FLAG_STATUS_NOXFER = 1 << 15,
FLAG_TWOBUFS = (1 << 11) * ENABLE_FEATURE_DD_IBS_OBS,
FLAG_COUNT = 1 << 12,
FLAG_STATUS_NONE = 1 << 13,
FLAG_STATUS_NOXFER = 1 << 14,
};
static void dd_output_status(int UNUSED_PARAM cur_signal)
@@ -177,9 +175,8 @@ static void dd_output_status(int UNUSED_PARAM cur_signal)
//So far we react to it (we print the stats),
//status=none only suppresses final, non-USR1 generated status message.
# endif
fprintf(stderr, /*G.total_bytes < 1024
? "%llu bytes copied, " : */ "%llu bytes (%sB) copied, "
, G.total_bytes,
fprintf(stderr, "%llu bytes (%sB) copied, ",
G.total_bytes,
/* show fractional digit, use suffixes */
make_human_readable_str(G.total_bytes, 1, 0)
);
@@ -320,7 +317,7 @@ int dd_main(int argc UNUSED_PARAM, char **argv)
static const char conv_words[] ALIGN1 =
"notrunc\0""sync\0""noerror\0""fsync\0""swab\0";
static const char iflag_words[] ALIGN1 =
"skip_bytes\0""count_bytes\0""fullblock\0""direct\0";
"skip_bytes\0""fullblock\0""direct\0";
static const char oflag_words[] ALIGN1 =
"seek_bytes\0append\0""direct\0";
#endif
@@ -362,7 +359,6 @@ int dd_main(int argc UNUSED_PARAM, char **argv)
/* Partially implemented: */
//swab swap every pair of input bytes: will abort on non-even reads
OP_iflag_skip_bytes,
OP_iflag_count_bytes,
OP_iflag_fullblock,
OP_iflag_direct,
OP_oflag_seek_bytes,
@@ -555,17 +551,8 @@ int dd_main(int argc UNUSED_PARAM, char **argv)
goto die_outfile;
}
while (1) {
ssize_t n = ibs;
if (G.flags & FLAG_COUNT) {
if (count == 0)
break;
if ((G.flags & FLAG_COUNT_BYTES) && count < ibs)
n = count;
}
n = dd_read(ibuf, n);
while (!(G.flags & FLAG_COUNT) || (G.in_full + G.in_part != count)) {
ssize_t n = dd_read(ibuf, ibs);
if (n == 0)
break;
if (n < 0) {
@@ -600,7 +587,6 @@ int dd_main(int argc UNUSED_PARAM, char **argv)
p16++;
}
}
count -= (G.flags & FLAG_COUNT_BYTES) ? n : 1;
if ((size_t)n == ibs)
G.in_full++;
else {
+21 -52
View File
@@ -32,26 +32,6 @@
//config: -a Show all filesystems
//config: -i Inodes
//config: -B <SIZE> Blocksize
//config:
//config:config FEATURE_SKIP_ROOTFS
//config: bool "Skip rootfs in mount table"
//config: default y
//config: depends on DF
//config: help
//config: Ignore rootfs entry in mount table.
//config:
//config: In Linux, kernel has a special filesystem, rootfs, which is initially
//config: mounted on /. It contains initramfs data, if kernel is configured
//config: to have one. Usually, another file system is mounted over / early
//config: in boot process, and therefore most tools which manipulate
//config: mount table, such as df, will skip rootfs entry.
//config:
//config: However, some systems do not mount anything on /.
//config: If you need to configure busybox for one of these systems,
//config: you may find it useful to turn this option off to make df show
//config: initramfs statistics.
//config:
//config: Otherwise, choose Y.
//applet:IF_DF(APPLET_NOEXEC(df, df, BB_DIR_BIN, BB_SUID_DROP, df))
@@ -65,7 +45,7 @@
//usage: IF_FEATURE_HUMAN_READABLE("mh")
//usage: "T"
//usage: IF_FEATURE_DF_FANCY("ai] [-B SIZE")
//usage: "] [-t TYPE] [FILESYSTEM]..."
//usage: "] [FILESYSTEM]..."
//usage:#define df_full_usage "\n\n"
//usage: "Print filesystem usage statistics\n"
//usage: "\n -P POSIX output format"
@@ -75,7 +55,6 @@
//usage: "\n -h Human readable (e.g. 1K 243M 2G)"
//usage: )
//usage: "\n -T Print filesystem type"
//usage: "\n -t TYPE Print only mounts of this type"
//usage: IF_FEATURE_DF_FANCY(
//usage: "\n -a Show all filesystems"
//usage: "\n -i Inodes"
@@ -118,41 +97,32 @@ int df_main(int argc UNUSED_PARAM, char **argv)
FILE *mount_table;
struct mntent *mount_entry;
struct statvfs s;
enum {
OPT_KILO = (1 << 0),
OPT_POSIX = (1 << 1),
OPT_FSTYPE = (1 << 2),
OPT_t = (1 << 3),
OPT_ALL = (1 << 4) * ENABLE_FEATURE_DF_FANCY,
OPT_INODE = (1 << 5) * ENABLE_FEATURE_DF_FANCY,
OPT_BSIZE = (1 << 6) * ENABLE_FEATURE_DF_FANCY,
OPT_HUMAN = (1 << (4 + 3*ENABLE_FEATURE_DF_FANCY)) * ENABLE_FEATURE_HUMAN_READABLE,
OPT_HUMANDEC = (1 << (5 + 3*ENABLE_FEATURE_DF_FANCY)) * ENABLE_FEATURE_HUMAN_READABLE,
OPT_MEGA = (1 << (6 + 3*ENABLE_FEATURE_DF_FANCY)) * ENABLE_FEATURE_HUMAN_READABLE,
OPT_KILO = (1 << 0),
OPT_POSIX = (1 << 1),
OPT_FSTYPE = (1 << 2),
OPT_ALL = (1 << 3) * ENABLE_FEATURE_DF_FANCY,
OPT_INODE = (1 << 4) * ENABLE_FEATURE_DF_FANCY,
OPT_BSIZE = (1 << 5) * ENABLE_FEATURE_DF_FANCY,
OPT_HUMAN = (1 << (3 + 3*ENABLE_FEATURE_DF_FANCY)) * ENABLE_FEATURE_HUMAN_READABLE,
OPT_MEGA = (1 << (4 + 3*ENABLE_FEATURE_DF_FANCY)) * ENABLE_FEATURE_HUMAN_READABLE,
};
const char *disp_units_hdr = NULL;
char *chp, *opt_t;
char *chp;
init_unicode();
/* From the manpage of df from coreutils-6.10:
* Disk space is shown in 1K blocks by default, unless the environment
* variable POSIXLY_CORRECT is set, in which case 512-byte blocks are used.
*/
if (getenv("POSIXLY_CORRECT")) /* TODO - a new libbb function? */
df_disp_hr = 512;
opt = getopt32(argv, "^"
"kPTt:"
"kPT"
IF_FEATURE_DF_FANCY("aiB:")
IF_FEATURE_HUMAN_READABLE("hHm")
IF_FEATURE_HUMAN_READABLE("hm")
"\0"
#if ENABLE_FEATURE_HUMAN_READABLE && ENABLE_FEATURE_DF_FANCY
"k-mB:m-Bk:B-km"
#elif ENABLE_FEATURE_HUMAN_READABLE
"k-m:m-k"
#endif
, &opt_t
IF_FEATURE_DF_FANCY(, &chp)
);
if (opt & OPT_MEGA)
@@ -172,11 +142,15 @@ int df_main(int argc UNUSED_PARAM, char **argv)
got_it: ;
}
if (opt & (OPT_HUMAN|OPT_HUMANDEC)) {
/* From the manpage of df from coreutils-6.10:
* Disk space is shown in 1K blocks by default, unless the environment
* variable POSIXLY_CORRECT is set, in which case 512-byte blocks are used.
*/
if (getenv("POSIXLY_CORRECT")) /* TODO - a new libbb function? */
df_disp_hr = 512;
if (opt & OPT_HUMAN) {
df_disp_hr = 0;
//TODO: need to add support in make_human_readable_str() for "decimal human readable"
//if (opt & OPT_HUMANDEC)
// df_disp_hr--;
disp_units_hdr = " Size";
}
if (opt & OPT_INODE)
@@ -240,11 +214,6 @@ int df_main(int argc UNUSED_PARAM, char **argv)
mount_point = mount_entry->mnt_dir;
fs_type = mount_entry->mnt_type;
if (opt & OPT_t) {
if (strcmp(fs_type, opt_t) != 0)
continue;
}
if (statvfs(mount_point, &s) != 0) {
bb_simple_perror_msg(mount_point);
goto set_error;
+13 -22
View File
@@ -40,9 +40,8 @@
//usage:#define du_trivial_usage
//usage: "[-aHLdclsx" IF_FEATURE_HUMAN_READABLE("hm") "k] [FILE]..."
//usage:#define du_full_usage "\n\n"
//usage: "Summarize disk space used for FILEs (or directories)\n"
//usage: "Summarize disk space used for each FILE and/or directory\n"
//usage: "\n -a Show file sizes too"
//usage: "\n -b Apparent size (including holes)"
//usage: "\n -L Follow all symlinks"
//usage: "\n -H Follow symlinks on command line"
//usage: "\n -d N Limit output to directories (and files with -a) of depth < N"
@@ -85,9 +84,8 @@ enum {
OPT_d_maxdepth = (1 << 6),
OPT_l_hardlinks = (1 << 7),
OPT_c_total = (1 << 8),
OPT_b = (1 << 9),
OPT_h_for_humans = (1 << 10),
OPT_m_mbytes = (1 << 11),
OPT_h_for_humans = (1 << 9),
OPT_m_mbytes = (1 << 10),
};
struct globals {
@@ -111,7 +109,7 @@ static void print(unsigned long long size, const char *filename)
/* TODO - May not want to defer error checking here. */
#if ENABLE_FEATURE_HUMAN_READABLE
# if ENABLE_DESKTOP
/* ~30 bytes of code for extra compat:
/* ~30 bytes of code for extra comtat:
* coreutils' du rounds sizes up:
* for example, 1025k file is shown as "2" by du -m.
* We round to nearest if human-readable [too hard to fix],
@@ -126,16 +124,12 @@ static void print(unsigned long long size, const char *filename)
* If G.disp_unit == 0, show one fractional
* and use suffixes
*/
make_human_readable_str(size, (option_mask32 & OPT_b) ? 1 : 512, G.disp_unit),
make_human_readable_str(size, 512, G.disp_unit),
filename);
#else
if (G.disp_k) {
if (!(option_mask32 & OPT_b)) {
size++;
size >>= 1;
} else {
size >>= 10;
}
size++;
size >>= 1;
}
printf("%llu\t%s\n", size, filename);
#endif
@@ -161,7 +155,7 @@ static unsigned long long du(const char *filename)
}
}
sum = ((option_mask32 & OPT_b) ? statbuf.st_size : statbuf.st_blocks);
sum = statbuf.st_blocks;
if (S_ISLNK(statbuf.st_mode)) {
if (G.slink_depth > G.du_depth) { /* -H or -L */
@@ -170,7 +164,7 @@ static unsigned long long du(const char *filename)
G.status = EXIT_FAILURE;
return 0;
}
sum = ((option_mask32 & OPT_b) ? statbuf.st_size : statbuf.st_blocks);
sum = statbuf.st_blocks;
if (G.slink_depth == 1) {
/* Convert -H to -L */
G.slink_depth = INT_MAX;
@@ -247,14 +241,11 @@ int du_main(int argc UNUSED_PARAM, char **argv)
*/
#if ENABLE_FEATURE_HUMAN_READABLE
opt = getopt32(argv, "^"
"aHkLsxd:+lcbhm"
"aHkLsxd:+lchm"
"\0" "h-km:k-hm:m-hk:H-L:L-H:s-d:d-s",
&G.max_print_depth
);
argv += optind;
if (opt & OPT_b) {
G.disp_unit = 1;
}
if (opt & OPT_h_for_humans) {
G.disp_unit = 0;
}
@@ -266,16 +257,16 @@ int du_main(int argc UNUSED_PARAM, char **argv)
}
#else
opt = getopt32(argv, "^"
"aHkLsxd:+lcb"
"aHkLsxd:+lc"
"\0" "H-L:L-H:s-d:d-s",
&G.max_print_depth
);
argv += optind;
# if !ENABLE_FEATURE_DU_DEFAULT_BLOCKSIZE_1K
#if !ENABLE_FEATURE_DU_DEFAULT_BLOCKSIZE_1K
if (opt & OPT_k_kbytes) {
G.disp_k = 1;
}
# endif
#endif
#endif
if (opt & OPT_H_follow_links) {
G.slink_depth = 1;
+9 -9
View File
@@ -43,10 +43,10 @@
//usage:#define echo_trivial_usage
//usage: IF_FEATURE_FANCY_ECHO("[-neE] ") "[ARG]..."
//usage:#define echo_full_usage "\n\n"
//usage: "Print ARGs to stdout"
//usage: "Print the specified ARGs to stdout"
//usage: IF_FEATURE_FANCY_ECHO( "\n"
//usage: "\n -n No trailing newline"
//usage: "\n -e Interpret backslash escapes (\\t=tab etc)"
//usage: "\n -n Suppress trailing newline"
//usage: "\n -e Interpret backslash escapes (i.e., \\t=tab)"
//usage: "\n -E Don't interpret backslash escapes (default)"
//usage: )
//usage:
@@ -87,7 +87,6 @@ int echo_main(int argc UNUSED_PARAM, char **argv)
char *out;
char *buffer;
unsigned buflen;
int err;
#if !ENABLE_FEATURE_FANCY_ECHO
enum {
eflag = 0, /* 0 -- disable escape sequences */
@@ -186,12 +185,13 @@ int echo_main(int argc UNUSED_PARAM, char **argv)
do_write:
/* Careful to error out on partial writes too (think ENOSPC!) */
errno = 0;
err = full_write(STDOUT_FILENO, buffer, out - buffer) != out - buffer;
if (err) {
bb_simple_perror_msg(bb_msg_write_error);
}
/*r =*/ full_write(STDOUT_FILENO, buffer, out - buffer);
free(buffer);
return err;
if (/*WRONG:r < 0*/ errno) {
bb_simple_perror_msg(bb_msg_write_error);
return 1;
}
return 0;
}
/*
+7 -12
View File
@@ -39,15 +39,12 @@
/* http://www.opengroup.org/onlinepubs/007904975/utilities/env.html */
//usage:#define env_trivial_usage
//usage: "[-i0] [-u NAME]... [-] [NAME=VALUE]... [PROG ARGS]"
// The "-" can occur only once (unlike, say, -i): it terminates option processing,
// so if it is followed by another "-" arg (or any option-looking arg),
// that arg will be taken as PROG (or even as NAME=VALUE, example: "-z=QWE").
//usage: "[-iu] [-] [name=value]... [PROG ARGS]"
//usage:#define env_full_usage "\n\n"
//usage: "Print current environment or run PROG after setting up environment\n"
//usage: "\n -, -i Start with empty environment"
//usage: "\n -0 NUL terminated output"
//usage: "\n -u NAME Remove variable from environment"
//usage: "Print the current environment or run PROG after setting up\n"
//usage: "the specified environment\n"
//usage: "\n -, -i Start with an empty environment"
//usage: "\n -u Remove variable from the environment"
#include "libbb.h"
@@ -57,9 +54,8 @@ int env_main(int argc UNUSED_PARAM, char **argv)
unsigned opts;
llist_t *unset_env = NULL;
opts = getopt32long(argv, "+i0u:*",
opts = getopt32long(argv, "+iu:*",
"ignore-environment\0" No_argument "i"
"null\0" No_argument "0"
"unset\0" Required_argument "u"
, &unset_env
);
@@ -94,9 +90,8 @@ int env_main(int argc UNUSED_PARAM, char **argv)
if (environ) { /* clearenv() may set environ == NULL! */
char **ep;
opts = (opts & 2) ? 0 : '\n';
for (ep = environ; *ep; ep++) {
printf("%s%c", *ep, opts);
puts(*ep);
}
}
+1 -1
View File
@@ -123,7 +123,7 @@ static void expand(FILE *file, unsigned tab_size, unsigned opt)
}
ptr++;
}
fputs_stdout(ptr_strbeg);
fputs(ptr_strbeg, stdout);
free(line);
}
}
+2 -2
View File
@@ -45,7 +45,7 @@
//usage:#define expr_trivial_usage
//usage: "EXPRESSION"
//usage:#define expr_full_usage "\n\n"
//usage: "Print the value of EXPRESSION\n"
//usage: "Print the value of EXPRESSION to stdout\n"
//usage: "\n"
//usage: "EXPRESSION may be:\n"
//usage: " ARG1 | ARG2 ARG1 if it is neither null nor 0, otherwise ARG2\n"
@@ -63,7 +63,7 @@
//usage: " ARG1 % ARG2\n"
//usage: " STRING : REGEXP Anchored pattern match of REGEXP in STRING\n"
//usage: " match STRING REGEXP Same as STRING : REGEXP\n"
//usage: " substr STRING POS LEN Substring of STRING, POS counts from 1\n"
//usage: " substr STRING POS LENGTH Substring of STRING, POS counted from 1\n"
//usage: " index STRING CHARS Index in STRING where any CHARS is found, or 0\n"
//usage: " length STRING Length of STRING\n"
//usage: " quote TOKEN Interpret TOKEN as a string, even if\n"
+1 -1
View File
@@ -23,7 +23,7 @@
//usage:#define fold_trivial_usage
//usage: "[-bs] [-w WIDTH] [FILE]..."
//usage:#define fold_full_usage "\n\n"
//usage: "Wrap input lines in FILEs (or stdin), writing to stdout\n"
//usage: "Wrap input lines in each FILE (or stdin), writing to stdout\n"
//usage: "\n -b Count bytes rather than columns"
//usage: "\n -s Break at spaces"
//usage: "\n -w Use WIDTH columns instead of 80"
+7 -8
View File
@@ -29,18 +29,17 @@
//usage:#define head_trivial_usage
//usage: "[OPTIONS] [FILE]..."
//usage:#define head_full_usage "\n\n"
//usage: "Print first 10 lines of FILEs (or stdin).\n"
//usage: "Print first 10 lines of each FILE (or stdin) to stdout.\n"
//usage: "With more than one FILE, precede each with a filename header.\n"
//usage: "\n -n N[bkm] Print first N lines"
//usage: IF_FEATURE_FANCY_HEAD(
//usage: "\n -n -N[bkm] Print all except N last lines"
//usage: "\n -c [-]N[bkm] Print first N bytes"
//usage: )
//usage: "\n (b:*512 k:*1024 m:*1024^2)"
//usage: "\n -n N[kbm] Print first N lines"
//usage: IF_FEATURE_FANCY_HEAD(
//usage: "\n -n -N[kbm] Print all except N last lines"
//usage: "\n -c [-]N[kbm] Print first N bytes"
//usage: "\n -q Never print headers"
//usage: "\n -v Always print headers"
//usage: )
//usage: "\n"
//usage: "\nN may be suffixed by k (x1024), b (x512), or m (x1024^2)."
//usage:
//usage:#define head_example_usage
//usage: "$ head -n 2 /etc/passwd\n"
@@ -118,7 +117,7 @@ print_except_N_last_lines(FILE *fp, unsigned count)
char *c;
if (head == count)
head = 0;
fputs_stdout(circle[head]);
fputs(circle[head], stdout);
c = xmalloc_fgets(fp);
if (!c)
goto ret;
+2 -2
View File
@@ -52,7 +52,7 @@
//usage:#define groups_trivial_usage
//usage: "[USER]"
//usage:#define groups_full_usage "\n\n"
//usage: "Print the groups USER is in"
//usage: "Print the group memberships of USER or for the current process"
//usage:
//usage:#define groups_example_usage
//usage: "$ groups\n"
@@ -258,7 +258,7 @@ int id_main(int argc UNUSED_PARAM, char **argv)
bb_error_msg_and_die("can't get process context%s",
username ? " for a different user" : "");
}
fputs_stdout(scontext);
fputs(scontext, stdout);
}
/* freecon(NULL) seems to be harmless */
if (ENABLE_FEATURE_CLEAN_UP)
+15 -20
View File
@@ -109,11 +109,11 @@
//usage:#define ls_full_usage "\n\n"
//usage: "List directory contents\n"
//usage: "\n -1 One column output"
//usage: "\n -a Include names starting with ."
//usage: "\n -a Include entries which start with ."
//usage: "\n -A Like -a, but exclude . and .."
////usage: "\n -C List by columns" - don't show, this is a default anyway
//usage: "\n -x List by lines"
//usage: "\n -d List directory names, not contents"
//usage: "\n -d List directory entries instead of contents"
//usage: IF_FEATURE_LS_FOLLOWLINKS(
//usage: "\n -L Follow symlinks"
//usage: "\n -H Follow symlinks on command line"
@@ -122,10 +122,10 @@
//usage: "\n -R Recurse"
//usage: )
//usage: IF_FEATURE_LS_FILETYPES(
//usage: "\n -p Append / to directory names"
//usage: "\n -F Append indicator (one of */=@|) to names"
//usage: "\n -p Append / to dir entries"
//usage: "\n -F Append indicator (one of */=@|) to entries"
//usage: )
//usage: "\n -l Long format"
//usage: "\n -l Long listing format"
//usage: "\n -i List inode numbers"
//usage: "\n -n List numeric UIDs and GIDs instead of names"
//usage: "\n -s List allocated blocks"
@@ -134,7 +134,7 @@
//usage: "\n -lu List atime"
//usage: )
//usage: IF_FEATURE_LS_TIMESTAMPS(IF_LONG_OPTS(
//usage: "\n --full-time List full date/time"
//usage: "\n --full-time List full date and time"
//usage: ))
//usage: IF_FEATURE_HUMAN_READABLE(
//usage: "\n -h Human readable sizes (1K 243M 2G)"
@@ -160,7 +160,7 @@
//usage: "\n -w N Format N columns wide"
//usage: )
//usage: IF_FEATURE_LS_COLOR(
//usage: "\n --color[={always,never,auto}]"
//usage: "\n --color[={always,never,auto}] Control coloring"
//usage: )
#include "libbb.h"
@@ -187,7 +187,7 @@
enum {
TERMINAL_WIDTH = 80, /* use 79 if terminal has linefold bug */
TERMINAL_WIDTH = 80, /* use 79 if terminal has linefold bug */
SPLIT_FILE = 0,
SPLIT_DIR = 1,
@@ -298,7 +298,7 @@ struct dnode {
// but there are invisible fields as well
// (such as nanosecond-resolution timespamps)
// and padding, which we also don't want to store.
// We also pre-parse dev_t dn_rdev (in glibc, it's huge).
// We also can pre-parse dev_t dn_rdev (in glibc, it's huge).
// On 32-bit uclibc: dnode size went from 112 to 84 bytes.
//
/* Same names as in struct stat, but with dn_ instead of st_ pfx: */
@@ -453,7 +453,7 @@ static unsigned print_name(const char *name)
name = printable_string2(&uni_stat, name);
if (!(option_mask32 & OPT_Q)) {
fputs_stdout(name);
fputs(name, stdout);
return uni_stat.unicode_width;
}
@@ -503,8 +503,7 @@ static NOINLINE unsigned display_single(const struct dnode *dn)
column += printf("%6"OFF_FMT"u ", (off_t) (dn->dn_blocks >> 1));
if (opt & OPT_l) {
/* long listing: show mode */
char modestr[12];
column += printf("%-10s ", bb_mode_string(modestr, dn->dn_mode));
column += printf("%-10s ", (char *) bb_mode_string(dn->dn_mode));
/* long listing: show number of links */
column += printf("%4lu ", (long) dn->dn_nlink);
/* long listing: show user/group */
@@ -1146,15 +1145,11 @@ int ls_main(int argc UNUSED_PARAM, char **argv)
#if ENABLE_FEATURE_LS_COLOR
/* set G_show_color = 1/0 */
if (ENABLE_FEATURE_LS_COLOR_IS_DEFAULT && !is_TERM_dumb()) {
if (ENABLE_FEATURE_LS_COLOR_IS_DEFAULT && isatty(STDOUT_FILENO)) {
char *p = getenv("LS_COLORS");
/* LS_COLORS is unset, or (not empty && not "none") ? */
if (!p || (p[0] && strcmp(p, "none") != 0)) {
if (isatty(STDOUT_FILENO)) {
/* check isatty() last because it's expensive (syscall) */
G_show_color = 1;
}
}
if (!p || (p[0] && strcmp(p, "none") != 0))
G_show_color = 1;
}
if (opt & OPT_color) {
if (color_opt[0] == 'n')
@@ -1163,7 +1158,7 @@ int ls_main(int argc UNUSED_PARAM, char **argv)
case 3:
case 4:
case 5:
if (!is_TERM_dumb() && isatty(STDOUT_FILENO)) {
if (isatty(STDOUT_FILENO)) {
case 0:
case 1:
case 2:
+1 -3
View File
@@ -36,9 +36,7 @@
//usage: "$ mknod /dev/fd0 b 2 0\n"
//usage: "$ mknod -m 644 /tmp/pipe p\n"
#ifdef __linux__
# include <sys/sysmacros.h> // For makedev
#endif
#include <sys/sysmacros.h> // For makedev
#include "libbb.h"
#include "libcoreutils/coreutils.h"
+1 -15
View File
@@ -72,27 +72,13 @@ int mktemp_main(int argc UNUSED_PARAM, char **argv)
OPT_t = 1 << 2,
OPT_p = 1 << 3,
OPT_u = 1 << 4,
OPT_tmpdir = (1 << 5) * ENABLE_LONG_OPTS,
};
path = getenv("TMPDIR");
if (!path || path[0] == '\0')
path = "/tmp";
#if ENABLE_LONG_OPTS
opts = getopt32long(argv, "^"
"dqtp:u"
"\0"
"?1" /* 1 arg max */,
"directory\0" No_argument "d"
"quiet\0" No_argument "q"
"dry-run\0" No_argument "u"
"tmpdir\0" Optional_argument "\xff"
, &path, &path
);
#else
opts = getopt32(argv, "^" "dqtp:u" "\0" "?1"/*1 arg max*/, &path);
#endif
chp = argv[optind];
if (!chp) {
@@ -109,7 +95,7 @@ int mktemp_main(int argc UNUSED_PARAM, char **argv)
goto error;
}
#endif
if (opts & (OPT_t|OPT_p|OPT_tmpdir))
if (opts & (OPT_t|OPT_p))
chp = concat_path_file(path, chp);
if (opts & OPT_u) {
+26 -52
View File
@@ -23,15 +23,13 @@
//kbuild:lib-$(CONFIG_MV) += mv.o
//usage:#define mv_trivial_usage
//usage: "[-finT] SOURCE DEST\n"
//usage: "or: mv [-fin] SOURCE... { -t DIRECTORY | DIRECTORY }"
//usage: "[-fin] SOURCE DEST\n"
//usage: "or: mv [-fin] SOURCE... DIRECTORY"
//usage:#define mv_full_usage "\n\n"
//usage: "Rename SOURCE to DEST, or move SOURCEs to DIRECTORY\n"
//usage: "Rename SOURCE to DEST, or move SOURCE(s) to DIRECTORY\n"
//usage: "\n -f Don't prompt before overwriting"
//usage: "\n -i Interactive, prompt before overwrite"
//usage: "\n -n Don't overwrite an existing file"
//usage: "\n -T Refuse to move if DEST is a directory"
//usage: "\n -t DIR Move all SOURCEs into DIR"
//usage:
//usage:#define mv_example_usage
//usage: "$ mv /tmp/foo /bin/bar\n"
@@ -42,7 +40,7 @@
int mv_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
int mv_main(int argc, char **argv)
{
struct stat statbuf;
struct stat dest_stat;
const char *last;
const char *dest;
unsigned flags;
@@ -53,66 +51,41 @@ int mv_main(int argc, char **argv)
#define OPT_FORCE (1 << 0)
#define OPT_INTERACTIVE (1 << 1)
#define OPT_NOCLOBBER (1 << 2)
#define OPT_DESTNOTDIR (1 << 3)
#define OPT_DESTDIR (1 << 4)
#define OPT_VERBOSE ((1 << 5) * ENABLE_FEATURE_VERBOSE)
#define OPT_VERBOSE ((1 << 3) * ENABLE_FEATURE_VERBOSE)
/* Need at least two arguments.
* If more than one of -f, -i, -n is specified , only the final one
* takes effect (it unsets previous options).
*/
flags = getopt32long(argv, "^"
"finTt:v"
"finv"
"\0"
/* At least one argument. (Usually two+, but -t DIR can have only one) */
"-1"
/* only the final one of -f, -i, -n takes effect */
":f-in:i-fn:n-fi"
/* -t and -T don't mix */
":t--T:T--t",
"-2:f-in:i-fn:n-fi",
"interactive\0" No_argument "i"
"force\0" No_argument "f"
"no-clobber\0" No_argument "n"
"no-target-directory\0" No_argument "T"
"target-directory\0" Required_argument "t"
IF_FEATURE_VERBOSE(
"verbose\0" No_argument "v",
&last
"verbose\0" No_argument "v"
)
);
argc -= optind;
argv += optind;
last = argv[argc - 1];
if (!(flags & OPT_DESTDIR)) {
last = argv[argc - 1];
if (argc < 2)
bb_show_usage();
if (argc != 2) {
if (flags & OPT_DESTNOTDIR)
bb_show_usage();
/* "mv A B C... DIR" - target must be dir */
} else /* argc == 2 */ {
/* "mv A B" - only case where target can be not a dir */
dest_exists = cp_mv_stat(last, &statbuf);
if (dest_exists < 0) { /* error other than ENOENT */
return EXIT_FAILURE;
}
if (!(dest_exists & 2)) {
/* last is not a directory */
dest = last;
goto DO_MOVE;
}
/* last is a directory */
if (flags & OPT_DESTNOTDIR) {
if (stat(argv[0], &statbuf) == 0 && !S_ISDIR(statbuf.st_mode))
bb_error_msg_and_die("'%s' is a directory", last);
/* "mv -T DIR1 DIR2" is allowed (renames a dir) */
dest = last;
goto DO_MOVE;
}
/* else: fall through into "do { move SRC to DIR/SRC } while" loop */
if (argc == 2) {
dest_exists = cp_mv_stat(last, &dest_stat);
if (dest_exists < 0) {
return EXIT_FAILURE;
}
if (!(dest_exists & 2)) { /* last is not a directory */
dest = last;
goto DO_MOVE;
}
}
/* else: last is DIR from "-t DIR" */
do {
dest = concat_path_file(last, bb_get_last_path_component_strip(*argv));
dest_exists = cp_mv_stat(dest, &statbuf);
dest_exists = cp_mv_stat(dest, &dest_stat);
if (dest_exists < 0) {
goto RET_1;
}
@@ -135,10 +108,11 @@ int mv_main(int argc, char **argv)
}
if (rename(*argv, dest) < 0) {
struct stat source_stat;
int source_exists;
if (errno != EXDEV
|| (source_exists = cp_mv_stat2(*argv, &statbuf, lstat)) < 1
|| (source_exists = cp_mv_stat2(*argv, &source_stat, lstat)) < 1
) {
bb_perror_msg("can't rename '%s'", *argv);
} else {
@@ -185,7 +159,7 @@ int mv_main(int argc, char **argv)
if (dest != last) {
free((void *) dest);
}
} while (*++argv && *argv != last);
} while (*++argv != last);
return status;
}
+1 -1
View File
@@ -68,7 +68,7 @@ int nl_main(int argc UNUSED_PARAM, char **argv)
&ns.width, &ns.sep, &ns.start, &ns.inc, &opt_b);
ns.all = (opt_b[0] == 'a');
ns.nonempty = (opt_b[0] == 't');
ns.empty_str = xasprintf("%*s", ns.width + (int)strlen(ns.sep), "");
ns.empty_str = xasprintf("%*s\n", ns.width + (int)strlen(ns.sep), "");
argv += optind;
if (!*argv)
+2 -2
View File
@@ -14,7 +14,7 @@
//kbuild:lib-$(CONFIG_NPROC) += nproc.o
//usage:#define nproc_trivial_usage
//usage: ""IF_LONG_OPTS("[--all] [--ignore=N]")
//usage: ""IF_LONG_OPTS("--all --ignore=N")
//usage:#define nproc_full_usage "\n\n"
//usage: "Print number of available CPUs"
//usage: IF_LONG_OPTS(
@@ -48,7 +48,7 @@ int nproc_main(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
if (cpuid && isdigit(cpuid[strlen(cpuid) - 1]))
count++;
}
IF_FEATURE_CLEAN_UP(closedir(cpusd);)
closedir(cpusd);
}
} else
#endif
+13 -13
View File
@@ -422,19 +422,19 @@ print_named_ascii(size_t n_bytes, const char *block,
masked_c &= 0x7f;
if (masked_c == 0x7f) {
fputs_stdout(" del");
fputs(" del", stdout);
continue;
}
if (masked_c > ' ') {
buf[3] = masked_c;
fputs_stdout(buf);
fputs(buf, stdout);
continue;
}
/* Why? Because printf(" %3.3s") is much slower... */
buf[6] = charname[masked_c][0];
buf[7] = charname[masked_c][1];
buf[8] = charname[masked_c][2];
fputs_stdout(buf+5);
fputs(buf+5, stdout);
}
}
@@ -451,7 +451,7 @@ print_ascii(size_t n_bytes, const char *block,
if (ISPRINT(c)) {
buf[3] = c;
fputs_stdout(buf);
fputs(buf, stdout);
continue;
}
switch (c) {
@@ -485,7 +485,7 @@ print_ascii(size_t n_bytes, const char *block,
buf[8] = (c & 7) + '0';
s = buf + 5;
}
fputs_stdout(s);
fputs(s, stdout);
}
}
@@ -881,7 +881,7 @@ format_address_label(off_t address, char c)
static void
dump_hexl_mode_trailer(size_t n_bytes, const char *block)
{
fputs_stdout(" >");
fputs(" >", stdout);
while (n_bytes--) {
unsigned c = *(unsigned char *) block++;
c = (ISPRINT(c) ? c : '.');
@@ -1121,13 +1121,13 @@ dump_strings(off_t address, off_t end_offset)
for (i = 0; (c = buf[i]); i++) {
switch (c) {
case '\007': fputs_stdout("\\a"); break;
case '\b': fputs_stdout("\\b"); break;
case '\f': fputs_stdout("\\f"); break;
case '\n': fputs_stdout("\\n"); break;
case '\r': fputs_stdout("\\r"); break;
case '\t': fputs_stdout("\\t"); break;
case '\v': fputs_stdout("\\v"); break;
case '\007': fputs("\\a", stdout); break;
case '\b': fputs("\\b", stdout); break;
case '\f': fputs("\\f", stdout); break;
case '\n': fputs("\\n", stdout); break;
case '\r': fputs("\\r", stdout); break;
case '\t': fputs("\\t", stdout); break;
case '\v': fputs("\\v", stdout); break;
default: putchar(c);
}
}
+2 -2
View File
@@ -53,7 +53,7 @@ static void paste_files(FILE** files, int file_cnt, char* delims, int del_cnt)
--active_files;
continue;
}
fputs_stdout(line);
fputs(line, stdout);
free(line);
delim = '\n';
if (i != file_cnt - 1) {
@@ -79,7 +79,7 @@ static void paste_files_separate(FILE** files, char* delims, int del_cnt)
line = NULL;
while ((next_line = xmalloc_fgetline(files[i])) != NULL) {
if (line) {
fputs_stdout(line);
fputs(line, stdout);
free(line);
delim = delims[del_idx++];
if (del_idx == del_cnt)
+1 -2
View File
@@ -122,7 +122,6 @@ static void FAST_FUNC conv_strtod(const char *arg, void *result)
char *end;
/* Well, this one allows leading whitespace... so what? */
/* What I like much less is that "-" accepted too! :( */
//TODO: needs setlocale(LC_NUMERIC, "C")?
*(double*)result = strtod(arg, &end);
if (end[0]) {
errno = ERANGE;
@@ -313,7 +312,7 @@ static char **print_formatted(char *f, char **argv, int *conv_err)
}
break;
}
while (*f && strchr("-+ #0", *f)) {
if (*f && strchr("-+ #", *f)) {
++f;
++direc_length;
}
+1 -1
View File
@@ -23,7 +23,7 @@
//usage:#define realpath_trivial_usage
//usage: "FILE..."
//usage:#define realpath_full_usage "\n\n"
//usage: "Print absolute pathnames of FILEs"
//usage: "Return the absolute pathnames of given FILE"
#include "libbb.h"
+11 -16
View File
@@ -15,15 +15,14 @@
//kbuild:lib-$(CONFIG_SHRED) += shred.o
//usage:#define shred_trivial_usage
//usage: "[-fuz] [-n N] [-s SIZE] FILE..."
//usage: "FILE..."
//usage:#define shred_full_usage "\n\n"
//usage: "Overwrite/delete FILEs\n"
//usage: "\n -f Chmod to ensure writability"
//usage: "\n -s SIZE Size to write"
//usage: "\n -n N Overwrite N times (default 3)"
//usage: "\n -z Final overwrite with zeros"
//usage: "\n -u Remove file"
//-x (exact: don't round up to 4k) and -v (verbose) are accepted but have no effect
//-x and -v are accepted but have no effect
/* shred (GNU coreutils) 8.25:
-f, --force change permissions to allow writing if necessary
@@ -42,7 +41,6 @@
int shred_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
int shred_main(int argc UNUSED_PARAM, char **argv)
{
char *opt_s;
int rand_fd = rand_fd; /* for compiler */
int zero_fd;
unsigned num_iter = 3;
@@ -54,16 +52,18 @@ int shred_main(int argc UNUSED_PARAM, char **argv)
OPT_n = (1 << 3),
OPT_v = (1 << 4),
OPT_x = (1 << 5),
OPT_s = (1 << 6),
};
opt = getopt32(argv, "^" "fuzn:+vxs:" "\0" "-1"/*min 1 arg*/, &num_iter, &opt_s);
opt = getopt32(argv, "fuzn:+vx", &num_iter);
argv += optind;
zero_fd = xopen("/dev/zero", O_RDONLY);
if (num_iter != 0)
rand_fd = xopen("/dev/urandom", O_RDONLY);
if (!*argv)
bb_show_usage();
for (;;) {
struct stat sb;
const char *fname;
@@ -85,11 +85,6 @@ int shred_main(int argc UNUSED_PARAM, char **argv)
if (fstat(fd, &sb) == 0 && sb.st_size > 0) {
off_t size = sb.st_size;
if (opt & OPT_s) {
size = BB_STRTOOFF(opt_s, NULL, 0); /* accepts oct/hex */
if (errno || size < 0) bb_show_usage();
}
for (i = 0; i < num_iter; i++) {
bb_copyfd_size(rand_fd, fd, size);
fdatasync(fd);
@@ -99,12 +94,12 @@ int shred_main(int argc UNUSED_PARAM, char **argv)
bb_copyfd_size(zero_fd, fd, size);
fdatasync(fd);
}
if (opt & OPT_u) {
ftruncate(fd, 0);
xunlink(fname);
}
xclose(fd);
}
if (opt & OPT_u) {
ftruncate(fd, 0);
xunlink(fname);
}
xclose(fd);
}
return EXIT_SUCCESS;
+39 -58
View File
@@ -17,14 +17,14 @@
//kbuild:lib-$(CONFIG_SHUF) += shuf.o
//usage:#define shuf_trivial_usage
//usage: "[-n NUM] [-o FILE] [-z] [FILE | -e [ARG...] | -i L-H]"
//usage: "[-e|-i L-H] [-n NUM] [-o FILE] [-z] [FILE|ARG...]"
//usage:#define shuf_full_usage "\n\n"
//usage: "Randomly permute lines\n"
//usage: "\n -n NUM Output at most NUM lines"
//usage: "\n -o FILE Write to FILE, not standard output"
//usage: "\n -z NUL terminated output"
//usage: "\n -e Treat ARGs as lines"
//usage: "\n -i L-H Treat numbers L-H as lines"
//usage: "\n -n NUM Output at most NUM lines"
//usage: "\n -o FILE Write to FILE, not standard output"
//usage: "\n -z End lines with zero byte, not newline"
#include "libbb.h"
@@ -39,30 +39,24 @@
/*
* Use the Fisher-Yates shuffle algorithm on an array of lines.
* If the required number of output lines is less than the total
* we can stop shuffling early.
*/
static void shuffle_lines(char **lines, unsigned numlines, unsigned outlines)
static void shuffle_lines(char **lines, unsigned numlines)
{
unsigned i;
unsigned r;
char *tmp;
srand(monotonic_us());
while (outlines != 0) {
char *tmp;
unsigned r = rand();
for (i = numlines-1; i > 0; i--) {
r = rand();
/* RAND_MAX can be as small as 32767 */
if (numlines > RAND_MAX)
if (i > RAND_MAX)
r ^= rand() << 15;
r %= numlines;
//TODO: the above method is seriously non-uniform when numlines is very large.
//For example, with numlines of 0xf0000000,
//values of (r % numlines) in [0, 0x0fffffff] range
//are more likely: e.g. r=1 and r=0xf0000001 both map to 1,
//whereas only one value, r=0xefffffff, maps to 0xefffffff.
numlines--;
tmp = lines[numlines];
lines[numlines] = lines[r];
r %= i + 1;
tmp = lines[i];
lines[i] = lines[r];
lines[r] = tmp;
outlines--;
}
}
@@ -71,10 +65,9 @@ int shuf_main(int argc, char **argv)
{
unsigned opts;
char *opt_i_str, *opt_n_str, *opt_o_str;
char **lines;
unsigned long long lo = lo;
unsigned numlines, outlines;
unsigned i;
char **lines;
unsigned numlines;
char eol;
opts = getopt32(argv, "^"
@@ -94,48 +87,35 @@ int shuf_main(int argc, char **argv)
} else
if (opts & OPT_i) {
/* create a range of numbers */
unsigned long long hi;
char *dash;
if (argv[0])
bb_show_usage();
unsigned lo, hi;
dash = strchr(opt_i_str, '-');
if (!dash) {
bb_error_msg_and_die("bad range '%s'", opt_i_str);
}
*dash = '\0';
lo = xatoull(opt_i_str);
hi = xatoull(dash + 1);
lo = xatou(opt_i_str);
hi = xatou(dash + 1);
*dash = '-';
if (hi < lo)
if (hi < lo) {
bb_error_msg_and_die("bad range '%s'", opt_i_str);
hi -= lo;
if (sizeof(size_t) > sizeof(numlines)) {
if (hi >= UINT_MAX)
bb_error_msg_and_die("bad range '%s'", opt_i_str);
} else {
if (hi >= UINT_MAX / sizeof(lines[0]))
bb_error_msg_and_die("bad range '%s'", opt_i_str);
}
numlines = hi + 1;
lines = xmalloc((size_t)numlines * sizeof(lines[0]));
numlines = (hi+1) - lo;
lines = xmalloc(numlines * sizeof(lines[0]));
for (i = 0; i < numlines; i++) {
lines[i] = (char*)(uintptr_t)i;
lines[i] = (char*)(uintptr_t)lo;
lo++;
}
} else {
/* default - read lines from stdin or the input file */
FILE *fp;
const char *fname = "-";
if (argv[0]) {
if (argv[1])
bb_show_usage();
fname = argv[0];
}
if (argc > 1)
bb_show_usage();
fp = xfopen_stdin(fname);
fp = xfopen_stdin(argv[0] ? argv[0] : "-");
lines = NULL;
numlines = 0;
for (;;) {
@@ -148,25 +128,26 @@ int shuf_main(int argc, char **argv)
fclose_if_not_stdin(fp);
}
outlines = numlines;
if (opts & OPT_n) {
outlines = xatou(opt_n_str);
if (outlines > numlines)
outlines = numlines;
}
shuffle_lines(lines, numlines, outlines);
if (numlines != 0)
shuffle_lines(lines, numlines);
if (opts & OPT_o)
xmove_fd(xopen(opt_o_str, O_WRONLY|O_CREAT|O_TRUNC), STDOUT_FILENO);
if (opts & OPT_n) {
unsigned maxlines;
maxlines = xatou(opt_n_str);
if (numlines > maxlines)
numlines = maxlines;
}
eol = '\n';
if (opts & OPT_z)
eol = '\0';
for (i = numlines - outlines; i < numlines; i++) {
for (i = 0; i < numlines; i++) {
if (opts & OPT_i)
printf("%llu%c", lo + (uintptr_t)lines[i], eol);
printf("%u%c", (unsigned)(uintptr_t)lines[i], eol);
else
printf("%s%c", lines[i], eol);
}
+4
View File
@@ -74,6 +74,10 @@ int sleep_main(int argc UNUSED_PARAM, char **argv)
sleep(INT_MAX);
#if ENABLE_FEATURE_FANCY_SLEEP
# if ENABLE_FLOAT_DURATION
/* undo busybox.c setlocale */
setlocale(LC_NUMERIC, "C");
# endif
duration = 0;
do {
duration += parse_duration_str(*argv);
+1 -2
View File
@@ -67,7 +67,7 @@
//usage: "\n -r Reverse sort order"
//usage: "\n -s Stable (don't sort ties alphabetically)"
//usage: "\n -u Suppress duplicate lines"
//usage: "\n -z NUL terminated input and output"
//usage: "\n -z Lines are terminated by NUL, not newline"
///////: "\n -m Ignored for GNU compatibility"
///////: "\n -S BUFSZ Ignored for GNU compatibility"
///////: "\n -T TMPDIR Ignored for GNU compatibility"
@@ -295,7 +295,6 @@ static int compare_keys(const void *xarg, const void *yarg)
#if ENABLE_FEATURE_SORT_BIG
case FLAG_g: {
char *xx, *yy;
//TODO: needs setlocale(LC_NUMERIC, "C")?
double dx = strtod(x, &xx);
double dy = strtod(y, &yy);
/* not numbers < NaN < -infinity < numbers < +infinity) */
+3 -5
View File
@@ -339,8 +339,7 @@ static void FAST_FUNC print_stat(char *pformat, const char m,
strcat(pformat, "lo");
printf(pformat, (unsigned long) (statbuf->st_mode & (S_ISUID|S_ISGID|S_ISVTX|S_IRWXU|S_IRWXG|S_IRWXO)));
} else if (m == 'A') {
char modestr[12];
printfs(pformat, bb_mode_string(modestr, statbuf->st_mode));
printfs(pformat, bb_mode_string(statbuf->st_mode));
} else if (m == 'f') {
strcat(pformat, "lx");
printf(pformat, (unsigned long) statbuf->st_mode);
@@ -440,7 +439,7 @@ static void print_it(const char *masterformat,
/* print preceding string */
*p = '\0';
fputs_stdout(b);
fputs(b, stdout);
p += len;
b = p + 1;
@@ -703,7 +702,6 @@ static bool do_stat(const char *filename, const char *format)
bb_putchar('\n');
# endif
} else {
char modestr[12];
char *linkname = NULL;
struct passwd *pw_ent;
struct group *gw_ent;
@@ -738,7 +736,7 @@ static bool do_stat(const char *filename, const char *format)
bb_putchar('\n');
printf("Access: (%04lo/%10.10s) Uid: (%5lu/%8s) Gid: (%5lu/%8s)\n",
(unsigned long) (statbuf.st_mode & (S_ISUID|S_ISGID|S_ISVTX|S_IRWXU|S_IRWXG|S_IRWXO)),
bb_mode_string(modestr, statbuf.st_mode),
bb_mode_string(statbuf.st_mode),
(unsigned long) statbuf.st_uid,
(pw_ent != NULL) ? pw_ent->pw_name : "UNKNOWN",
(unsigned long) statbuf.st_gid,
+1 -1
View File
@@ -855,7 +855,7 @@ static void wrapf(const char *message, ...)
}
}
}
fputs_stdout(buf);
fputs(buf, stdout);
G.current_col += buflen;
if (buf[buflen-1] == '\n')
G.current_col = 0;
+27 -42
View File
@@ -48,20 +48,19 @@
//usage:#define tail_trivial_usage
//usage: "[OPTIONS] [FILE]..."
//usage:#define tail_full_usage "\n\n"
//usage: "Print last 10 lines of FILEs (or stdin) to.\n"
//usage: "Print last 10 lines of each FILE (or stdin) to stdout.\n"
//usage: "With more than one FILE, precede each with a filename header.\n"
//usage: "\n -c [+]N[bkm] Print last N bytes"
//usage: "\n -n N[bkm] Print last N lines"
//usage: "\n -n +N[bkm] Start on Nth line and print the rest"
//usage: "\n (b:*512 k:*1024 m:*1024^2)"
//usage: "\n -f Print data as file grows"
//usage: "\n -c [+]N[kbm] Print last N bytes"
//usage: "\n -n N[kbm] Print last N lines"
//usage: "\n -n +N[kbm] Start on Nth line and print the rest"
//usage: IF_FEATURE_FANCY_TAIL(
//usage: "\n -q Never print headers"
//usage: "\n -v Always print headers"
//usage: )
//usage: "\n -f Print data as file grows"
//usage: IF_FEATURE_FANCY_TAIL(
//usage: "\n -F Same as -f, but keep retrying"
//usage: "\n -s SECONDS Wait SECONDS between reads with -f"
//usage: "\n -v Always print headers"
//usage: "\n -F Same as -f, but keep retrying"
//usage: "\n"
//usage: "\nN may be suffixed by k (x1024), b (x512), or m (x1024^2)."
//usage: )
//usage:
//usage:#define tail_example_usage
@@ -119,7 +118,7 @@ int tail_main(int argc, char **argv)
char *tailbuf;
size_t tailbufsize;
unsigned header_threshold = 1;
unsigned header_threshhold = 1;
unsigned nfiles;
int i, opt;
@@ -152,10 +151,10 @@ int tail_main(int argc, char **argv)
if (opt & 0x2) count = eat_num(str_c); // -c
if (opt & 0x4) count = eat_num(str_n); // -n
#if ENABLE_FEATURE_FANCY_TAIL
/* q: make it impossible for nfiles to be > header_threshold */
if (opt & 0x8) header_threshold = UINT_MAX; // -q
/* q: make it impossible for nfiles to be > header_threshhold */
if (opt & 0x8) header_threshhold = UINT_MAX; // -q
//if (opt & 0x10) // -s
if (opt & 0x20) header_threshold = 0; // -v
if (opt & 0x20) header_threshhold = 0; // -v
# define FOLLOW_RETRY (opt & 0x40)
#else
# define FOLLOW_RETRY 0
@@ -216,7 +215,7 @@ int tail_main(int argc, char **argv)
if (ENABLE_FEATURE_FANCY_TAIL && fd < 0)
continue; /* may happen with -F */
if (nfiles > header_threshold) {
if (nfiles > header_threshhold) {
tail_xprint_header(fmt, argv[i]);
fmt = header_fmt_str;
}
@@ -346,11 +345,9 @@ int tail_main(int argc, char **argv)
int nread;
const char *filename = argv[i];
int fd = fds[i];
int new_fd = -1;
struct stat sbuf;
if (FOLLOW_RETRY) {
struct stat fsbuf;
struct stat sbuf, fsbuf;
if (fd < 0
|| fstat(fd, &fsbuf) < 0
@@ -358,51 +355,39 @@ int tail_main(int argc, char **argv)
|| fsbuf.st_dev != sbuf.st_dev
|| fsbuf.st_ino != sbuf.st_ino
) {
/* Looks like file has been created/renamed/deleted */
int new_fd;
if (fd >= 0)
close(fd);
new_fd = open(filename, O_RDONLY);
if (new_fd >= 0) {
bb_error_msg("%s has %s; following end of new file",
filename, (fd < 0) ? "appeared" : "been replaced"
);
if (fd < 0) {
/* No previously open fd for this file,
* start using new_fd immediately. */
fds[i] = fd = new_fd;
new_fd = -1;
}
} else if (fd >= 0) {
bb_perror_msg("%s has been renamed or deleted", filename);
bb_perror_msg("%s has become inaccessible", filename);
}
fds[i] = fd = new_fd;
}
}
if (ENABLE_FEATURE_FANCY_TAIL && fd < 0)
continue;
if (nfiles > header_threshold) {
if (nfiles > header_threshhold) {
fmt = header_fmt_str;
}
for (;;) {
/* tail -f keeps following files even if they are truncated */
struct stat sbuf;
/* /proc files report zero st_size, don't lseek them */
if (fstat(fd, &sbuf) == 0
/* && S_ISREG(sbuf.st_mode) TODO? */
&& sbuf.st_size > 0
) {
if (fstat(fd, &sbuf) == 0 && sbuf.st_size > 0) {
off_t current = lseek(fd, 0, SEEK_CUR);
if (sbuf.st_size < current) {
//bb_perror_msg("%s: file truncated", filename); - says coreutils 8.32
if (sbuf.st_size < current)
xlseek(fd, 0, SEEK_SET);
}
}
nread = tail_read(fd, tailbuf, BUFSIZ);
if (nread <= 0) {
if (new_fd < 0)
break;
/* Switch to "tail -F"ing the new file */
xmove_fd(new_fd, fd);
new_fd = -1;
continue;
}
if (nread <= 0)
break;
if (fmt && (fd != prev_fd)) {
tail_xprint_header(fmt, filename);
fmt = NULL;
+3 -2
View File
@@ -435,7 +435,7 @@ struct test_statics {
};
/* See test_ptr_hack.c */
extern struct test_statics *BB_GLOBAL_CONST test_ptr_to_statics;
extern struct test_statics *const test_ptr_to_statics;
#define S (*test_ptr_to_statics)
#define args (S.args )
@@ -446,7 +446,8 @@ extern struct test_statics *BB_GLOBAL_CONST test_ptr_to_statics;
#define leaving (S.leaving )
#define INIT_S() do { \
XZALLOC_CONST_PTR(&test_ptr_to_statics, sizeof(S)); \
(*(struct test_statics**)not_const_pp(&test_ptr_to_statics)) = xzalloc(sizeof(S)); \
barrier(); \
} while (0)
#define DEINIT_S() do { \
free(group_array); \
+11 -32
View File
@@ -39,29 +39,13 @@
//kbuild:lib-$(CONFIG_TIMEOUT) += timeout.o
//usage:#define timeout_trivial_usage
//usage: "[-s SIG] [-k KILL_SECS] SECS PROG ARGS"
//usage: "[-s SIG] SECS PROG ARGS"
//usage:#define timeout_full_usage "\n\n"
//usage: "Run PROG. Send SIG to it if it is not gone in SECS seconds.\n"
//usage: "Default SIG: TERM."
//usage: "If it still exists in KILL_SECS seconds, send KILL.\n"
#include "libbb.h"
static NOINLINE int timeout_wait(int timeout, pid_t pid)
{
/* Just sleep(HUGE_NUM); kill(parent) may kill wrong process! */
while (1) {
sleep1();
if (--timeout <= 0)
break;
if (kill(pid, 0)) {
/* process is gone */
return EXIT_SUCCESS;
}
}
return EXIT_FAILURE;
}
int timeout_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
int timeout_main(int argc UNUSED_PARAM, char **argv)
{
@@ -69,29 +53,23 @@ int timeout_main(int argc UNUSED_PARAM, char **argv)
int status;
int parent = 0;
int timeout;
int kill_timeout;
pid_t pid;
#if !BB_MMU
char *sv1, *sv2;
#endif
const char *opt_s = "TERM";
char *opt_k = NULL;
/* -p option is not documented, it is needed to support NOMMU. */
/* -t SECONDS; -p PARENT_PID */
/* '+': stop at first non-option */
getopt32(argv, "+s:k:" USE_FOR_NOMMU("p:+"), &opt_s, &opt_k, &parent);
getopt32(argv, "+s:" USE_FOR_NOMMU("p:+"), &opt_s, &parent);
/*argv += optind; - no, wait for bb_daemonize_or_rexec! */
signo = get_signum(opt_s);
if (signo < 0)
bb_error_msg_and_die("unknown signal '%s'", opt_s);
kill_timeout = 0;
if (opt_k)
kill_timeout = parse_duration_str(opt_k);
if (!argv[optind])
bb_show_usage();
timeout = parse_duration_str(argv[optind++]);
@@ -125,16 +103,17 @@ int timeout_main(int argc UNUSED_PARAM, char **argv)
bb_daemonize_or_rexec(0, argv);
/* Here we are grandchild. Sleep, then kill grandparent */
grandchild:
if (timeout_wait(timeout, parent) == EXIT_SUCCESS)
return EXIT_SUCCESS;
kill(parent, signo);
if (kill_timeout > 0) {
if (timeout_wait(kill_timeout, parent) == EXIT_SUCCESS)
/* Just sleep(HUGE_NUM); kill(parent) may kill wrong process! */
while (1) {
sleep1();
if (--timeout <= 0)
break;
if (kill(parent, 0)) {
/* process is gone */
return EXIT_SUCCESS;
kill(parent, SIGKILL);
}
}
kill(parent, signo);
return EXIT_SUCCESS;
}
+76 -73
View File
@@ -19,8 +19,16 @@
//config: touch is used to create or change the access and/or
//config: modification timestamp of specified files.
//config:
//config:config FEATURE_TOUCH_NODEREF
//config: bool "Add support for -h"
//config: default y
//config: depends on TOUCH
//config: help
//config: Enable touch to have the -h option.
//config: This requires libc support for lutimes() function.
//config:
//config:config FEATURE_TOUCH_SUSV3
//config: bool "Add support for SUSV3 features (-a -d -m -t -r)"
//config: bool "Add support for SUSV3 features (-d -t -r)"
//config: default y
//config: depends on TOUCH
//config: help
@@ -30,17 +38,18 @@
//kbuild:lib-$(CONFIG_TOUCH) += touch.o
/* BB_AUDIT SUSv3 _NOT_ compliant -- options -a, -m not supported. */
/* http://www.opengroup.org/onlinepubs/007904975/utilities/touch.html */
//usage:#define touch_trivial_usage
//usage: "[-ch" IF_FEATURE_TOUCH_SUSV3("am") "]"
//usage: IF_FEATURE_TOUCH_SUSV3(" [-d DATE] [-t DATE] [-r FILE]")
//usage: " FILE..."
//usage: "[-c]" IF_FEATURE_TOUCH_SUSV3(" [-d DATE] [-t DATE] [-r FILE]") " FILE..."
//usage:#define touch_full_usage "\n\n"
//usage: "Update mtime of FILEs\n"
//usage: "Update the last-modified date on the given FILE[s]\n"
//usage: "\n -c Don't create files"
//usage: IF_FEATURE_TOUCH_NODEREF(
//usage: "\n -h Don't follow links"
//usage: )
//usage: IF_FEATURE_TOUCH_SUSV3(
//usage: "\n -a Change only atime"
//usage: "\n -m Change only mtime"
//usage: "\n -d DT Date/time to use"
//usage: "\n -t DT Date/time to use"
//usage: "\n -r FILE Use FILE's date/time"
@@ -76,99 +85,93 @@ int touch_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
int touch_main(int argc UNUSED_PARAM, char **argv)
{
int fd;
int status = EXIT_SUCCESS;
int opts;
smalluint status = EXIT_SUCCESS;
enum {
OPT_c = (1 << 0),
OPT_r = (1 << 1) * ENABLE_FEATURE_TOUCH_SUSV3,
OPT_d = (1 << 2) * ENABLE_FEATURE_TOUCH_SUSV3,
OPT_t = (1 << 3) * ENABLE_FEATURE_TOUCH_SUSV3,
OPT_h = (1 << 4) * ENABLE_FEATURE_TOUCH_NODEREF,
};
#if ENABLE_FEATURE_TOUCH_SUSV3
char *reference_file;
char *date_str;
/* timebuf[0] is atime, timebuf[1] is mtime */
struct timespec timebuf[2];
# if ENABLE_LONG_OPTS
static const char touch_longopts[] ALIGN1 =
/* name, has_arg, val */
"no-create\0" No_argument "c"
"reference\0" Required_argument "r"
"date\0" Required_argument "d"
IF_FEATURE_TOUCH_NODEREF("no-dereference\0" No_argument "h")
;
# define GETOPT32 getopt32long
# define LONGOPTS ,touch_longopts
# else
# define GETOPT32 getopt32
# define LONGOPTS
# endif
char *reference_file = NULL;
char *date_str = NULL;
struct timeval timebuf[2];
timebuf[1].tv_usec = timebuf[0].tv_usec = 0;
#else
# define reference_file NULL
# define date_str NULL
# define timebuf ((struct timespec*)NULL)
# define timebuf ((struct timeval*)NULL)
# define GETOPT32 getopt32
# define LONGOPTS
#endif
enum {
OPT_c = (1 << 0),
OPT_h = (1 << 1),
OPT_r = (1 << 2) * ENABLE_FEATURE_TOUCH_SUSV3,
OPT_d = (1 << 3) * ENABLE_FEATURE_TOUCH_SUSV3,
OPT_t = (1 << 4) * ENABLE_FEATURE_TOUCH_SUSV3,
OPT_a = (1 << 5) * ENABLE_FEATURE_TOUCH_SUSV3,
OPT_m = (1 << 6) * ENABLE_FEATURE_TOUCH_SUSV3,
};
#if ENABLE_LONG_OPTS
static const char touch_longopts[] ALIGN1 =
/* name, has_arg, val */
"no-create\0" No_argument "c"
"no-dereference\0" No_argument "h"
IF_FEATURE_TOUCH_SUSV3("reference\0" Required_argument "r")
IF_FEATURE_TOUCH_SUSV3("date\0" Required_argument "d")
;
#endif
/* -d and -t both set time. In coreutils,
* accepted data format differs a bit between -d and -t.
* We accept the same formats for both
*/
opts = getopt32long(argv, "^"
"ch"
IF_FEATURE_TOUCH_SUSV3("r:d:t:am")
/*ignored:*/ "f" IF_NOT_FEATURE_TOUCH_SUSV3("am")
"\0" /* opt_complementary: */
/* at least one arg: */ "-1"
/* coreutils forbids -r and -t at once: */ IF_FEATURE_TOUCH_SUSV3(":r--t:t--r")
/* but allows these combinations: "r--d:d--r:t--d:d--t" */
, touch_longopts
#if ENABLE_FEATURE_TOUCH_SUSV3
, &reference_file
, &date_str
, &date_str
#endif
* We accept the same formats for both */
opts = GETOPT32(argv, "c" IF_FEATURE_TOUCH_SUSV3("r:d:t:")
IF_FEATURE_TOUCH_NODEREF("h")
/*ignored:*/ "fma"
LONGOPTS
IF_FEATURE_TOUCH_SUSV3(, &reference_file)
IF_FEATURE_TOUCH_SUSV3(, &date_str)
IF_FEATURE_TOUCH_SUSV3(, &date_str)
);
#if ENABLE_FEATURE_TOUCH_SUSV3
timebuf[0].tv_nsec = timebuf[1].tv_nsec = UTIME_NOW;
if (opts & OPT_r) {
argv += optind;
if (!*argv) {
bb_show_usage();
}
if (reference_file) {
struct stat stbuf;
xstat(reference_file, &stbuf);
timebuf[0].tv_sec = stbuf.st_atime;
timebuf[1].tv_sec = stbuf.st_mtime;
timebuf[0].tv_nsec = stbuf.st_atim.tv_nsec;
timebuf[1].tv_nsec = stbuf.st_mtim.tv_nsec;
timebuf[1].tv_sec = timebuf[0].tv_sec = stbuf.st_mtime;
/* Can use .st_mtim.tv_nsec
* (or is it .st_mtimensec?? see date.c)
* to set microseconds too.
*/
}
if (opts & (OPT_d|OPT_t)) {
if (date_str) {
struct tm tm_time;
time_t t;
int check_dst;
//memset(&tm_time, 0, sizeof(tm_time));
/* Better than memset: makes "HH:MM" dates meaningful */
time(&t);
localtime_r(&t, &tm_time);
check_dst = parse_datestr(date_str, &tm_time);
parse_datestr(date_str, &tm_time);
/* Correct any day of week and day of year etc. fields */
if (check_dst)
tm_time.tm_isdst = -1; /* recheck dst unless date is UTC */
tm_time.tm_isdst = -1; /* Be sure to recheck dst */
t = validate_tm_time(date_str, &tm_time);
timebuf[1].tv_sec = timebuf[0].tv_sec = t;
timebuf[1].tv_nsec = timebuf[0].tv_nsec = 0;
}
/* If both -a and -m specified, both times should be set.
* IOW: set OMIT only if one, not both, of them is given!
*/
if ((opts & (OPT_a|OPT_m)) == OPT_a)
timebuf[1].tv_nsec = UTIME_OMIT;
if ((opts & (OPT_a|OPT_m)) == OPT_m)
timebuf[0].tv_nsec = UTIME_OMIT;
#endif
argv += optind;
do {
int result = utimensat(AT_FDCWD, *argv, timebuf,
(opts & OPT_h) ? AT_SYMLINK_NOFOLLOW : 0);
int result;
result = (
#if ENABLE_FEATURE_TOUCH_NODEREF
(opts & OPT_h) ? lutimes :
#endif
utimes)(*argv, (reference_file || date_str) ? timebuf : NULL);
if (result != 0) {
if (errno == ENOENT) { /* no such file? */
if (opts & OPT_c) {
@@ -178,9 +181,9 @@ int touch_main(int argc UNUSED_PARAM, char **argv)
/* Try to create the file */
fd = open(*argv, O_RDWR | O_CREAT, 0666);
if (fd >= 0) {
if (opts & (OPT_r|OPT_d|OPT_t))
futimens(fd, timebuf);
xclose(fd);
if (reference_file || date_str)
utimes(*argv, timebuf);
continue;
}
}
+2 -2
View File
@@ -19,9 +19,9 @@
//usage:#define truncate_trivial_usage
//usage: "[-c] -s SIZE FILE..."
//usage:#define truncate_full_usage "\n\n"
//usage: "Truncate FILEs to SIZE\n"
//usage: "Truncate FILEs to the given size\n"
//usage: "\n -c Do not create files"
//usage: "\n -s SIZE"
//usage: "\n -s SIZE Truncate to SIZE"
//usage:
//usage:#define truncate_example_usage
//usage: "$ truncate -s 1G foo"
+1 -1
View File
@@ -21,7 +21,7 @@
/* http://www.opengroup.org/onlinepubs/9699919799/utilities/tty.html */
//usage:#define tty_trivial_usage
//usage: "" IF_INCLUDE_SUSv2("[-s]")
//usage: ""
//usage:#define tty_full_usage "\n\n"
//usage: "Print file name of stdin's terminal"
//usage: IF_INCLUDE_SUSv2( "\n"
+2 -2
View File
@@ -79,13 +79,13 @@
//usage:#define uname_full_usage "\n\n"
//usage: "Print system information\n"
//usage: "\n -a Print all"
//usage: "\n -m Machine (hardware) type"
//usage: "\n -m The machine (hardware) type"
//usage: "\n -n Hostname"
//usage: "\n -r Kernel release"
//usage: "\n -s Kernel name (default)"
//usage: "\n -p Processor type"
//usage: "\n -v Kernel version"
//usage: "\n -i Hardware platform"
//usage: "\n -i The hardware platform"
//usage: "\n -o OS name"
//usage:
//usage:#define uname_example_usage
+10 -14
View File
@@ -20,14 +20,13 @@
/* http://www.opengroup.org/onlinepubs/007904975/utilities/uniq.html */
//usage:#define uniq_trivial_usage
//usage: "[-cduiz] [-f,s,w N] [FILE [OUTFILE]]"
//usage: "[-cdui] [-f,s,w N] [INPUT [OUTPUT]]"
//usage:#define uniq_full_usage "\n\n"
//usage: "Discard duplicate lines\n"
//usage: "\n -c Prefix lines by the number of occurrences"
//usage: "\n -d Only print duplicate lines"
//usage: "\n -u Only print unique lines"
//usage: "\n -i Ignore case"
//usage: "\n -z NUL terminated output"
//usage: "\n -f N Skip first N fields"
//usage: "\n -s N Skip first N chars (after any skipped fields)"
//usage: "\n -w N Compare N characters in line"
@@ -46,25 +45,23 @@ int uniq_main(int argc UNUSED_PARAM, char **argv)
const char *input_filename;
unsigned skip_fields, skip_chars, max_chars;
unsigned opt;
char eol;
char *cur_line;
const char *cur_compare;
enum {
OPT_c = 1 << 0,
OPT_d = 1 << 1, /* print only dups */
OPT_u = 1 << 2, /* print only uniq */
OPT_f = 1 << 3,
OPT_s = 1 << 4,
OPT_w = 1 << 5,
OPT_i = 1 << 6,
OPT_z = 1 << 7,
OPT_c = 0x1,
OPT_d = 0x2, /* print only dups */
OPT_u = 0x4, /* print only uniq */
OPT_f = 0x8,
OPT_s = 0x10,
OPT_w = 0x20,
OPT_i = 0x40,
};
skip_fields = skip_chars = 0;
max_chars = INT_MAX;
opt = getopt32(argv, "cduf:+s:+w:+iz", &skip_fields, &skip_chars, &max_chars);
opt = getopt32(argv, "cduf:+s:+w:+i", &skip_fields, &skip_chars, &max_chars);
argv += optind;
input_filename = argv[0];
@@ -89,7 +86,6 @@ int uniq_main(int argc UNUSED_PARAM, char **argv)
}
cur_compare = cur_line = NULL; /* prime the pump */
eol = (opt & OPT_z) ? 0 : '\n';
do {
unsigned i;
@@ -131,7 +127,7 @@ int uniq_main(int argc UNUSED_PARAM, char **argv)
/* %7lu matches GNU coreutils 6.9 */
printf("%7lu ", dups + 1);
}
printf("%s%c", old_line, eol);
puts(old_line);
}
free(old_line);
}
+6 -17
View File
@@ -155,16 +155,7 @@ int uudecode_main(int argc UNUSED_PARAM, char **argv)
break;
}
dst_stream = stdout;
if (NOT_LONE_DASH(outname)
/* https://pubs.opengroup.org/onlinepubs/9699919799/utilities/uudecode.html
* https://pubs.opengroup.org/onlinepubs/9699919799/utilities/uuencode.html
* The above says that output file name specified in input file
* or overridden by -o OUTFILE can be special "/dev/stdout" string.
* This usually works "implicitly": many systems have /dev/stdout.
* If ENABLE_DESKTOP, support that explicitly:
*/
&& (!ENABLE_DESKTOP || strcmp(outname, "/dev/stdout") != 0)
) {
if (NOT_LONE_DASH(outname)) {
dst_stream = xfopen_for_write(outname);
fchmod(fileno(dst_stream), mode & (S_IRWXU | S_IRWXG | S_IRWXO));
}
@@ -192,7 +183,7 @@ int uudecode_main(int argc UNUSED_PARAM, char **argv)
//usage:#define base32_trivial_usage
//usage: "[-d] [-w COL] [FILE]"
//usage:#define base32_full_usage "\n\n"
//usage: "Base32 encode or decode FILE to standard output\n"
//usage: "Base32 encode or decode FILE to standard output"
//usage: "\n -d Decode data"
//usage: "\n -w COL Wrap lines at COL (default 76, 0 disables)"
////usage: "\n -i When decoding, ignore non-alphabet characters"
@@ -200,12 +191,10 @@ int uudecode_main(int argc UNUSED_PARAM, char **argv)
//usage:#define base64_trivial_usage
//usage: "[-d] [-w COL] [FILE]"
//usage:#define base64_full_usage "\n\n"
//usage: "Base64 encode or decode FILE to standard output\n"
//usage: "Base64 encode or decode FILE to standard output"
//usage: "\n -d Decode data"
//usage: "\n -w COL Wrap lines at COL (default 76, 0 disables)"
///////: "\n -i When decoding, ignore non-alphabet characters"
// -i is accepted but has no effect: currently, decode_base32/64() functions
// (called via read_base64()) skip invalid chars unconditionally.
////usage: "\n -i When decoding, ignore non-alphabet characters"
// APPLET_ODDNAME:name main location suid_type help
//applet:IF_BASE32(APPLET_ODDNAME(base32, baseNUM, BB_DIR_BIN, BB_SUID_DROP, base32))
@@ -283,7 +272,7 @@ int baseNUM_main(int argc UNUSED_PARAM, char **argv)
unsigned opts;
unsigned col = 76;
opts = getopt32(argv, "^" "diw:+" "\0" "?1"/* 1 arg max*/, &col);
opts = getopt32(argv, "^" "dw:+" "\0" "?1"/* 1 arg max*/, &col);
argv += optind;
if (!argv[0])
@@ -330,7 +319,7 @@ int baseNUM_main(int argc UNUSED_PARAM, char **argv)
}
if (col == 0) {
fputs_stdout(dst_buf);
fputs(dst_buf, stdout);
} else {
char *result = dst_buf;
if (rem == 0)
+1 -1
View File
@@ -80,7 +80,7 @@
//usage: "[-c"IF_UNICODE_SUPPORT("m")"lwL] [FILE]..."
//usage:
//usage:#define wc_full_usage "\n\n"
//usage: "Count lines, words, and bytes for FILEs (or stdin)\n"
//usage: "Count lines, words, and bytes for each FILE (or stdin)\n"
//usage: "\n -c Count bytes"
//usage: IF_UNICODE_SUPPORT(
//usage: "\n -m Count characters"
+1 -1
View File
@@ -78,7 +78,7 @@
// root pts/1 Mon13 3:24m 1:01 0.01s w
//usage:#define who_trivial_usage
//usage: "[-aH]"
//usage: "[-a]"
//usage:#define who_full_usage "\n\n"
//usage: "Show who is logged on\n"
//usage: "\n -a Show all"
+2 -2
View File
@@ -27,7 +27,7 @@
//usage:#define yes_trivial_usage
//usage: "[STRING]"
//usage:#define yes_full_usage "\n\n"
//usage: "Repeatedly print a line with STRING, or 'y'"
//usage: "Repeatedly output a line with STRING, or 'y'"
#include "libbb.h"
@@ -43,7 +43,7 @@ int yes_main(int argc UNUSED_PARAM, char **argv)
do {
pp = argv;
while (1) {
fputs_stdout(*pp);
fputs(*pp, stdout);
if (!*++pp)
break;
putchar(' ');
+2 -13
View File
@@ -113,24 +113,13 @@ enum {
};
/* Is this a valid filename (upper/lower alpha, digits,
* underscores, hyphens, and non-leading dots only?)
* underscores, and hyphens only?)
*/
static bool invalid_name(const char *c)
{
c = bb_basename(c);
if (*c == '.')
return *c;
/* Debian run-parts 4.8.3, manpage:
* "...the names must consist entirely of ASCII letters,
* ASCII digits, ASCII underscores, and ASCII minus-hyphens.
* However, the name must not begin with a period."
* The last sentence is a giveaway that something is fishy
* (why mention leading dot if dots are not allowed anyway?).
* Yes, you guessed it right: in fact non-leading dots ARE allowed.
*/
while (isalnum(*c) || *c == '_' || *c == '-' || *c == '.')
while (*c && (isalnum(*c) || *c == '_' || *c == '-'))
c++;
return *c; /* TRUE (!0) if terminating NUL is not reached */
+2 -3
View File
@@ -17,10 +17,9 @@
//kbuild:lib-$(CONFIG_WHICH) += which.o
//usage:#define which_trivial_usage
//usage: "[-a] COMMAND..."
//usage: "COMMAND..."
//usage:#define which_full_usage "\n\n"
//usage: "Locate COMMAND\n"
//usage: "\n -a Show all matches"
//usage: "Locate COMMAND"
//usage:
//usage:#define which_example_usage
//usage: "$ which login\n"
-1
View File
@@ -37,7 +37,6 @@ incorrect, please send in an update.
=for html <br>
Emanuele Aina <emanuele.aina@tiscali.it>
run-parts
=for html <br>
+8 -8
View File
@@ -55,19 +55,19 @@ Next we need the configuration data. This is very similar to the example
code for the native applet:
//config:config MU
//config: bool "MU"
//config: default y
//config: help
//config: Returns an indeterminate value.
//config: bool "MU"
//config: default y
//config: help
//config: Returns an indeterminate value.
//applet:IF_MU(APPLET_SCRIPTED(mu, scripted, BB_DIR_USR_BIN, BB_SUID_DROP, mu))
//usage:#define mu_trivial_usage
//usage: "[-abcde] FILE..."
//usage: "[-abcde] FILE..."
//usage:#define mu_full_usage
//usage: "Returns an indeterminate value\n"
//usage: "\n -a First function"
//usage: "\n -b Second function"
//usage: "Returns an indeterminate value\n"
//usage: "\n -a First function"
//usage: "\n -b Second function"
The only difference is that the applet is specified as being of type
APPLET_SCRIPTED. It would also be useful to include details of any
+1 -1
View File
@@ -690,7 +690,7 @@ uniq Busybox specific options:
uudecode POSIX options
option | exists | compliant | remarks
-o outfile | yes | no |
-o outfile | no | no |
uudecode Busybox specific options: None
uuencode POSIX options
+47 -98
View File
@@ -20,52 +20,40 @@
//kbuild:lib-$(CONFIG_CHATTR) += chattr.o e2fs_lib.o
//usage:#define chattr_trivial_usage
//usage: "[-R] [-v VERSION] [-p PROJID] [-+=AacDdijsStTu] FILE..."
//usage: "[-R] [-v VERSION] [-+=AacDdijsStTu] FILE..."
//usage:#define chattr_full_usage "\n\n"
//usage: "Change ext2 file attributes\n"
//usage: "\n -R Recurse"
//usage: "\n -v NUM Set version/generation number"
//usage: "\n -p NUM Set project number"
//usage: "\n -v VER Set version/generation number"
//-V, -f accepted but ignored
//usage: "\nModifiers:"
//usage: "\n -,+,= Remove/add/set attributes"
//usage: "\nAttributes:"
//usage: "\n A No atime"
//usage: "\n a Append only"
//usage: "\n C No copy-on-write"
//usage: "\n c Compressed"
//usage: "\n D Synchronous dir updates"
//usage: "\n A Don't track atime"
//usage: "\n a Append mode only"
//usage: "\n c Enable compress"
//usage: "\n D Write dir contents synchronously"
//usage: "\n d Don't backup with dump"
//usage: "\n E Encrypted"
//usage: "\n e File uses extents"
//usage: "\n F Case-insensitive dir"
//usage: "\n I Indexed dir"
//usage: "\n i Immutable"
//usage: "\n j Write data to journal first"
//usage: "\n N File is stored in inode"
//usage: "\n P Hierarchical project ID dir"
//usage: "\n S Synchronous file updates"
//usage: "\n s Zero storage when deleted"
//usage: "\n T Top of dir hierarchy"
//usage: "\n t Don't tail-merge with other files"
//usage: "\n u Allow undelete"
//usage: "\n V Verity"
//usage: "\n i Cannot be modified (immutable)"
//usage: "\n j Write all data to journal first"
//usage: "\n s Zero disk storage when deleted"
//usage: "\n S Write synchronously"
//usage: "\n t Disable tail-merging of partial blocks with other files"
//usage: "\n u Allow file to be undeleted"
#include "libbb.h"
#include "e2fs_lib.h"
#define OPT_ADD (1 << 0)
#define OPT_REM (1 << 1)
#define OPT_SET (1 << 2)
#define OPT_SET_VER (1 << 3)
#define OPT_SET_PROJ (1 << 4)
#define OPT_ADD 1
#define OPT_REM 2
#define OPT_SET 4
#define OPT_SET_VER 8
struct globals {
unsigned version;
unsigned af;
unsigned rf;
unsigned long version;
unsigned long af;
unsigned long rf;
int flags;
uint32_t projid;
smallint recursive;
};
@@ -79,15 +67,13 @@ static unsigned long get_flag(char c)
static char** decode_arg(char **argv, struct globals *gp)
{
unsigned *fl;
unsigned long *fl;
const char *arg = *argv;
char opt = *arg;
fl = &gp->af;
if (opt == '-') {
/* gp->flags |= OPT_REM; - WRONG, it can be an option */
/* testcase: chattr =ae -R FILE should not complain "= is incompatible with - and +" */
/* (and should not read flags, with =FLAGS they can be just set directly) */
gp->flags |= OPT_REM;
fl = &gp->rf;
} else if (opt == '+') {
gp->flags |= OPT_ADD;
@@ -117,21 +103,14 @@ static char** decode_arg(char **argv, struct globals *gp)
if (*arg == 'v') {
if (!*++argv)
bb_show_usage();
gp->version = xatou(*argv);
gp->version = xatoul(*argv);
gp->flags |= OPT_SET_VER;
continue;
}
if (*arg == 'p') {
if (!*++argv)
bb_show_usage();
gp->projid = xatou32(*argv);
gp->flags |= OPT_SET_PROJ;
continue;
}
//TODO: "-p PROJECT_NUM" ?
/* not a known option, try as an attribute */
gp->flags |= OPT_REM;
}
*fl |= get_flag(*arg); /* aborts on bad flag letter */
*fl |= get_flag(*arg);
}
return argv;
@@ -141,8 +120,6 @@ static void change_attributes(const char *name, struct globals *gp);
static int FAST_FUNC chattr_dir_proc(const char *dir_name, struct dirent *de, void *gp)
{
//TODO: use de->d_type (if it's not DT_UNKNOWN) to skip !(REG || DIR || LNK) entries without lstat?
char *path = concat_subpath_file(dir_name, de->d_name);
/* path is NULL if de->d_name is "." or "..", else... */
if (path) {
@@ -154,14 +131,15 @@ static int FAST_FUNC chattr_dir_proc(const char *dir_name, struct dirent *de, vo
static void change_attributes(const char *name, struct globals *gp)
{
unsigned fsflags;
int fd;
unsigned long fsflags;
struct stat st;
if (lstat(name, &st) != 0) {
bb_perror_msg("can't stat '%s'", name);
bb_perror_msg("stat %s", name);
return;
}
if (S_ISLNK(st.st_mode) && gp->recursive)
return;
/* Don't try to open device files, fifos etc. We probably
* ought to display an error if the file was explicitly given
@@ -170,58 +148,29 @@ static void change_attributes(const char *name, struct globals *gp)
if (!S_ISREG(st.st_mode) && !S_ISLNK(st.st_mode) && !S_ISDIR(st.st_mode))
return;
/* There is no way to run needed ioctls on a symlink.
* open(O_PATH | O_NOFOLLOW) _can_ be used to get a fd referring to the symlink,
* but ioctls fail on such a fd (tried on 4.12.0 kernel).
* e2fsprogs-1.46.2 uses open(O_NOFOLLOW), it fails on symlinks.
*/
fd = open_or_warn(name, O_RDONLY | O_NONBLOCK | O_NOCTTY | O_NOFOLLOW);
if (fd >= 0) {
int r;
if (gp->flags & OPT_SET_VER)
if (fsetversion(name, gp->version) != 0)
bb_perror_msg("setting version on %s", name);
if (gp->flags & OPT_SET_VER) {
r = ioctl(fd, EXT2_IOC_SETVERSION, &gp->version);
if (r != 0)
bb_perror_msg("setting %s on %s", "version", name);
if (gp->flags & OPT_SET) {
fsflags = gp->af;
} else {
if (fgetflags(name, &fsflags) != 0) {
bb_perror_msg("reading flags on %s", name);
goto skip_setflags;
}
if (gp->flags & OPT_SET_PROJ) {
struct ext2_fsxattr fsxattr;
r = ioctl(fd, EXT2_IOC_FSGETXATTR, &fsxattr);
/* note: ^^^ may fail in 32-bit userspace on 64-bit kernel (seen on 4.12.0) */
if (r != 0) {
bb_perror_msg("getting %s on %s", "project ID", name);
} else {
fsxattr.fsx_projid = gp->projid;
r = ioctl(fd, EXT2_IOC_FSSETXATTR, &fsxattr);
if (r != 0)
bb_perror_msg("setting %s on %s", "project ID", name);
}
}
if (gp->flags & OPT_SET) {
fsflags = gp->af;
} else {
r = ioctl(fd, EXT2_IOC_GETFLAGS, &fsflags);
if (r != 0) {
bb_perror_msg("getting %s on %s", "flags", name);
goto skip_setflags;
}
/*if (gp->flags & OPT_REM) - not needed, rf is zero otherwise */
fsflags &= ~gp->rf;
/*if (gp->flags & OPT_ADD) - not needed, af is zero otherwise */
fsflags |= gp->af;
/*if (gp->flags & OPT_REM) - not needed, rf is zero otherwise */
fsflags &= ~gp->rf;
/*if (gp->flags & OPT_ADD) - not needed, af is zero otherwise */
fsflags |= gp->af;
// What is this? And why it's not done for SET case?
if (!S_ISDIR(st.st_mode))
fsflags &= ~EXT2_DIRSYNC_FL;
}
r = ioctl(fd, EXT2_IOC_SETFLAGS, &fsflags);
if (r != 0)
bb_perror_msg("setting %s on %s", "flags", name);
skip_setflags:
close(fd);
if (!S_ISDIR(st.st_mode))
fsflags &= ~EXT2_DIRSYNC_FL;
}
if (fsetflags(name, fsflags) != 0)
bb_perror_msg("setting flags on %s", name);
skip_setflags:
if (gp->recursive && S_ISDIR(st.st_mode))
iterate_on_dir(name, chattr_dir_proc, gp);
}
@@ -251,7 +200,7 @@ int chattr_main(int argc UNUSED_PARAM, char **argv)
if (g.rf & g.af)
bb_simple_error_msg_and_die("can't set and unset a flag");
if (!g.flags)
bb_simple_error_msg_and_die("must use -v, -p, =, - or +");
bb_simple_error_msg_and_die("must use '-v', =, - or +");
/* now run chattr on all the files passed to us */
do change_attributes(*argv, &g); while (*++argv);
+153 -51
View File
@@ -8,13 +8,133 @@
#include "libbb.h"
#include "e2fs_lib.h"
#define HAVE_EXT2_IOCTLS 1
#if INT_MAX == LONG_MAX
#define IF_LONG_IS_SAME(...) __VA_ARGS__
#define IF_LONG_IS_WIDER(...)
#else
#define IF_LONG_IS_SAME(...)
#define IF_LONG_IS_WIDER(...) __VA_ARGS__
#endif
static void close_silently(int fd)
{
int e = errno;
close(fd);
errno = e;
}
/* Iterate a function on each entry of a directory */
int iterate_on_dir(const char *dir_name,
int FAST_FUNC (*func)(const char *, struct dirent *, void *),
void *private)
{
DIR *dir;
struct dirent *de;
dir = opendir(dir_name);
if (dir == NULL) {
return -1;
}
while ((de = readdir(dir)) != NULL) {
func(dir_name, de, private);
}
closedir(dir);
return 0;
}
/* Get/set a file version on an ext2 file system */
int fgetsetversion(const char *name, unsigned long *get_version, unsigned long set_version)
{
#if HAVE_EXT2_IOCTLS
int fd, r;
IF_LONG_IS_WIDER(int ver;)
fd = open(name, O_RDONLY | O_NONBLOCK);
if (fd == -1)
return -1;
if (!get_version) {
IF_LONG_IS_WIDER(
ver = (int) set_version;
r = ioctl(fd, EXT2_IOC_SETVERSION, &ver);
)
IF_LONG_IS_SAME(
r = ioctl(fd, EXT2_IOC_SETVERSION, (void*)&set_version);
)
} else {
IF_LONG_IS_WIDER(
r = ioctl(fd, EXT2_IOC_GETVERSION, &ver);
*get_version = ver;
)
IF_LONG_IS_SAME(
r = ioctl(fd, EXT2_IOC_GETVERSION, (void*)get_version);
)
}
close_silently(fd);
return r;
#else /* ! HAVE_EXT2_IOCTLS */
errno = EOPNOTSUPP;
return -1;
#endif /* ! HAVE_EXT2_IOCTLS */
}
/* Get/set a file flags on an ext2 file system */
int fgetsetflags(const char *name, unsigned long *get_flags, unsigned long set_flags)
{
#if HAVE_EXT2_IOCTLS
struct stat buf;
int fd, r;
IF_LONG_IS_WIDER(int f;)
if (stat(name, &buf) == 0 /* stat is ok */
&& !S_ISREG(buf.st_mode) && !S_ISDIR(buf.st_mode)
) {
goto notsupp;
}
fd = open(name, O_RDONLY | O_NONBLOCK); /* neither read nor write asked for */
if (fd == -1)
return -1;
if (!get_flags) {
IF_LONG_IS_WIDER(
f = (int) set_flags;
r = ioctl(fd, EXT2_IOC_SETFLAGS, &f);
)
IF_LONG_IS_SAME(
r = ioctl(fd, EXT2_IOC_SETFLAGS, (void*)&set_flags);
)
} else {
IF_LONG_IS_WIDER(
r = ioctl(fd, EXT2_IOC_GETFLAGS, &f);
*get_flags = f;
)
IF_LONG_IS_SAME(
r = ioctl(fd, EXT2_IOC_GETFLAGS, (void*)get_flags);
)
}
close_silently(fd);
return r;
notsupp:
#endif /* HAVE_EXT2_IOCTLS */
errno = EOPNOTSUPP;
return -1;
}
/* Print file attributes on an ext2 file system */
const uint32_t e2attr_flags_value[] ALIGN4 = {
#ifdef ENABLE_COMPRESSION
EXT2_COMPRBLK_FL,
EXT2_DIRTY_FL,
EXT2_NOCOMPR_FL,
EXT2_ECOMPR_FL,
#endif
EXT2_INDEX_FL,
EXT2_SECRM_FL,
EXT2_UNRM_FL,
EXT2_SYNC_FL,
@@ -24,31 +144,26 @@ const uint32_t e2attr_flags_value[] ALIGN4 = {
EXT2_NODUMP_FL,
EXT2_NOATIME_FL,
EXT2_COMPR_FL,
EXT2_ECOMPR_FL,
EXT3_JOURNAL_DATA_FL,
EXT2_INDEX_FL,
EXT2_NOTAIL_FL,
EXT2_TOPDIR_FL,
EXT2_EXTENT_FL,
EXT2_NOCOW_FL,
EXT2_CASEFOLD_FL,
EXT2_INLINE_DATA_FL,
EXT2_PROJINHERIT_FL,
EXT2_VERITY_FL,
EXT2_TOPDIR_FL
};
const char e2attr_flags_sname[] ALIGN1 =
#ifdef ENABLE_COMPRESSION
"BZX"
"BZXE"
#endif
"suSDiadAcEjItTeCFNPV";
"I"
"suSDiadAcjtT";
static const char e2attr_flags_lname[] ALIGN1 =
#ifdef ENABLE_COMPRESSION
"Compressed_File" "\0"
"Compressed_Dirty_File" "\0"
"Compression_Raw_Access" "\0"
"Compression_Error" "\0"
#endif
"Indexed_directory" "\0"
"Secure_Deletion" "\0"
"Undelete" "\0"
"Synchronous_Updates" "\0"
@@ -58,54 +173,41 @@ static const char e2attr_flags_lname[] ALIGN1 =
"No_Dump" "\0"
"No_Atime" "\0"
"Compression_Requested" "\0"
"Encrypted" "\0"
"Journaled_Data" "\0"
"Indexed_directory" "\0"
"No_Tailmerging" "\0"
"Top_of_Directory_Hierarchies" "\0"
"Extents" "\0"
"No_COW" "\0"
"Casefold" "\0"
"Inline_Data" "\0"
"Project_Hierarchy" "\0"
"Verity" "\0"
/* Another trailing NUL is added by compiler */;
void print_e2flags_long(unsigned flags)
{
const uint32_t *fv;
const char *fn;
int first = 1;
fv = e2attr_flags_value;
fn = e2attr_flags_lname;
do {
if (flags & *fv) {
if (!first)
fputs(", ", stdout);
fputs(fn, stdout);
first = 0;
}
fv++;
fn += strlen(fn) + 1;
} while (*fn);
if (first)
fputs("---", stdout);
}
void print_e2flags(unsigned flags)
void print_e2flags(FILE *f, unsigned long flags, unsigned options)
{
const uint32_t *fv;
const char *fn;
fv = e2attr_flags_value;
fn = e2attr_flags_sname;
do {
char c = '-';
if (flags & *fv)
c = *fn;
putchar(c);
fv++;
fn++;
} while (*fn);
if (options & PFOPT_LONG) {
int first = 1;
fn = e2attr_flags_lname;
do {
if (flags & *fv) {
if (!first)
fputs(", ", f);
fputs(fn, f);
first = 0;
}
fv++;
fn += strlen(fn) + 1;
} while (*fn);
if (first)
fputs("---", f);
} else {
fn = e2attr_flags_sname;
do {
char c = '-';
if (flags & *fv)
c = *fn;
fputc(c, f);
fv++;
fn++;
} while (*fn);
}
}
+18 -2
View File
@@ -11,9 +11,25 @@
PUSH_AND_SET_FUNCTION_VISIBILITY_TO_HIDDEN
/* Iterate a function on each entry of a directory */
int iterate_on_dir(const char *dir_name,
int FAST_FUNC (*func)(const char *, struct dirent *, void *),
void *private);
/* Get/set a file version on an ext2 file system */
int fgetsetversion(const char *name, unsigned long *get_version, unsigned long set_version);
#define fgetversion(name, version) fgetsetversion(name, version, 0)
#define fsetversion(name, version) fgetsetversion(name, NULL, version)
/* Get/set a file flags on an ext2 file system */
int fgetsetflags(const char *name, unsigned long *get_flags, unsigned long set_flags);
#define fgetflags(name, flags) fgetsetflags(name, flags, 0)
#define fsetflags(name, flags) fgetsetflags(name, NULL, flags)
/* Must be 1 for compatibility with 'int long_format'. */
#define PFOPT_LONG 1
/* Print file attributes on an ext2 file system */
void print_e2flags_long(unsigned flags);
void print_e2flags(unsigned flags);
void print_e2flags(FILE *f, unsigned long flags, unsigned options);
extern const uint32_t e2attr_flags_value[];
extern const char e2attr_flags_sname[];
+22 -53
View File
@@ -21,79 +21,52 @@
//kbuild:lib-$(CONFIG_LSATTR) += lsattr.o e2fs_lib.o
//usage:#define lsattr_trivial_usage
//usage: "[-Radlpv] [FILE]..."
//usage: "[-Radlv] [FILE]..."
//usage:#define lsattr_full_usage "\n\n"
//usage: "List ext2 file attributes\n"
//usage: "\n -R Recurse"
//usage: "\n -a Include names starting with ."
//usage: "\n -d List directory names, not contents"
// -a,-d text should match ls --help
//usage: "\n -a Don't hide entries starting with ."
//usage: "\n -d List directory entries instead of contents"
//usage: "\n -l List long flag names"
//usage: "\n -p List project ID"
//usage: "\n -v List version/generation number"
#include "libbb.h"
#include "e2fs_lib.h"
enum {
OPT_RECUR = 1 << 0,
OPT_ALL = 1 << 1,
OPT_DIRS_OPT = 1 << 2,
OPT_PF_LONG = 1 << 3,
OPT_GENERATION = 1 << 4,
OPT_PROJID = 1 << 5,
OPT_RECUR = 0x1,
OPT_ALL = 0x2,
OPT_DIRS_OPT = 0x4,
OPT_PF_LONG = 0x8,
OPT_GENERATION = 0x10,
};
static void list_attributes(const char *name)
{
unsigned fsflags;
int fd, r;
unsigned long fsflags;
unsigned long generation;
/* There is no way to run needed ioctls on a symlink.
* open(O_PATH | O_NOFOLLOW) _can_ be used to get a fd referring to the symlink,
* but ioctls fail on such a fd (tried on 4.12.0 kernel).
* e2fsprogs-1.46.2 uses open(O_NOFOLLOW), it fails on symlinks.
*/
fd = open_or_warn(name, O_RDONLY | O_NONBLOCK | O_NOCTTY | O_NOFOLLOW);
if (fd < 0)
return;
if (option_mask32 & OPT_PROJID) {
struct ext2_fsxattr fsxattr;
r = ioctl(fd, EXT2_IOC_FSGETXATTR, &fsxattr);
/* note: ^^^ may fail in 32-bit userspace on 64-bit kernel (seen on 4.12.0) */
if (r != 0)
goto read_err;
printf("%5u ", (unsigned)fsxattr.fsx_projid);
}
if (option_mask32 & OPT_GENERATION) {
unsigned generation;
r = ioctl(fd, EXT2_IOC_GETVERSION, &generation);
if (r != 0)
goto read_err;
printf("%-10u ", generation);
}
r = ioctl(fd, EXT2_IOC_GETFLAGS, &fsflags);
if (r != 0)
if (fgetflags(name, &fsflags) != 0)
goto read_err;
close(fd);
if (option_mask32 & OPT_GENERATION) {
if (fgetversion(name, &generation) != 0)
goto read_err;
printf("%5lu ", generation);
}
if (option_mask32 & OPT_PF_LONG) {
printf("%-28s ", name);
print_e2flags_long(fsflags);
print_e2flags(stdout, fsflags, PFOPT_LONG);
bb_putchar('\n');
} else {
print_e2flags(fsflags);
print_e2flags(stdout, fsflags, 0);
printf(" %s\n", name);
}
return;
read_err:
bb_perror_msg("reading %s", name);
close(fd);
}
static int FAST_FUNC lsattr_dir_proc(const char *dir_name,
@@ -106,13 +79,9 @@ static int FAST_FUNC lsattr_dir_proc(const char *dir_name,
path = concat_path_file(dir_name, de->d_name);
if (lstat(path, &st) != 0)
bb_perror_msg("can't stat '%s'", path);
bb_perror_msg("stat %s", path);
else if (de->d_name[0] != '.' || (option_mask32 & OPT_ALL)) {
/* Don't try to open device files, fifos etc */
if (S_ISREG(st.st_mode) || S_ISLNK(st.st_mode) || S_ISDIR(st.st_mode))
list_attributes(path);
list_attributes(path);
if (S_ISDIR(st.st_mode) && (option_mask32 & OPT_RECUR)
&& !DOT_OR_DOTDOT(de->d_name)
) {
@@ -131,7 +100,7 @@ static void lsattr_args(const char *name)
struct stat st;
if (lstat(name, &st) == -1) {
bb_perror_msg("can't stat '%s'", name);
bb_perror_msg("stat %s", name);
} else if (S_ISDIR(st.st_mode) && !(option_mask32 & OPT_DIRS_OPT)) {
iterate_on_dir(name, lsattr_dir_proc, NULL);
} else {
@@ -142,7 +111,7 @@ static void lsattr_args(const char *name)
int lsattr_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
int lsattr_main(int argc UNUSED_PARAM, char **argv)
{
getopt32(argv, "Radlvp");
getopt32(argv, "Radlv");
argv += optind;
if (!*argv)
+867 -1215
View File
File diff suppressed because it is too large. Load diff
+3 -9
View File
@@ -18,13 +18,12 @@
//kbuild:lib-$(CONFIG_CMP) += cmp.o
//usage:#define cmp_trivial_usage
//usage: "[-ls] [-n NUM] FILE1 [FILE2" IF_DESKTOP(" [SKIP1 [SKIP2]]") "]"
//usage: "[-l] [-s] FILE1 [FILE2" IF_DESKTOP(" [SKIP1 [SKIP2]]") "]"
//usage:#define cmp_full_usage "\n\n"
//usage: "Compare FILE1 with FILE2 (or stdin)\n"
//usage: "\n -l Write the byte numbers (decimal) and values (octal)"
//usage: "\n for all differing bytes"
//usage: "\n -s Quiet"
//usage: "\n -n NUM Compare at most NUM bytes"
/* BB_AUDIT SUSv3 (virtually) compliant -- uses nicer GNU format for -l. */
/* http://www.opengroup.org/onlinepubs/007904975/utilities/cmp.html */
@@ -36,10 +35,9 @@ static const char fmt_differ[] ALIGN1 = "%s %s differ: char %"OFF_FMT"u, line %u
// This fmt_l_opt uses gnu-isms. SUSv3 would be "%.0s%.0s%"OFF_FMT"u %o %o\n"
static const char fmt_l_opt[] ALIGN1 = "%.0s%.0s%"OFF_FMT"u %3o %3o\n";
#define OPT_STR "sln:+"
#define OPT_STR "sl"
#define CMP_OPT_s (1<<0)
#define CMP_OPT_l (1<<1)
#define CMP_OPT_n (1<<2)
int cmp_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
int cmp_main(int argc UNUSED_PARAM, char **argv)
@@ -52,15 +50,13 @@ int cmp_main(int argc UNUSED_PARAM, char **argv)
int c1, c2;
unsigned opt;
int retval = 0;
int max_count = -1;
opt = getopt32(argv, "^"
OPT_STR
"\0" "-1"
IF_DESKTOP(":?4")
IF_NOT_DESKTOP(":?2")
":l--s:s--l",
&max_count
":l--s:s--l"
);
argv += optind;
@@ -99,8 +95,6 @@ int cmp_main(int argc UNUSED_PARAM, char **argv)
while (skip2) { getc(fp2); skip2--; }
}
do {
if (max_count >= 0 && --max_count < 0)
break;
c1 = getc(fp1);
c2 = getc(fp2);
++char_pos;
+1 -1
View File
@@ -1050,7 +1050,7 @@ int diff_main(int argc UNUSED_PARAM, char **argv)
/* diffreg can get non-regular files here */
print_status(gotstdin > 1 ? STATUS_SAME : diffreg(file), file);
if (ENABLE_FEATURE_CLEAN_UP && dirfile)
if (dirfile)
free(file[dir]);
}
+24 -29
View File
@@ -18,7 +18,7 @@
//applet:IF_ED(APPLET(ed, BB_DIR_BIN, BB_SUID_DROP))
//usage:#define ed_trivial_usage "[-p PROMPT] [FILE]"
//usage:#define ed_trivial_usage "[FILE]"
//usage:#define ed_full_usage ""
#include "libbb.h"
@@ -48,7 +48,6 @@ struct globals {
char *bufBase;
char *bufPtr;
char *fileName;
const char *prompt;
LINE lines;
smallint dirty;
int marks[26];
@@ -58,7 +57,6 @@ struct globals {
#define bufBase (G.bufBase )
#define bufPtr (G.bufPtr )
#define fileName (G.fileName )
#define prompt (G.prompt )
#define curNum (G.curNum )
#define lastNum (G.lastNum )
#define bufUsed (G.bufUsed )
@@ -382,8 +380,7 @@ static void addLines(int num)
static int readLines(const char *file, int num)
{
int fd, cc;
int len;
unsigned charCount;
int len, lineCount, charCount;
char *cp;
if ((num < 1) || (num > lastNum + 1)) {
@@ -399,9 +396,13 @@ static int readLines(const char *file, int num)
bufPtr = bufBase;
bufUsed = 0;
lineCount = 0;
charCount = 0;
cc = 0;
printf("\"%s\", ", file);
fflush_all();
do {
cp = memchr(bufPtr, '\n', bufUsed);
@@ -414,6 +415,7 @@ static int readLines(const char *file, int num)
bufPtr += len;
bufUsed -= len;
charCount += len;
lineCount++;
num++;
continue;
}
@@ -447,18 +449,15 @@ static int readLines(const char *file, int num)
close(fd);
return -1;
}
lineCount++;
charCount += bufUsed;
}
close(fd);
/* https://pubs.opengroup.org/onlinepubs/9699919799/utilities/ed.html
* "Read Command"
* "...the number of bytes read shall be written to standard output
* in the following format:
* "%d\n", <number of bytes read>
*/
printf("%u\n", charCount);
printf("%d lines%s, %d chars\n", lineCount,
(bufUsed ? " (incomplete)" : ""), charCount);
return TRUE;
}
@@ -469,12 +468,12 @@ static int readLines(const char *file, int num)
static int writeLines(const char *file, int num1, int num2)
{
LINE *lp;
int fd;
unsigned charCount;
int fd, lineCount, charCount;
if (bad_nums(num1, num2, "write"))
return FALSE;
lineCount = 0;
charCount = 0;
fd = creat(file, 0666);
@@ -483,6 +482,9 @@ static int writeLines(const char *file, int num1, int num2)
return FALSE;
}
printf("\"%s\", ", file);
fflush_all();
lp = findLine(num1);
if (lp == NULL) {
close(fd);
@@ -496,6 +498,7 @@ static int writeLines(const char *file, int num1, int num2)
return FALSE;
}
charCount += lp->len;
lineCount++;
lp = lp->next;
}
@@ -504,13 +507,7 @@ static int writeLines(const char *file, int num1, int num2)
return FALSE;
}
/* https://pubs.opengroup.org/onlinepubs/9699919799/utilities/ed.html
* "Write Command"
* "...the number of bytes written shall be written to standard output,
* unless the -s option was specified, in the following format:
* "%d\n", <number of bytes written>
*/
printf("%u\n", charCount);
printf("%d lines, %d chars\n", lineCount, charCount);
return TRUE;
}
@@ -556,7 +553,7 @@ static int printLines(int num1, int num2, int expandFlag)
fputc_printable(ch | PRINTABLE_META, stdout);
}
fputs_stdout("$\n");
fputs("$\n", stdout);
setCurNum(num1++);
lp = lp->next;
@@ -792,7 +789,7 @@ static void doCommands(void)
* 0 on ctrl-C,
* >0 length of input string, including terminating '\n'
*/
len = read_line_input(NULL, prompt, buf, sizeof(buf));
len = read_line_input(NULL, ": ", buf, sizeof(buf));
if (len <= 0)
return;
while (len && isspace(buf[--len]))
@@ -1004,15 +1001,13 @@ int ed_main(int argc UNUSED_PARAM, char **argv)
lines.next = &lines;
lines.prev = &lines;
prompt = ""; /* no prompt by default */
getopt32(argv, "p:", &prompt);
argv += optind;
if (argv[0]) {
fileName = xstrdup(argv[0]);
if (argv[1]) {
fileName = xstrdup(argv[1]);
if (!readLines(fileName, 1)) {
return EXIT_SUCCESS;
}
if (lastNum)
setCurNum(1);
dirty = FALSE;
}
+3 -2
View File
@@ -70,7 +70,7 @@
//usage:#define sed_full_usage "\n\n"
//usage: " -e CMD Add CMD to sed commands to be executed"
//usage: "\n -f FILE Add FILE contents to sed commands to be executed"
//usage: "\n -i[SFX] Edit files in-place (otherwise write to stdout)"
//usage: "\n -i[SFX] Edit files in-place (otherwise sends to stdout)"
//usage: "\n Optionally back files up, appending SFX"
//usage: "\n -n Suppress automatic printing of pattern space"
//usage: "\n -r,-E Use extended regex syntax"
@@ -435,7 +435,8 @@ static int parse_subst_cmd(sed_cmd_t *sed_cmd, const char *substr)
switch (substr[idx]) {
/* Replace all occurrences */
case 'g':
sed_cmd->which_match = 0;
if (match[0] != '^')
sed_cmd->which_match = 0;
break;
/* Print pattern space */
case 'p':
+720 -1325
View File
File diff suppressed because it is too large. Load diff
+3 -6
View File
@@ -79,7 +79,7 @@ option staticroutes 10.0.0.0/8 10.127.0.1, 10.11.12.0/24 10.11.12.1
option 0x08 01020304 # option 8: "cookie server IP addr: 1.2.3.4"
option 14 "dumpfile"
# Currently supported options [hex option value] (for more info, see common.c):
# Currently supported options [hex option value] (for more info, see options.c):
#opt lease NUM # [0x33]
#opt subnet IP # [0x01]
#opt broadcast IP # [0x1c]
@@ -91,20 +91,17 @@ option 14 "dumpfile"
#opt search STRING_LIST # [0x77] search domains
#opt nisdomain STRING # [0x28]
#opt timezone NUM # [0x02] (localtime - UTC_time) in seconds. signed
#opt tzstr STRING # [0x64] RFC 4833. IEEE 1003.1 TZ string
#opt tzdbstr STRING # [0x65] RFC 4833. Reference to the TZ database string
#opt tftp STRING # [0x42] tftp server name
#opt bootfile STRING # [0x43] tftp file to download (e.g. kernel image)
#opt bootsize NUM # [0x0d] size of that file
#opt rootpath STRING # [0x11] (NFS) path to mount as root fs
#opt wpad STRING # [0xfc] Web Proxy Auto Discovery Protocol
#opt serverid IP # [0x36] default: server's IP
#opt message STRING # [0x38] error message (if set, udhcpd would send it on success too)
#opt message STRING # [0x38] error message (udhcpd sends it on success too)
#opt vlanid NUM # [0x84] 802.1P VLAN ID
#opt vlanpriority NUM # [0x85] 802.1Q VLAN priority
#opt vendor STRING # [0x3c] client's vendor string, not intended to be sent by DHCP servers
# RFC 5071: PXELINUX Options
#opt 0xd0 F100747E # [0xd0] magic needed for other options to be recognized by clients
#opt 0xd0 F100747E # [0xd0] magic
#opt pxeconffile STRING # [0xd1]
#opt pxepathprefix STRING # [0xd2]
#opt reboottime NUM # [0xd3] bootstrap timeout
+8 -12
View File
@@ -179,9 +179,7 @@ ipt="iptables -t nat -A OUTPUT"
# OUTGOING TRAFFIC
ipt="iptables -t nat -A POSTROUTING"
# Masquerade boxes on my private net
for e in $extif; do
doit $ipt -s 192.168.0.0/24 -o $e -j MASQUERADE
done
doit $ipt -s 192.168.0.0/24 -o $extif -j MASQUERADE
# *** mangle ***
### DEBUG
@@ -206,9 +204,7 @@ fi
doit $ipt -p tcp -j REJECT # Anything else isn't ok. REJECT = irc opens faster
# (it probes proxy ports, DROP will incur timeout delays)
ipt="iptables -t filter -A INPUT"
for e in $extif; do
doit $ipt -i $e -j iext
done
doit $ipt -i $extif -j iext
echo; echo "* Enabling forwarding"
@@ -226,12 +222,12 @@ echo; echo "* Routing:"
ip r l
echo; echo "* Firewall:"
{
echo '---FILTER--'
iptables -v -L -x -n
echo '---NAT-----'
iptables -t nat -v -L -x -n
echo '---MANGLE--'
iptables -t mangle -v -L -x -n
echo '---FILTER--';
iptables -v -L -x -n;
echo '---NAT-----';
iptables -t nat -v -L -x -n;
echo '---MANGLE--';
iptables -t mangle -v -L -x -n;
} \
| grep -v '^$' | grep -Fv 'bytes target'
echo
+22 -160
View File
@@ -67,53 +67,21 @@
//config: interpreted by other programs.
//config:
//config:config FEATURE_FIND_MTIME
//config: bool "Enable -mtime: modification time matching"
//config: bool "Enable -mtime: modified time matching"
//config: default y
//config: depends on FIND
//config: help
//config: Allow searching based on the modification time of
//config: files, in days.
//config:
//config:config FEATURE_FIND_ATIME
//config: bool "Enable -atime: access time matching"
//config: default y
//config: depends on FEATURE_FIND_MTIME
//config: help
//config: Allow searching based on the access time of
//config: files, in days.
//config:
//config:config FEATURE_FIND_CTIME
//config: bool "Enable -ctime: status change timestamp matching"
//config: default y
//config: depends on FEATURE_FIND_MTIME
//config: help
//config: Allow searching based on the status change timestamp of
//config: files, in days.
//config:
//config:config FEATURE_FIND_MMIN
//config: bool "Enable -mmin: modification time matching by minutes"
//config: bool "Enable -mmin: modified time matching by minutes"
//config: default y
//config: depends on FIND
//config: help
//config: Allow searching based on the modification time of
//config: files, in minutes.
//config:
//config:config FEATURE_FIND_AMIN
//config: bool "Enable -amin: access time matching by minutes"
//config: default y
//config: depends on FEATURE_FIND_MMIN
//config: help
//config: Allow searching based on the access time of
//config: files, in minutes.
//config:
//config:config FEATURE_FIND_CMIN
//config: bool "Enable -cmin: status change timestamp matching by minutes"
//config: default y
//config: depends on FEATURE_FIND_MMIN
//config: help
//config: Allow searching based on the status change timestamp of
//config: files, in minutes.
//config:
//config:config FEATURE_FIND_PERM
//config: bool "Enable -perm: permissions matching"
//config: default y
@@ -155,13 +123,6 @@
//config: default y
//config: depends on FIND
//config:
//config:config FEATURE_FIND_SAMEFILE
//config: bool "Enable -samefile: reference file matching"
//config: default y
//config: depends on FIND
//config: help
//config: Support the 'find -samefile' option for searching by a reference file.
//config:
//config:config FEATURE_FIND_EXEC
//config: bool "Enable -exec: execute commands"
//config: default y
@@ -335,31 +296,16 @@
//usage: "\n -mtime DAYS mtime is greater than (+N), less than (-N),"
//usage: "\n or exactly N days in the past"
//usage: )
//usage: IF_FEATURE_FIND_ATIME(
//usage: "\n -atime DAYS atime +N/-N/N days in the past"
//usage: )
//usage: IF_FEATURE_FIND_CTIME(
//usage: "\n -ctime DAYS ctime +N/-N/N days in the past"
//usage: )
//usage: IF_FEATURE_FIND_MMIN(
//usage: "\n -mmin MINS mtime is greater than (+N), less than (-N),"
//usage: "\n or exactly N minutes in the past"
//usage: )
//usage: IF_FEATURE_FIND_AMIN(
//usage: "\n -amin MINS atime +N/-N/N minutes in the past"
//usage: )
//usage: IF_FEATURE_FIND_CMIN(
//usage: "\n -cmin MINS ctime +N/-N/N minutes in the past"
//usage: )
//usage: IF_FEATURE_FIND_NEWER(
//usage: "\n -newer FILE mtime is more recent than FILE's"
//usage: )
//usage: IF_FEATURE_FIND_INUM(
//usage: "\n -inum N File has inode number N"
//usage: )
//usage: IF_FEATURE_FIND_SAMEFILE(
//usage: "\n -samefile FILE File is same as FILE"
//usage: )
//usage: IF_FEATURE_FIND_USER(
//usage: "\n -user NAME/ID File is owned by given user"
//usage: )
@@ -450,11 +396,10 @@ IF_FEATURE_FIND_PRINT0( ACTS(print0))
IF_FEATURE_FIND_TYPE( ACTS(type, int type_mask;))
IF_FEATURE_FIND_EXECUTABLE(ACTS(executable))
IF_FEATURE_FIND_PERM( ACTS(perm, char perm_char; mode_t perm_mask;))
IF_FEATURE_FIND_MTIME( ACTS(mtime, unsigned char time_type; unsigned char mtime_char; unsigned mtime_days;))
IF_FEATURE_FIND_MMIN( ACTS(mmin, unsigned char time_type; unsigned char mmin_char; unsigned mmin_mins;))
IF_FEATURE_FIND_MTIME( ACTS(mtime, char mtime_char; unsigned mtime_days;))
IF_FEATURE_FIND_MMIN( ACTS(mmin, char mmin_char; unsigned mmin_mins;))
IF_FEATURE_FIND_NEWER( ACTS(newer, time_t newer_mtime;))
IF_FEATURE_FIND_INUM( ACTS(inum, ino_t inode_num;))
IF_FEATURE_FIND_SAMEFILE(ACTS(samefile, ino_t inode_num; dev_t device;))
IF_FEATURE_FIND_USER( ACTS(user, uid_t uid;))
IF_FEATURE_FIND_SIZE( ACTS(size, char size_char; off_t size;))
IF_FEATURE_FIND_CONTEXT(ACTS(context, security_context_t context;))
@@ -673,61 +618,30 @@ ACTF(perm)
return (statbuf->st_mode & 07777) == ap->perm_mask;
}
#endif
#if 0 \
|| ENABLE_FEATURE_FIND_AMIN \
|| ENABLE_FEATURE_FIND_ATIME \
|| ENABLE_FEATURE_FIND_CMIN \
|| ENABLE_FEATURE_FIND_CTIME \
|| ENABLE_FEATURE_FIND_MMIN \
|| ENABLE_FEATURE_FIND_MTIME
static int time_cmp(const struct stat *statbuf, unsigned type_and_char, time_t N_from_user, unsigned unit)
{
time_t ftime, file_age;
ftime = statbuf->st_mtime;
# if ENABLE_FEATURE_FIND_ATIME || ENABLE_FEATURE_FIND_CTIME
# if ENABLE_FEATURE_FIND_ATIME
if ((type_and_char >> 8) == 'a')
ftime = statbuf->st_atime;
# endif
# if ENABLE_FEATURE_FIND_CTIME
if ((type_and_char >> 8) == 'c')
ftime = statbuf->st_ctime;
# endif
type_and_char &= 0xff;
# endif
file_age = time(NULL) - ftime;
N_from_user *= unit;
switch (type_and_char) {
case '+': return file_age >= N_from_user + unit;
case '-': return file_age < N_from_user;
/* just numeric time */
default: return file_age >= N_from_user && file_age < N_from_user + unit;
}
}
#endif
#if ENABLE_FEATURE_FIND_MTIME
ACTF(mtime)
{
return time_cmp(statbuf,
# if ENABLE_FEATURE_FIND_ATIME || ENABLE_FEATURE_FIND_CTIME
(ap->time_type << 8) |
# endif
ap->mtime_char,
ap->mtime_days, 24*60*60);
time_t file_age = time(NULL) - statbuf->st_mtime;
time_t mtime_secs = ap->mtime_days * 24*60*60;
if (ap->mtime_char == '+')
return file_age >= mtime_secs + 24*60*60;
if (ap->mtime_char == '-')
return file_age < mtime_secs;
/* just numeric mtime */
return file_age >= mtime_secs && file_age < (mtime_secs + 24*60*60);
}
#endif
#if ENABLE_FEATURE_FIND_MMIN
ACTF(mmin)
{
return time_cmp(statbuf,
# if ENABLE_FEATURE_FIND_ATIME || ENABLE_FEATURE_FIND_CTIME
(ap->time_type << 8) |
# endif
ap->mmin_char,
ap->mmin_mins, 60);
time_t file_age = time(NULL) - statbuf->st_mtime;
time_t mmin_secs = ap->mmin_mins * 60;
if (ap->mmin_char == '+')
return file_age >= mmin_secs + 60;
if (ap->mmin_char == '-')
return file_age < mmin_secs;
/* just numeric mmin */
return file_age >= mmin_secs && file_age < (mmin_secs + 60);
}
#endif
#if ENABLE_FEATURE_FIND_NEWER
@@ -742,13 +656,6 @@ ACTF(inum)
return (statbuf->st_ino == ap->inode_num);
}
#endif
#if ENABLE_FEATURE_FIND_SAMEFILE
ACTF(samefile)
{
return statbuf->st_ino == ap->inode_num &&
statbuf->st_dev == ap->device;
}
#endif
#if ENABLE_FEATURE_FIND_EXEC
static int do_exec(action_exec *ap, const char *fileName)
{
@@ -1136,14 +1043,9 @@ static action*** parse_params(char **argv)
IF_FEATURE_FIND_TYPE( PARM_type ,)
IF_FEATURE_FIND_PERM( PARM_perm ,)
IF_FEATURE_FIND_MTIME( PARM_mtime ,)
IF_FEATURE_FIND_ATIME( PARM_atime ,)
IF_FEATURE_FIND_CTIME( PARM_ctime ,)
IF_FEATURE_FIND_MMIN( PARM_mmin ,)
IF_FEATURE_FIND_AMIN( PARM_amin ,)
IF_FEATURE_FIND_CMIN( PARM_cmin ,)
IF_FEATURE_FIND_NEWER( PARM_newer ,)
IF_FEATURE_FIND_INUM( PARM_inum ,)
IF_FEATURE_FIND_SAMEFILE(PARM_samefile ,)
IF_FEATURE_FIND_USER( PARM_user ,)
IF_FEATURE_FIND_GROUP( PARM_group ,)
IF_FEATURE_FIND_SIZE( PARM_size ,)
@@ -1185,14 +1087,9 @@ static action*** parse_params(char **argv)
IF_FEATURE_FIND_TYPE( "-type\0" )
IF_FEATURE_FIND_PERM( "-perm\0" )
IF_FEATURE_FIND_MTIME( "-mtime\0" )
IF_FEATURE_FIND_ATIME( "-atime\0" )
IF_FEATURE_FIND_CTIME( "-ctime\0" )
IF_FEATURE_FIND_MMIN( "-mmin\0" )
IF_FEATURE_FIND_AMIN( "-amin\0" )
IF_FEATURE_FIND_CMIN( "-cmin\0" )
IF_FEATURE_FIND_NEWER( "-newer\0" )
IF_FEATURE_FIND_INUM( "-inum\0" )
IF_FEATURE_FIND_SAMEFILE("-samefile\0")
IF_FEATURE_FIND_USER( "-user\0" )
IF_FEATURE_FIND_GROUP( "-group\0" )
IF_FEATURE_FIND_SIZE( "-size\0" )
@@ -1476,39 +1373,19 @@ static action*** parse_params(char **argv)
}
#endif
#if ENABLE_FEATURE_FIND_MTIME
else if (parm == PARM_mtime
# if ENABLE_FEATURE_FIND_ATIME
|| parm == PARM_atime
# endif
# if ENABLE_FEATURE_FIND_CTIME
|| parm == PARM_ctime
# endif
) {
else if (parm == PARM_mtime) {
action_mtime *ap;
dbg("%d", __LINE__);
ap = ALLOC_ACTION(mtime);
# if ENABLE_FEATURE_FIND_AMIN || ENABLE_FEATURE_FIND_CMIN
ap->time_type = arg[1];
# endif
ap->mtime_char = arg1[0];
ap->mtime_days = xatoul(plus_minus_num(arg1));
}
#endif
#if ENABLE_FEATURE_FIND_MMIN
else if (parm == PARM_mmin
# if ENABLE_FEATURE_FIND_AMIN
|| parm == PARM_amin
# endif
# if ENABLE_FEATURE_FIND_CMIN
|| parm == PARM_cmin
# endif
) {
else if (parm == PARM_mmin) {
action_mmin *ap;
dbg("%d", __LINE__);
ap = ALLOC_ACTION(mmin);
# if ENABLE_FEATURE_FIND_AMIN || ENABLE_FEATURE_FIND_CMIN
ap->time_type = arg[1];
# endif
ap->mmin_char = arg1[0];
ap->mmin_mins = xatoul(plus_minus_num(arg1));
}
@@ -1531,21 +1408,6 @@ static action*** parse_params(char **argv)
ap->inode_num = xatoul(arg1);
}
#endif
#if ENABLE_FEATURE_FIND_SAMEFILE
else if (parm == PARM_samefile) {
action_samefile *ap;
struct stat stbuf;
dbg("%d", __LINE__);
if (G.recurse_flags & (ACTION_FOLLOWLINKS |
ACTION_FOLLOWLINKS_L0))
xstat(arg1, &stbuf);
else if (lstat(arg1, &stbuf))
bb_perror_msg_and_die("can't stat '%s'", arg1);
ap = ALLOC_ACTION(samefile);
ap->inode_num = stbuf.st_ino;
ap->device = stbuf.st_dev;
}
#endif
#if ENABLE_FEATURE_FIND_USER
else if (parm == PARM_user) {
action_user *ap;
+5 -3
View File
@@ -57,12 +57,14 @@
#include "common_bufsiz.h"
#include "xregex.h"
/* options */
//usage:#define grep_trivial_usage
//usage: "[-HhnlLoqvsrRiwFE"
//usage: IF_EXTRA_COMPAT("z")
//usage: "] [-m N] "
//usage: IF_FEATURE_GREP_CONTEXT("[-A|B|C N] ")
//usage: "{ PATTERN | -e PATTERN... | -f FILE... } [FILE]..."
//usage: IF_FEATURE_GREP_CONTEXT("[-A/B/C N] ")
//usage: "PATTERN/-e PATTERN.../-f FILE [FILE]..."
//usage:#define grep_full_usage "\n\n"
//usage: "Search for PATTERN in FILEs (or stdin)\n"
//usage: "\n -H Add 'filename:' prefix"
@@ -83,7 +85,7 @@
//usage: "\n -F PATTERN is a literal (not regexp)"
//usage: "\n -E PATTERN is an extended regexp"
//usage: IF_EXTRA_COMPAT(
//usage: "\n -z NUL terminated input"
//usage: "\n -z Input is NUL terminated"
//usage: )
//usage: "\n -m N Match up to N times per file"
//usage: IF_FEATURE_GREP_CONTEXT(
+1 -1
View File
@@ -537,7 +537,7 @@ static int xargs_ask_confirmation(void)
//usage:#define xargs_full_usage "\n\n"
//usage: "Run PROG on every item given by stdin\n"
//usage: IF_FEATURE_XARGS_SUPPORT_ZERO_TERM(
//usage: "\n -0 NUL terminated input"
//usage: "\n -0 Input is separated by NULs"
//usage: )
//usage: IF_FEATURE_XARGS_SUPPORT_ARGS_FILE(
//usage: "\n -a FILE Read from FILE instead of stdin"
+1 -1
View File
@@ -167,7 +167,6 @@ typedef struct tar_header_t { /* byte offset */
struct BUG_tar_header {
char c[sizeof(tar_header_t) == TAR_BLOCK_SIZE ? 1 : -1];
};
void chksum_and_xwrite_tar_header(int fd, struct tar_header_t *hp) FAST_FUNC;
extern const char cpio_TRAILER[];
@@ -195,6 +194,7 @@ char get_header_ar(archive_handle_t *archive_handle) FAST_FUNC;
char get_header_cpio(archive_handle_t *archive_handle) FAST_FUNC;
char get_header_tar(archive_handle_t *archive_handle) FAST_FUNC;
char get_header_tar_gz(archive_handle_t *archive_handle) FAST_FUNC;
char get_header_tar_xz(archive_handle_t *archive_handle) FAST_FUNC;
char get_header_tar_bz2(archive_handle_t *archive_handle) FAST_FUNC;
char get_header_tar_lzma(archive_handle_t *archive_handle) FAST_FUNC;
char get_header_tar_xz(archive_handle_t *archive_handle) FAST_FUNC;
+5 -18
View File
@@ -182,12 +182,11 @@ struct ext2_dx_countlimit {
#define EXT2_NOTAIL_FL 0x00008000 /* file tail should not be merged */
#define EXT2_DIRSYNC_FL 0x00010000 /* Synchronous directory modifications */
#define EXT2_TOPDIR_FL 0x00020000 /* Top of directory hierarchies*/
#define EXT2_EXTENT_FL 0x00080000 /* Extents */
#define EXT2_VERITY_FL 0x00100000
#define EXT2_NOCOW_FL 0x00800000 /* Do not cow file */
#define EXT2_INLINE_DATA_FL 0x10000000
#define EXT2_PROJINHERIT_FL 0x20000000
#define EXT2_CASEFOLD_FL 0x40000000
#define EXT3_EXTENTS_FL 0x00080000 /* Inode uses extents */
#define EXT2_RESERVED_FL 0x80000000 /* reserved for ext2 lib */
#define EXT2_FL_USER_VISIBLE 0x0003DFFF /* User visible flags */
#define EXT2_FL_USER_MODIFIABLE 0x000080FF /* User modifiable flags */
/*
* ioctl commands
@@ -196,18 +195,6 @@ struct ext2_dx_countlimit {
#define EXT2_IOC_SETFLAGS _IOW('f', 2, long)
#define EXT2_IOC_GETVERSION _IOR('v', 1, long)
#define EXT2_IOC_SETVERSION _IOW('v', 2, long)
//NB: despite "long" in defs above, these ioctls use an _int_!
//passing them a pointer to long will read/write only int-sized data!
struct ext2_fsxattr {
uint32_t fsx_xflags; /* xflags field value (get/set) */
uint32_t fsx_extsize; /* extsize field value (get/set)*/
uint32_t fsx_nextents; /* nextents field value (get) */
uint32_t fsx_projid; /* project identifier (get/set) */
uint32_t fsx_cowextsize; /* CoW extsize field value (get/set)*/
unsigned char fsx_pad[8];
};
#define EXT2_IOC_FSGETXATTR _IOR('X', 31, struct ext2_fsxattr)
#define EXT2_IOC_FSSETXATTR _IOW('X', 32, struct ext2_fsxattr)
/*
* Structure of an inode on the disk
+1 -3
View File
@@ -32,10 +32,8 @@ typedef struct dumper_t {
off_t dump_skip; /* bytes to skip */
int dump_length; /* max bytes to read */
smallint dump_vflag; /*enum dump_vflag_t*/
const char *eofstring;
FS *fshead;
const char *xxd_eofstring;
off_t address; /* address/offset in stream */
long long xxd_displayoff;
} dumper_t;
dumper_t* alloc_dumper(void) FAST_FUNC;
Loaded 100 of 370 files, more files were not shown because too many files have changed in this diff. Show more