Compare commits

..
Author SHA1 Message Date
Denys Vlasenko 0cf9e105e6 Bump version to 1.34.1
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-09-30 22:27:55 +02:00
Denys Vlasenko 0e0dd21497 awk: never return NULL from awk_printf()
function                                             old     new   delta
awk_printf                                           651     628     -23

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-09-30 00:15:44 +02:00
Denys Vlasenko 118baea06e awk: code shrink
function                                             old     new   delta
awk_printf                                           652     651      -1

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-09-30 00:15:44 +02:00
Denys Vlasenko 5ec12fa657 awk: code shrink: avoid duplicate NUL checks and strlen()
function                                             old     new   delta
awk_printf                                           665     652     -13

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-09-30 00:15:44 +02:00
Ron Yorston 150986c922 awk: fix read beyond end of buffer
Commit 7d06d6e18 (awk: fix printf %%) can cause awk printf to read
beyond the end of a strduped buffer:

  2349      while (*f && *f != '%')
  2350          f++;
  2351      c = *++f;

If the loop terminates because a NUL character is detected the
character after the NUL is read.  This can result in failures
depending on the value of that character.

function                                             old     new   delta
awk_printf                                           672     665      -7

Signed-off-by: Ron Yorston <rmy@pobox.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-09-30 00:15:44 +02:00
Denys Vlasenko 3c9f559a41 chat: hopefully fix infinite spinning on input EOF
function                                             old     new   delta
chat_main                                           1295    1303      +8

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-09-30 00:15:44 +02:00
Daniel Thau 9ea17d5a0a awk: fix printf %%
A refactor of the awk printf code in
e2e3802987
appears to have broken the printf interpretation of two percent signs,
which normally outputs only one percent sign.

The patch below brings busybox awk printf behavior back into alignment
with the pre-e2e380 behavior, the busybox printf util, and other common
(awk and non-awk) printf implementations.

function                                             old     new   delta
awk_printf                                           626     672     +46

Signed-off-by: Daniel Thau <danthau at bedrocklinux.org>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-09-30 00:15:44 +02:00
Ron Yorston 76ef439154 ash: regressions in process substitution
Stacy Harper reports that this script:

   test() { . /tmp/bb_test; }
   echo "export TEST=foo" >/tmp/bb_test
   test 2>/dev/null
   echo "$TEST"

correctly prints 'foo' in BusyBox 1.33 but hangs in 1.34.

Bisection suggested the problem was caused by commit a1b0d3856 (ash: add
process substitution in bash-compatibility mode).  Removing the call to
unwindredir() in cmdloop() introduced in that commit makes the script
work again.

Additionally, these examples of process substitution:

   while true; do cat <(echo hi); done
   f() { while true; do cat <(echo hi); done }
   f

result in running out of file descriptors.  This is a regression from
v5 of the process substitution patch caused by changes to evalcommand()
not being transferred to v6.

function                                             old     new   delta
static.pushredir                                       -      99     +99
evalcommand                                         1729    1750     +21
exitreset                                             69      86     +17
cmdloop                                              372     365      -7
unwindredir                                           28       -     -28
pushredir                                            112       -    -112
------------------------------------------------------------------------------
(add/remove: 1/2 grow/shrink: 2/1 up/down: 137/-147)          Total: -10 bytes

Signed-off-by: Ron Yorston <rmy@pobox.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-09-30 00:15:33 +02:00
Denys Vlasenko 00adcdb64a udhcp: fix build breakage on MIPS
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-08-20 13:35:54 +02:00
157 changed files with 2509 additions and 3792 deletions

No files matched your search

+2 -2
View File
@@ -1,6 +1,6 @@
VERSION = 1
PATCHLEVEL = 35
SUBLEVEL = 0
PATCHLEVEL = 34
SUBLEVEL = 1
EXTRAVERSION =
NAME = Unnamed
+2 -2
View File
@@ -151,8 +151,8 @@ LDLIBS += m
# 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;}' >bb_libtest.c; $(CC) $(CFLAGS) -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) -lrt -o /dev/null bb_libtest.c >/dev/null 2>&1 && echo "y"; rm bb_libtest.c)
ifeq ($(CRYPT_AVAILABLE),y)
LDLIBS += crypt
endif
+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);
-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));
}
+1 -53
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
+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];
+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));
+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;
+29 -2
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) {
+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
+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 -4
View File
@@ -88,12 +88,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 -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;
+11 -35
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))
@@ -119,16 +99,15 @@ int df_main(int argc UNUSED_PARAM, char **argv)
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_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_MEGA = (1 << (5 + 3*ENABLE_FEATURE_DF_FANCY)) * ENABLE_FEATURE_HUMAN_READABLE,
};
const char *disp_units_hdr = NULL;
char *chp, *opt_t;
@@ -145,7 +124,7 @@ int df_main(int argc UNUSED_PARAM, char **argv)
opt = getopt32(argv, "^"
"kPTt:"
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"
@@ -172,11 +151,8 @@ int df_main(int argc UNUSED_PARAM, char **argv)
got_it: ;
}
if (opt & (OPT_HUMAN|OPT_HUMANDEC)) {
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)
+1 -2
View File
@@ -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 */
+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) {
+1 -1
View File
@@ -313,7 +313,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;
}
+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);
}
+2 -4
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);
@@ -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,
+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;
}
+2 -4
View File
@@ -140,17 +140,15 @@ int touch_main(int argc UNUSED_PARAM, char **argv)
if (opts & (OPT_d|OPT_t)) {
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;
+1 -10
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));
}
+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"
+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
+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: "[-ls] 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;
+23 -28
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;
}
@@ -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;
}
+2 -1
View File
@@ -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':
+134 -190
View File
@@ -7,7 +7,7 @@
*/
//
//Things To Do:
// ./.exrc
// $HOME/.exrc and ./.exrc
// add magic to search /foo.*bar
// add :help command
// :map macros
@@ -185,7 +185,7 @@
//usage:#define vi_full_usage "\n\n"
//usage: "Edit FILE\n"
//usage: IF_FEATURE_VI_COLON(
//usage: "\n -c CMD Initial command to run ($EXINIT and ~/.exrc also available)"
//usage: "\n -c CMD Initial command to run ($EXINIT also available)"
//usage: )
//usage: IF_FEATURE_VI_READONLY(
//usage: "\n -R Read-only"
@@ -201,7 +201,6 @@
// the CRASHME code is unmaintained, and doesn't currently build
#define ENABLE_FEATURE_VI_CRASHME 0
#define IF_FEATURE_VI_CRASHME(...)
#if ENABLE_LOCALE_SUPPORT
@@ -404,7 +403,7 @@ struct globals {
int cindex; // saved character index for up/down motion
smallint keep_index; // retain saved character index
#if ENABLE_FEATURE_VI_COLON
llist_t *initial_cmds;
char *initial_cmds[3]; // currently 2 entries, NULL terminated
#endif
// Should be just enough to hold a key sequence,
// but CRASHME mode uses it as generated command buffer too
@@ -1377,14 +1376,21 @@ static void print_literal(char *buf, const char *s)
char *d;
unsigned char c;
buf[0] = '\0';
if (!s[0])
s = "(NULL)";
d = buf;
for (; *s; s++) {
int c_is_no_print;
c = *s;
if ((c & 0x80) && !Isprint(c))
c = '?';
c_is_no_print = (c & 0x80) && !Isprint(c);
if (c_is_no_print) {
strcpy(d, ESC_NORM_TEXT);
d += sizeof(ESC_NORM_TEXT)-1;
c = '.';
}
if (c < ' ' || c == 0x7f) {
*d++ = '^';
c |= '@'; // 0x40
@@ -1393,6 +1399,14 @@ static void print_literal(char *buf, const char *s)
}
*d++ = c;
*d = '\0';
if (c_is_no_print) {
strcpy(d, ESC_BOLD_TEXT);
d += sizeof(ESC_BOLD_TEXT)-1;
}
if (*s == '\n') {
*d++ = '$';
*d = '\0';
}
if (d - buf > MAX_INPUT_LEN - 10) // paranoia
break;
}
@@ -2458,38 +2472,26 @@ static char *char_search(char *p, const char *pat, int dir_and_range)
//----- The Colon commands -------------------------------------
#if ENABLE_FEATURE_VI_COLON
// Evaluate colon address expression. Returns a pointer to the
// next character or NULL on error. If 'result' contains a valid
// address 'valid' is TRUE.
static char *get_one_address(char *p, int *result, int *valid)
static char *get_one_address(char *p, int *result) // get colon addr, if present
{
int num, sign, addr, got_addr;
int st, num, sign, addr, new_addr;
# if ENABLE_FEATURE_VI_YANKMARK || ENABLE_FEATURE_VI_SEARCH
char *q, c;
# endif
IF_FEATURE_VI_SEARCH(int dir;)
got_addr = FALSE;
addr = count_lines(text, dot); // default to current line
addr = -1; // assume no addr
sign = 0;
for (;;) {
new_addr = -1;
if (isblank(*p)) {
if (got_addr) {
addr += sign;
sign = 0;
}
p++;
} else if (!got_addr && *p == '.') { // the current line
} else if (*p == '.') { // the current line
p++;
//addr = count_lines(text, dot);
got_addr = TRUE;
} else if (!got_addr && *p == '$') { // the last line in file
p++;
addr = count_lines(text, end - 1);
got_addr = TRUE;
new_addr = count_lines(text, dot);
}
# if ENABLE_FEATURE_VI_YANKMARK
else if (!got_addr && *p == '\'') { // is this a mark addr
else if (*p == '\'') { // is this a mark addr
p++;
c = tolower(*p);
p++;
@@ -2499,16 +2501,13 @@ static char *get_one_address(char *p, int *result, int *valid)
c = c - 'a';
q = mark[(unsigned char) c];
}
if (q == NULL) { // is mark valid
status_line_bold("Mark not set");
if (q == NULL) // is mark valid
return NULL;
}
addr = count_lines(text, q);
got_addr = TRUE;
new_addr = count_lines(text, q);
}
# endif
# if ENABLE_FEATURE_VI_SEARCH
else if (!got_addr && (*p == '/' || *p == '?')) { // a search pattern
else if (*p == '/' || *p == '?') { // a search pattern
c = *p;
q = strchrnul(p + 1, c);
if (p + 1 != q) {
@@ -2527,45 +2526,39 @@ static char *get_one_address(char *p, int *result, int *valid)
dir = ((unsigned)BACK << 1) | FULL;
}
q = char_search(q, last_search_pattern + 1, dir);
if (q == NULL) {
// no match, continue from other end of file
q = char_search(dir > 0 ? text : end - 1,
last_search_pattern + 1, dir);
if (q == NULL) {
status_line_bold("Pattern not found");
return NULL;
}
}
addr = count_lines(text, q);
got_addr = TRUE;
if (q == NULL)
return NULL;
new_addr = count_lines(text, q);
}
# endif
else if (isdigit(*p)) {
num = 0;
while (isdigit(*p))
num = num * 10 + *p++ -'0';
if (!got_addr) { // specific line number
else if (*p == '$') { // the last line in file
p++;
new_addr = count_lines(text, end - 1);
} else if (isdigit(*p)) {
sscanf(p, "%d%n", &num, &st);
p += st;
if (addr < 0) { // specific line number
addr = num;
got_addr = TRUE;
} else { // offset from current addr
addr += sign >= 0 ? num : -num;
}
sign = 0;
} else if (*p == '-' || *p == '+') {
if (!got_addr) { // default address is dot
//addr = count_lines(text, dot);
got_addr = TRUE;
} else {
addr += sign;
}
sign = *p++ == '-' ? -1 : 1;
if (addr < 0) { // default address is dot
addr = count_lines(text, dot);
}
} else {
addr += sign; // consume unused trailing sign
break;
}
if (new_addr >= 0) {
if (addr >= 0) // only one new address per expression
return NULL;
addr = new_addr;
}
}
*result = addr;
*valid = got_addr;
return p;
}
@@ -2574,40 +2567,34 @@ static char *get_one_address(char *p, int *result, int *valid)
// Read line addresses for a colon command. The user can enter as
// many as they like but only the last two will be used.
static char *get_address(char *p, int *b, int *e, unsigned int *got)
static char *get_address(char *p, int *b, int *e)
{
int state = GET_ADDRESS;
int valid;
int addr;
char *save_dot = dot;
//----- get the address' i.e., 1,3 'a,'b -----
for (;;) {
if (isblank(*p)) {
p++;
} else if (state == GET_ADDRESS && *p == '%') { // alias for 1,$
} else if (*p == '%' && state == GET_ADDRESS) { // alias for 1,$
p++;
*b = 1;
*e = count_lines(text, end-1);
*got = 3;
state = GET_SEPARATOR;
} else if (state == GET_ADDRESS) {
valid = FALSE;
p = get_one_address(p, &addr, &valid);
// Quit on error or if the address is invalid and isn't of
// the form ',$' or '1,' (in which case it defaults to dot).
if (p == NULL || !(valid || *p == ',' || *p == ';' || *got & 1))
break;
*b = *e;
*e = addr;
*got = (*got << 1) | 1;
state = GET_SEPARATOR;
} else if (state == GET_SEPARATOR && (*p == ',' || *p == ';')) {
if (*p == ';')
dot = find_line(*e);
p++;
*b = *e;
state = GET_ADDRESS;
} else if (state == GET_ADDRESS) {
p = get_one_address(p, e);
if (p == NULL)
break;
state = GET_SEPARATOR;
} else {
if (state == GET_SEPARATOR && *b >= 0 && *e < 0)
*e = count_lines(text, dot);
break;
}
}
@@ -2821,14 +2808,9 @@ static void colon(char *buf)
not_implemented(p);
#else
// check how many addresses we got
# define GOT_ADDRESS (got & 1)
# define GOT_RANGE ((got & 3) == 3)
char c, *buf1, *q, *r;
char *fn, cmd[MAX_INPUT_LEN], *cmdend, *args, *exp = NULL;
int i, l, li, b, e;
unsigned int got;
int useforce;
// :3154 // if (-e line 3154) goto it else stay put
@@ -2846,22 +2828,21 @@ static void colon(char *buf)
// :!<cmd> // run <cmd> then return
//
while (*buf == ':')
buf++; // move past leading colons
while (isblank(*buf))
buf++; // move past leading blanks
if (!buf[0] || buf[0] == '"')
goto ret; // ignore empty lines or those starting with '"'
if (!buf[0])
goto ret;
if (*buf == ':')
buf++; // move past the ':'
li = i = 0;
b = e = -1;
got = 0;
li = count_lines(text, end - 1);
fn = current_filename;
// look for optional address(es) :. :1 :1,9 :'q,'a :%
buf = get_address(buf, &b, &e, &got);
buf1 = buf;
buf = get_address(buf, &b, &e);
if (buf == NULL) {
status_line_bold("Bad address: %s", buf1);
goto ret;
}
@@ -2884,17 +2865,13 @@ static void colon(char *buf)
}
// assume the command will want a range, certain commands
// (read, substitute) need to adjust these assumptions
if (!GOT_ADDRESS) {
if (e < 0) {
q = text; // no addr, use 1,$ for the range
r = end - 1;
} else {
// at least one addr was given, get its details
if (e < 0 || e > li) {
status_line_bold("Invalid range");
goto ret;
}
q = r = find_line(e);
if (!GOT_RANGE) {
if (b < 0) {
// if there is only one addr, then it's the line
// number of the single line the user wants.
// Reset the end pointer to the end of that line.
@@ -2903,10 +2880,6 @@ static void colon(char *buf)
} else {
// we were given two addrs. change the
// start pointer to the addr given by user.
if (b < 0 || b > li || b > e) {
status_line_bold("Invalid range");
goto ret;
}
q = find_line(b); // what line is #b
r = end_line(r);
li = e - b + 1;
@@ -2937,12 +2910,12 @@ static void colon(char *buf)
}
# endif
else if (cmd[0] == '=' && !cmd[1]) { // where is the address
if (!GOT_ADDRESS) { // no addr given- use defaults
if (e < 0) { // no addr given- use defaults
e = count_lines(text, dot);
}
status_line("%d", e);
} else if (strncmp(cmd, "delete", i) == 0) { // delete lines
if (!GOT_ADDRESS) { // no addr given- use defaults
if (e < 0) { // no addr given- use defaults
q = begin_line(dot); // assume .,. for the range
r = end_line(dot);
}
@@ -3014,7 +2987,7 @@ static void colon(char *buf)
rawmode();
Hit_Return();
} else if (strncmp(cmd, "list", i) == 0) { // literal print line
if (!GOT_ADDRESS) { // no addr given- use defaults
if (e < 0) { // no addr given- use defaults
q = begin_line(dot); // assume .,. for the range
r = end_line(dot);
}
@@ -3097,7 +3070,7 @@ static void colon(char *buf)
if (e == 0) { // user said ":0r foo"
q = text;
} else { // read after given line or current line if none given
q = next_line(GOT_ADDRESS ? find_line(e) : dot);
q = next_line(e > 0 ? find_line(e) : dot);
// read after last line
if (q == end-1)
++q;
@@ -3218,11 +3191,11 @@ static void colon(char *buf)
len_F = strlen(F);
}
if (!GOT_ADDRESS) { // no addr given
if (e < 0) { // no addr given
q = begin_line(dot); // start with cur line
r = end_line(dot);
b = e = count_lines(text, q); // cur line number
} else if (!GOT_RANGE) { // one addr given
} else if (b < 0) { // one addr given
b = e;
}
@@ -3393,7 +3366,7 @@ static void colon(char *buf)
}
# if ENABLE_FEATURE_VI_YANKMARK
} else if (strncmp(cmd, "yank", i) == 0) { // yank lines
if (!GOT_ADDRESS) { // no addr given- use defaults
if (b < 0) { // no addr given- use defaults
q = begin_line(dot); // assume .,. for the range
r = end_line(dot);
}
@@ -4116,8 +4089,8 @@ static void do_cmd(int c)
#endif
}
}
} else if (/* c == '>' && */ p != end_line(p)) {
// shift right -- add tab or tabstop spaces on non-empty lines
} else /* if (c == '>') */ {
// shift right -- add tab or tabstop spaces
char_insert(p, '\t', allow_undo);
}
#if ENABLE_FEATURE_VI_UNDO
@@ -4735,21 +4708,6 @@ static void crash_test()
}
#endif
#if ENABLE_FEATURE_VI_COLON
static void run_cmds(char *p)
{
while (p) {
char *q = p;
p = strchr(q, '\n');
if (p)
while (*p == '\n')
*p++ = '\0';
if (strlen(q) < MAX_INPUT_LEN)
colon(q);
}
}
#endif
static void edit_file(char *fn)
{
#if ENABLE_FEATURE_VI_YANKMARK
@@ -4820,8 +4778,25 @@ static void edit_file(char *fn)
#endif
#if ENABLE_FEATURE_VI_COLON
while (initial_cmds)
run_cmds((char *)llist_pop(&initial_cmds));
{
char *p, *q;
int n = 0;
while ((p = initial_cmds[n]) != NULL) {
do {
q = p;
p = strchr(q, '\n');
if (p)
while (*p == '\n')
*p++ = '\0';
if (*q)
colon(q);
} while (p);
free(initial_cmds[n]);
initial_cmds[n] = NULL;
n++;
}
}
#endif
redraw(FALSE); // dont force every col re-draw
//------This is the main Vi cmd handling loop -----------------------
@@ -4884,29 +4859,10 @@ static void edit_file(char *fn)
#undef cur_line
}
#define VI_OPTSTR \
IF_FEATURE_VI_CRASHME("C") \
IF_FEATURE_VI_COLON("c:*") \
"Hh" \
IF_FEATURE_VI_READONLY("R")
enum {
IF_FEATURE_VI_CRASHME(OPTBIT_C,)
IF_FEATURE_VI_COLON(OPTBIT_c,)
OPTBIT_H,
OPTBIT_h,
IF_FEATURE_VI_READONLY(OPTBIT_R,)
OPT_C = IF_FEATURE_VI_CRASHME( (1 << OPTBIT_C)) + 0,
OPT_c = IF_FEATURE_VI_COLON( (1 << OPTBIT_c)) + 0,
OPT_H = 1 << OPTBIT_H,
OPT_h = 1 << OPTBIT_h,
OPT_R = IF_FEATURE_VI_READONLY( (1 << OPTBIT_R)) + 0,
};
int vi_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
int vi_main(int argc, char **argv)
{
int opts;
int c;
INIT_G();
@@ -4930,62 +4886,50 @@ int vi_main(int argc, char **argv)
// 0: all of our options are disabled by default in vim
//vi_setops = 0;
opts = getopt32(argv, VI_OPTSTR IF_FEATURE_VI_COLON(, &initial_cmds));
#if ENABLE_FEATURE_VI_CRASHME
if (opts & OPT_C)
crashme = 1;
// 1- process EXINIT variable from environment
// 2- if EXINIT is unset process $HOME/.exrc file (not inplemented yet)
// 3- process command line args
#if ENABLE_FEATURE_VI_COLON
{
char *p = getenv("EXINIT");
if (p && *p)
initial_cmds[0] = xstrndup(p, MAX_INPUT_LEN);
}
#endif
if (opts & OPT_R)
SET_READONLY_MODE(readonly_mode);
if (opts & OPT_H)
show_help();
if (opts & (OPT_H | OPT_h)) {
bb_show_usage();
return 1;
while ((c = getopt(argc, argv,
#if ENABLE_FEATURE_VI_CRASHME
"C"
#endif
"RHh" IF_FEATURE_VI_COLON("c:"))) != -1) {
switch (c) {
#if ENABLE_FEATURE_VI_CRASHME
case 'C':
crashme = 1;
break;
#endif
#if ENABLE_FEATURE_VI_READONLY
case 'R': // Read-only flag
SET_READONLY_MODE(readonly_mode);
break;
#endif
#if ENABLE_FEATURE_VI_COLON
case 'c': // cmd line vi command
if (*optarg)
initial_cmds[initial_cmds[0] != NULL] = xstrndup(optarg, MAX_INPUT_LEN);
break;
#endif
case 'H':
show_help();
// fall through
default:
bb_show_usage();
return 1;
}
}
argv += optind;
cmdline_filecnt = argc - optind;
// 1- process EXINIT variable from environment
// 2- if EXINIT is unset process $HOME/.exrc file
// 3- process command line args
#if ENABLE_FEATURE_VI_COLON
{
const char *exinit = getenv("EXINIT");
char *cmds = NULL;
if (exinit) {
cmds = xstrdup(exinit);
} else {
const char *home = getenv("HOME");
if (home && *home) {
char *exrc = concat_path_file(home, ".exrc");
struct stat st;
// .exrc must belong to and only be writable by user
if (stat(exrc, &st) == 0) {
if ((st.st_mode & (S_IWGRP|S_IWOTH)) == 0
&& st.st_uid == getuid()
) {
cmds = xmalloc_open_read_close(exrc, NULL);
} else {
status_line_bold(".exrc: permission denied");
}
}
free(exrc);
}
}
if (cmds) {
init_text_buffer(NULL);
run_cmds(cmds);
free(cmds);
}
}
#endif
// "Save cursor, use alternate screen buffer, clear screen"
write1(ESC"[?1049h");
// This is the main file handling loop
+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;
+1 -1
View File
@@ -83,7 +83,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;
+32 -54
View File
@@ -305,13 +305,9 @@ typedef unsigned long long uoff_t;
# endif
#else
/* CONFIG_LFS is off */
/* sizeof(off_t) == sizeof(long).
* May or may not be == sizeof(int). If it is, use xatoi_positive()
* and bb_strtou() instead of xatoul_range() and bb_strtoul().
* Even if sizeof(off_t) == sizeof(int), off_t is typedef'ed to long anyway.
* gcc will throw warnings on printf("%d", off_t)... Have to use %ld etc.
*/
# if UINT_MAX == ULONG_MAX
# if UINT_MAX == 0xffffffff
/* While sizeof(off_t) == sizeof(int), off_t is typedef'ed to long anyway.
* gcc will throw warnings on printf("%d", off_t). Crap... */
typedef unsigned long uoff_t;
# define XATOOFF(a) xatoi_positive(a)
# define BB_STRTOOFF bb_strtou
@@ -369,27 +365,13 @@ struct BUG_off_t_size_is_misdetected {
#endif
#endif
/* We use a trick to have more optimized code (fewer pointer reloads
* and reduced binary size by a few kilobytes) like:
* ash.c: extern struct globals *const ash_ptr_to_globals;
* ash_ptr_hack.c: struct globals *ash_ptr_to_globals;
* This way, compiler in ash.c knows the pointer can not change.
*
* However, this may break on weird arches or toolchains. In this case,
* set "-DBB_GLOBAL_CONST=''" in CONFIG_EXTRA_CFLAGS to disable
* this optimization.
*/
#ifndef BB_GLOBAL_CONST
# define BB_GLOBAL_CONST const
#endif
#if defined(errno)
/* If errno is a define, assume it's "define errno (*__errno_location())"
* and we will cache it's result in this variable */
extern int *BB_GLOBAL_CONST bb_errno;
# undef errno
# define errno (*bb_errno)
# define bb_cached_errno_ptr 1
extern int *const bb_errno;
#undef errno
#define errno (*bb_errno)
#define bb_cached_errno_ptr 1
#endif
#if !(ULONG_MAX > 0xffffffff)
@@ -458,8 +440,9 @@ void *xmmap_anon(size_t size) FAST_FUNC;
# define cached_pagesize(var) (var)
#endif
/* Generate ls-style "mode string" like "-rwsr-xr-x" or "drwxrwxrwt" */
extern char *bb_mode_string(char buf[11], mode_t mode) FAST_FUNC;
//TODO: supply a pointer to char[11] buffer (avoid statics)?
extern const char *bb_mode_string(mode_t mode) FAST_FUNC;
extern int is_directory(const char *name, int followLinks) FAST_FUNC;
enum { /* cp.c, mv.c, install.c depend on these values. CAREFUL when changing them! */
FILEUTILS_PRESERVE_STATUS = 1 << 0, /* -p */
@@ -578,7 +561,7 @@ DIR *xopendir(const char *path) FAST_FUNC;
DIR *warn_opendir(const char *path) FAST_FUNC;
char *xmalloc_realpath(const char *path) FAST_FUNC RETURNS_MALLOC;
char *xmalloc_realpath_coreutils(char *path) FAST_FUNC RETURNS_MALLOC;
char *xmalloc_realpath_coreutils(const char *path) FAST_FUNC RETURNS_MALLOC;
char *xmalloc_readlink(const char *path) FAST_FUNC RETURNS_MALLOC;
char *xmalloc_readlink_or_warn(const char *path) FAST_FUNC RETURNS_MALLOC;
/* !RETURNS_MALLOC: it's a realloc-like function */
@@ -707,7 +690,7 @@ struct BUG_too_small {
};
int parse_datestr(const char *date_str, struct tm *ptm) FAST_FUNC;
void parse_datestr(const char *date_str, struct tm *ptm) FAST_FUNC;
time_t validate_tm_time(const char *date_str, struct tm *ptm) FAST_FUNC;
char *strftime_HHMMSS(char *buf, unsigned len, time_t *tp) FAST_FUNC;
char *strftime_YYYYMMDDHHMMSS(char *buf, unsigned len, time_t *tp) FAST_FUNC;
@@ -1271,10 +1254,8 @@ void run_applet_no_and_exit(int a, const char *name, char **argv) NORETURN FAST_
#endif
void show_usage_if_dash_dash_help(int applet_no, char **argv) FAST_FUNC;
#if defined(__linux__)
int re_execed_comm(void) FAST_FUNC;
void set_task_comm(const char *comm) FAST_FUNC;
#else
# define re_execed_comm() 0
# define set_task_comm(name) ((void)0)
#endif
@@ -1502,8 +1483,16 @@ int scripted_main(int argc, char** argv) MAIN_EXTERNALLY_VISIBLE;
/* Applets which are useful from another applets */
int bb_cat(char** argv) FAST_FUNC;
int ash_main(int argc, char** argv) IF_SHELL_ASH(MAIN_EXTERNALLY_VISIBLE);
int hush_main(int argc, char** argv) IF_SHELL_HUSH(MAIN_EXTERNALLY_VISIBLE);
int ash_main(int argc, char** argv)
#if ENABLE_ASH || ENABLE_SH_IS_ASH || ENABLE_BASH_IS_ASH
MAIN_EXTERNALLY_VISIBLE
#endif
;
int hush_main(int argc, char** argv)
#if ENABLE_HUSH || ENABLE_SH_IS_HUSH || ENABLE_BASH_IS_HUSH
MAIN_EXTERNALLY_VISIBLE
#endif
;
/* If shell needs them, they exist even if not enabled as applets */
int echo_main(int argc, char** argv) IF_ECHO(MAIN_EXTERNALLY_VISIBLE);
int printf_main(int argc, char **argv) IF_PRINTF(MAIN_EXTERNALLY_VISIBLE);
@@ -1618,7 +1607,7 @@ char *bb_ask_noecho_stdin(const char *prompt) FAST_FUNC;
int bb_ask_y_confirmation_FILE(FILE *fp) FAST_FUNC;
int bb_ask_y_confirmation(void) FAST_FUNC;
/* Returns -1 if input is invalid. cur_mode is a base for e.g. "u+rw" */
/* Returns -1 if input is invalid. current_mode is a base for e.g. "u+rw" */
int bb_parse_mode(const char* s, unsigned cur_mode) FAST_FUNC;
/*
@@ -2274,7 +2263,6 @@ extern const char bb_PATH_root_path[] ALIGN1; /* BB_PATH_ROOT_PATH */
extern const int const_int_0;
//extern const int const_int_1;
/* This struct is deliberately not defined. */
/* See docs/keep_data_small.txt */
struct globals;
@@ -2283,8 +2271,6 @@ struct globals;
* If you want to assign a value, use SET_PTR_TO_GLOBALS(x) */
extern struct globals *const ptr_to_globals;
#define barrier() asm volatile ("":::"memory")
#if defined(__clang_major__) && __clang_major__ >= 9
/* Clang/llvm drops assignment to "constant" storage. Silently.
* Needs serious convincing to not eliminate the store.
@@ -2292,38 +2278,30 @@ extern struct globals *const ptr_to_globals;
static ALWAYS_INLINE void* not_const_pp(const void *p)
{
void *pp;
asm volatile (
__asm__ __volatile__(
"# forget that p points to const"
: /*outputs*/ "=r" (pp)
: /*inputs*/ "0" (p)
);
return pp;
}
# define ASSIGN_CONST_PTR(pptr, v) do { \
*(void**)not_const_pp(pptr) = (void*)(v); \
barrier(); \
} while (0)
/* XZALLOC_CONST_PTR() is an out-of-line function to prevent
* clang from reading pointer before it is assigned.
*/
void XZALLOC_CONST_PTR(const void *pptr, size_t size) FAST_FUNC;
#else
# define ASSIGN_CONST_PTR(pptr, v) do { \
*(void**)(pptr) = (void*)(v); \
/* At least gcc 3.4.6 on mipsel needs optimization barrier */ \
barrier(); \
} while (0)
# define XZALLOC_CONST_PTR(pptr, size) ASSIGN_CONST_PTR(pptr, xzalloc(size))
static ALWAYS_INLINE void* not_const_pp(const void *p) { return (void*)p; }
#endif
#define SET_PTR_TO_GLOBALS(x) ASSIGN_CONST_PTR(&ptr_to_globals, x)
/* At least gcc 3.4.6 on mipsel system needs optimization barrier */
#define barrier() __asm__ __volatile__("":::"memory")
#define SET_PTR_TO_GLOBALS(x) do { \
(*(struct globals**)not_const_pp(&ptr_to_globals)) = (void*)(x); \
barrier(); \
} while (0)
#define FREE_PTR_TO_GLOBALS() do { \
if (ENABLE_FEATURE_CLEAN_UP) { \
free(ptr_to_globals); \
} \
} while (0)
/* You can change LIBBB_DEFAULT_LOGIN_SHELL, but don't use it,
* use bb_default_login_shell and following defines.
* If you change LIBBB_DEFAULT_LOGIN_SHELL,
-2
View File
@@ -239,7 +239,6 @@ typedef uint64_t bb__aliased_uint64_t FIX_ALIASING;
# define move_from_unaligned_long(v, longp) ((v) = *(bb__aliased_long*)(longp))
# define move_from_unaligned16(v, u16p) ((v) = *(bb__aliased_uint16_t*)(u16p))
# define move_from_unaligned32(v, u32p) ((v) = *(bb__aliased_uint32_t*)(u32p))
# define move_from_unaligned64(v, u64p) ((v) = *(bb__aliased_uint64_t*)(u64p))
# define move_to_unaligned16(u16p, v) (*(bb__aliased_uint16_t*)(u16p) = (v))
# define move_to_unaligned32(u32p, v) (*(bb__aliased_uint32_t*)(u32p) = (v))
# define move_to_unaligned64(u64p, v) (*(bb__aliased_uint64_t*)(u64p) = (v))
@@ -251,7 +250,6 @@ typedef uint64_t bb__aliased_uint64_t FIX_ALIASING;
# define move_from_unaligned_long(v, longp) (memcpy(&(v), (longp), sizeof(long)))
# define move_from_unaligned16(v, u16p) (memcpy(&(v), (u16p), 2))
# define move_from_unaligned32(v, u32p) (memcpy(&(v), (u32p), 4))
# define move_from_unaligned64(v, u64p) (memcpy(&(v), (u64p), 8))
# define move_to_unaligned16(u16p, v) do { \
uint16_t __t = (v); \
memcpy((u16p), &__t, 2); \
-3
View File
@@ -31,9 +31,6 @@
# define ADJTIME_PATH "/etc/adjtime"
#endif
#define STR1(s) #s
#define STR(s) STR1(s)
INSERT
#define busybox_notes_usage \
+113 -61
View File
@@ -61,73 +61,32 @@ config SHA3_SMALL
64-bit x86: +270 bytes of code, 45% faster
32-bit x86: +450 bytes of code, 75% faster
config FEATURE_NON_POSIX_CP
bool "Non-POSIX, but safer, copying to special nodes"
default y
config FEATURE_FAST_TOP
bool "Faster /proc scanning code (+100 bytes)"
default n # all "fast or small" options default to small
help
With this option, "cp file symlink" will delete symlink
and create a regular file. This does not conform to POSIX,
but prevents a symlink attack.
Similarly, "cp file device" will not send file's data
to the device. (To do that, use "cat file >device")
This option makes top and ps ~20% faster (or 20% less CPU hungry),
but code size is slightly bigger.
config FEATURE_VERBOSE_CP_MESSAGE
bool "Give more precise messages when copy fails (cp, mv etc)"
config FEATURE_ETC_NETWORKS
bool "Support /etc/networks"
default n
help
Error messages with this feature enabled:
Enable support for network names in /etc/networks. This is
a rarely used feature which allows you to use names
instead of IP/mask pairs in route command.
$ cp file /does_not_exist/file
cp: cannot create '/does_not_exist/file': Path does not exist
$ cp file /vmlinuz/file
cp: cannot stat '/vmlinuz/file': Path has non-directory component
If this feature is not enabled, they will be, respectively:
cp: cannot create '/does_not_exist/file': No such file or directory
cp: cannot stat '/vmlinuz/file': Not a directory
This will cost you ~60 bytes.
config FEATURE_USE_SENDFILE
bool "Use sendfile system call"
default y
config FEATURE_ETC_SERVICES
bool "Consult /etc/services even for well-known ports"
default n
help
When enabled, busybox will use the kernel sendfile() function
instead of read/write loops to copy data between file descriptors
(for example, cp command does this a lot).
If sendfile() doesn't work, copying code falls back to read/write
loop. sendfile() was originally implemented for faster I/O
from files to sockets, but since Linux 2.6.33 it was extended
to work for many more file types.
config FEATURE_COPYBUF_KB
int "Copy buffer size, in kilobytes"
range 1 1024
default 4
help
Size of buffer used by cp, mv, install, wget etc.
Buffers which are 4 kb or less will be allocated on stack.
Bigger buffers will be allocated with mmap, with fallback to 4 kb
stack buffer if mmap fails.
config MONOTONIC_SYSCALL
bool "Use clock_gettime(CLOCK_MONOTONIC) syscall"
default y
help
Use clock_gettime(CLOCK_MONOTONIC) syscall for measuring
time intervals (time, ping, traceroute etc need this).
Probably requires Linux 2.6+. If not selected, gettimeofday
will be used instead (which gives wrong results if date/time
is reset).
config IOCTL_HEX2STR_ERROR
bool "Use ioctl names rather than hex values in error messages"
default y
help
Use ioctl names rather than hex values in error messages
(e.g. VT_DISALLOCATE rather than 0x5608). If disabled this
saves about 1400 bytes.
Look up e.g. "telnet" and "http" in /etc/services file
instead of assuming ports 23 and 80.
This is almost never necessary (everybody uses standard ports),
and it makes sense to avoid reading this file.
If you disable this option, in the cases where port is explicitly
specified as a service name (e.g. "telnet HOST PORTNAME"),
it will still be looked up in /etc/services.
config FEATURE_EDITING
bool "Command line editing"
@@ -343,3 +302,96 @@ config UNICODE_PRESERVE_BROKEN
For example, this means that entering 'l', 's', ' ', 0xff, [Enter]
at shell prompt will list file named 0xff (single char name
with char value 255), not file named '?'.
config FEATURE_NON_POSIX_CP
bool "Non-POSIX, but safer, copying to special nodes"
default y
help
With this option, "cp file symlink" will delete symlink
and create a regular file. This does not conform to POSIX,
but prevents a symlink attack.
Similarly, "cp file device" will not send file's data
to the device. (To do that, use "cat file >device")
config FEATURE_VERBOSE_CP_MESSAGE
bool "Give more precise messages when copy fails (cp, mv etc)"
default n
help
Error messages with this feature enabled:
$ cp file /does_not_exist/file
cp: cannot create '/does_not_exist/file': Path does not exist
$ cp file /vmlinuz/file
cp: cannot stat '/vmlinuz/file': Path has non-directory component
If this feature is not enabled, they will be, respectively:
cp: cannot create '/does_not_exist/file': No such file or directory
cp: cannot stat '/vmlinuz/file': Not a directory
This will cost you ~60 bytes.
config FEATURE_USE_SENDFILE
bool "Use sendfile system call"
default y
help
When enabled, busybox will use the kernel sendfile() function
instead of read/write loops to copy data between file descriptors
(for example, cp command does this a lot).
If sendfile() doesn't work, copying code falls back to read/write
loop. sendfile() was originally implemented for faster I/O
from files to sockets, but since Linux 2.6.33 it was extended
to work for many more file types.
config FEATURE_COPYBUF_KB
int "Copy buffer size, in kilobytes"
range 1 1024
default 4
help
Size of buffer used by cp, mv, install, wget etc.
Buffers which are 4 kb or less will be allocated on stack.
Bigger buffers will be allocated with mmap, with fallback to 4 kb
stack buffer if mmap fails.
config FEATURE_SKIP_ROOTFS
bool "Skip rootfs in mount table"
default y
help
Ignore rootfs entry in mount table.
In Linux, kernel has a special filesystem, rootfs, which is initially
mounted on /. It contains initramfs data, if kernel is configured
to have one. Usually, another file system is mounted over / early
in boot process, and therefore most tools which manipulate
mount table, such as df, will skip rootfs entry.
However, some systems do not mount anything on /.
If you need to configure busybox for one of these systems,
you may find it useful to turn this option off to make df show
initramfs statistics.
Otherwise, choose Y.
config MONOTONIC_SYSCALL
bool "Use clock_gettime(CLOCK_MONOTONIC) syscall"
default y
help
Use clock_gettime(CLOCK_MONOTONIC) syscall for measuring
time intervals (time, ping, traceroute etc need this).
Probably requires Linux 2.6+. If not selected, gettimeofday
will be used instead (which gives wrong results if date/time
is reset).
config IOCTL_HEX2STR_ERROR
bool "Use ioctl names rather than hex values in error messages"
default y
help
Use ioctl names rather than hex values in error messages
(e.g. VT_DISALLOCATE rather than 0x5608). If disabled this
saves about 1400 bytes.
config FEATURE_HWIB
bool "Support infiniband HW"
default y
help
Support for printing infiniband addresses in network applets.
-1
View File
@@ -24,7 +24,6 @@ lib-y += chomp.o
lib-y += compare_string_array.o
lib-y += concat_path_file.o
lib-y += concat_subpath_file.o
lib-y += const_hack.o
lib-y += copy_file.o
lib-y += copyfd.o
lib-y += crc32.o
+9 -14
View File
@@ -247,7 +247,8 @@ void lbb_prepare(const char *applet
IF_FEATURE_INDIVIDUAL(, char **argv))
{
#ifdef bb_cached_errno_ptr
ASSIGN_CONST_PTR(&bb_errno, get_perrno());
(*(int **)not_const_pp(&bb_errno)) = get_perrno();
barrier();
#endif
applet_name = applet;
@@ -725,9 +726,9 @@ int scripted_main(int argc UNUSED_PARAM, char **argv)
int script = find_script_by_name(applet_name);
if (script >= 0)
# if ENABLE_SHELL_ASH
return ash_main(-script - 1, argv);
exit(ash_main(-script - 1, argv));
# elif ENABLE_SHELL_HUSH
return hush_main(-script - 1, argv);
exit(hush_main(-script - 1, argv));
# else
return 1;
# endif
@@ -1004,10 +1005,10 @@ int scripted_main(int argc UNUSED_PARAM, char **argv)
{
# if ENABLE_SHELL_ASH
int script = 0;
return ash_main(-script - 1, argv);
exit(ash_main(-script - 1, argv));
# elif ENABLE_SHELL_HUSH
int script = 0;
return hush_main(-script - 1, argv);
exit(hush_main(-script - 1, argv));
# else
return 1;
# endif
@@ -1093,7 +1094,7 @@ int main(int argc UNUSED_PARAM, char **argv)
full_write2_str(bb_basename(argv[0]));
full_write2_str(": no applets enabled\n");
return 127;
exit(127);
#else
@@ -1112,14 +1113,8 @@ int main(int argc UNUSED_PARAM, char **argv)
|| ENABLE_FEATURE_PREFER_APPLETS
|| !BB_MMU
) {
if (NUM_APPLETS > 1) {
/* Careful, do not trash comm of "SCRIPT.sh" -
* the case when started from e.g. #!/bin/ash script.
* (not limited to shells - #!/bin/awk scripts also exist)
*/
if (re_execed_comm())
set_task_comm(applet_name);
}
if (NUM_APPLETS > 1)
set_task_comm(applet_name);
}
parse_config_file(); /* ...maybe, if FEATURE_SUID_CONFIG */
-16
View File
@@ -1,16 +0,0 @@
/* vi: set sw=4 ts=4: */
/*
* Trick to assign a const ptr with barrier for clang
*
* Copyright (C) 2021 by YU Jincheng <shana@zju.edu.cn>
*
* Licensed under GPLv2 or later, see file LICENSE in this source tree.
*/
#include "libbb.h"
#if defined(__clang_major__) && __clang_major__ >= 9
void FAST_FUNC XZALLOC_CONST_PTR(const void *pptr, size_t size)
{
ASSIGN_CONST_PTR(pptr, xzalloc(size));
}
#endif
+1 -1
View File
@@ -532,7 +532,7 @@ static void conv_u(PR *pr, unsigned char *p)
}
}
static NOINLINE void display(priv_dumper_t* dumper)
static void display(priv_dumper_t* dumper)
{
unsigned char *bp;
unsigned char savech = '\0';
+39 -66
View File
@@ -135,6 +135,10 @@ enum {
: 0x7ff0
};
#if ENABLE_USERNAME_OR_HOMEDIR
static const char null_str[] ALIGN1 = "";
#endif
/* We try to minimize both static and stack usage. */
struct lineedit_statics {
line_input_t *state;
@@ -157,13 +161,12 @@ struct lineedit_statics {
#if ENABLE_USERNAME_OR_HOMEDIR
char *user_buf;
char *home_pwd_buf;
smallint got_user_strings;
char *home_pwd_buf; /* = (char*)null_str; */
#endif
#if ENABLE_FEATURE_TAB_COMPLETION
unsigned num_matches;
char **matches;
unsigned num_matches;
#endif
#if ENABLE_FEATURE_EDITING_WINCH
@@ -189,7 +192,7 @@ struct lineedit_statics {
};
/* See lineedit_ptr_hack.c */
extern struct lineedit_statics *BB_GLOBAL_CONST lineedit_ptr_to_statics;
extern struct lineedit_statics *const lineedit_ptr_to_statics;
#define S (*lineedit_ptr_to_statics)
#define state (S.state )
@@ -204,15 +207,15 @@ extern struct lineedit_statics *BB_GLOBAL_CONST lineedit_ptr_to_statics;
#define prompt_last_line (S.prompt_last_line)
#define user_buf (S.user_buf )
#define home_pwd_buf (S.home_pwd_buf )
#define got_user_strings (S.got_user_strings)
#define num_matches (S.num_matches )
#define matches (S.matches )
#define num_matches (S.num_matches )
#define delptr (S.delptr )
#define newdelflag (S.newdelflag )
#define delbuf (S.delbuf )
#define INIT_S() do { \
XZALLOC_CONST_PTR(&lineedit_ptr_to_statics, sizeof(S)); \
(*(struct lineedit_statics**)not_const_pp(&lineedit_ptr_to_statics)) = xzalloc(sizeof(S)); \
barrier(); \
} while (0)
static void deinit_S(void)
@@ -224,47 +227,14 @@ static void deinit_S(void)
#endif
#if ENABLE_USERNAME_OR_HOMEDIR
free(user_buf);
free(home_pwd_buf);
if (home_pwd_buf != null_str)
free(home_pwd_buf);
#endif
free(lineedit_ptr_to_statics);
}
#define DEINIT_S() deinit_S()
#if ENABLE_USERNAME_OR_HOMEDIR
/* Call getpwuid() only if necessary.
* E.g. if PS1=':', no user database reading is needed to generate prompt.
* (Unfortunately, default PS1='\w \$' needs it, \w abbreviates homedir
* as ~/... - for that it needs to *know* the homedir...)
*/
static void get_user_strings(void)
{
struct passwd *entry;
got_user_strings = 1;
entry = getpwuid(geteuid());
if (entry) {
user_buf = xstrdup(entry->pw_name);
home_pwd_buf = xstrdup(entry->pw_dir);
}
}
static const char *get_username_str(void)
{
if (!got_user_strings)
get_user_strings();
return user_buf ? user_buf : "";
/* btw, bash uses "I have no name!" string if uid has no entry */
}
static NOINLINE const char *get_homedir_or_NULL(void)
{
if (!got_user_strings)
get_user_strings();
return home_pwd_buf;
}
#endif
#if ENABLE_UNICODE_SUPPORT
static size_t load_string(const char *src)
{
@@ -722,11 +692,11 @@ static char *username_path_completion(char *ud)
{
struct passwd *entry;
char *tilde_name = ud;
const char *home = NULL;
char *home = NULL;
ud++; /* skip ~ */
if (*ud == '/') { /* "~/..." */
home = get_homedir_or_NULL();
home = home_pwd_buf;
} else {
/* "~user/..." */
ud = strchr(ud, '/');
@@ -1163,16 +1133,7 @@ static void showfiles(void)
static const char *is_special_char(char c)
{
// {: It's mandatory to escape { only if entire name is "{"
// (otherwise it's not special. Example: file named "{ "
// can be escaped simply as "{\ "; "{a" or "a{" need no escaping),
// or if shell supports brace expansion
// (ash doesn't, hush optionally does).
// (): unlike {, shell treats () specially even in contexts
// where they clearly are not valid (e.g. "echo )" is an error).
// #: needs escaping to not start a shell comment.
return strchr(" `'\"\\#$~?*[{()&;|<>", c);
// Used to also have %^=+}]: but not necessary to escape?
return strchr(" `\"#$%^&*()=+{}[]:;'|\\<>", c);
}
static char *quote_special_chars(char *found)
@@ -1792,7 +1753,7 @@ vi_back_motion(void)
input_backward(1);
}
}
#endif /* ENABLE_FEATURE_EDITING_VI */
#endif
/* Modelled after bash 4.0 behavior of Ctrl-<arrow> */
static void ctrl_left(void)
@@ -1893,7 +1854,7 @@ static void ask_terminal(void)
}
}
#else
# define ask_terminal() ((void)0)
#define ask_terminal() ((void)0)
#endif
/* Note about multi-line PS1 (e.g. "\n\w \u@\h\n> ") and prompt redrawing:
@@ -2002,7 +1963,7 @@ static void parse_and_put_prompt(const char *prmt_ptr)
switch (c) {
case 'u':
pbuf = (char*)get_username_str();
pbuf = user_buf ? user_buf : (char*)"";
break;
case 'H':
case 'h':
@@ -2024,15 +1985,14 @@ static void parse_and_put_prompt(const char *prmt_ptr)
case 'w': /* current dir */
case 'W': /* basename of cur dir */
if (!cwd_buf) {
const char *home;
cwd_buf = xrealloc_getcwd_or_warn(NULL);
if (!cwd_buf)
cwd_buf = (char *)bb_msg_unknown;
else if ((home = get_homedir_or_NULL()) != NULL && home[0]) {
else if (home_pwd_buf[0]) {
char *after_home_user;
/* /home/user[/something] -> ~[/something] */
after_home_user = is_prefixed_with(cwd_buf, home);
after_home_user = is_prefixed_with(cwd_buf, home_pwd_buf);
if (after_home_user
&& (*after_home_user == '/' || *after_home_user == '\0')
) {
@@ -2088,7 +2048,7 @@ static void parse_and_put_prompt(const char *prmt_ptr)
if (c == '\n')
cmdedit_prmt_len = 0;
else if (flg_not_length != ']') {
# if ENABLE_UNICODE_SUPPORT
#if ENABLE_UNICODE_SUPPORT
if (n == 1) {
/* Only count single-byte characters and the first of multi-byte characters */
if ((unsigned char)*pbuf < 0x80 /* single byte character */
@@ -2099,9 +2059,9 @@ static void parse_and_put_prompt(const char *prmt_ptr)
} else {
cmdedit_prmt_len += unicode_strwidth(pbuf);
}
# else
#else
cmdedit_prmt_len += n;
# endif
#endif
}
}
prmt_mem_ptr = strcat(xrealloc(prmt_mem_ptr, prmt_size+1), pbuf);
@@ -2328,7 +2288,7 @@ static int32_t reverse_i_search(int timeout)
}
/* Append this char */
# if ENABLE_UNICODE_SUPPORT
#if ENABLE_UNICODE_SUPPORT
if (unicode_status == UNICODE_ON) {
mbstate_t mbstate = { 0 };
char buf[MB_CUR_MAX + 1];
@@ -2339,7 +2299,7 @@ static int32_t reverse_i_search(int timeout)
strcpy(match_buf + match_buf_len, buf);
}
} else
# endif
#endif
if (match_buf_len < sizeof(match_buf) - 1) {
match_buf[match_buf_len] = ic;
match_buf[match_buf_len + 1] = '\0';
@@ -2391,7 +2351,7 @@ static int32_t reverse_i_search(int timeout)
return ic;
}
#endif /* ENABLE_FEATURE_REVERSE_SEARCH */
#endif
#if ENABLE_FEATURE_EDITING_WINCH
static void sigaction2(int sig, struct sigaction *act)
@@ -2431,6 +2391,7 @@ int FAST_FUNC read_line_input(line_input_t *st, const char *prompt, char *comman
//command_len = 0; - done by INIT_S()
//cmdedit_y = 0; /* quasireal y, not true if line > xt*yt */
cmdedit_termw = 80;
IF_USERNAME_OR_HOMEDIR(home_pwd_buf = (char*)null_str;)
IF_FEATURE_EDITING_VI(delptr = delbuf;)
n = get_termios_and_make_raw(STDIN_FILENO, &new_settings, &initial_settings, 0
@@ -2490,6 +2451,18 @@ int FAST_FUNC read_line_input(line_input_t *st, const char *prompt, char *comman
tcsetattr_stdin_TCSANOW(&new_settings);
#if ENABLE_USERNAME_OR_HOMEDIR
{
struct passwd *entry;
entry = getpwuid(geteuid());
if (entry) {
user_buf = xstrdup(entry->pw_name);
home_pwd_buf = xstrdup(entry->pw_dir);
}
}
#endif
#if 0
for (i = 0; i <= state->max_history; i++)
bb_error_msg("history[%d]:'%s'", i, state->history[i]);
+22 -12
View File
@@ -16,18 +16,16 @@
#error permission bitflag value assumption(s) violated!
#endif
/* Generate ls-style "mode string" like "-rwsr-xr-x" or "drwxrwxrwt" */
#if ( S_IFSOCK!= 0140000 ) || ( S_IFLNK != 0120000 ) \
|| ( S_IFREG != 0100000 ) || ( S_IFBLK != 0060000 ) \
|| ( S_IFDIR != 0040000 ) || ( S_IFCHR != 0020000 ) \
|| ( S_IFIFO != 0010000 )
# warning mode type bitflag value assumption(s) violated! falling back to larger version
#warning mode type bitflag value assumption(s) violated! falling back to larger version
# if (S_IRWXU | S_IRWXG | S_IRWXO | S_ISUID | S_ISGID | S_ISVTX) == 07777
# undef mode_t
# define mode_t unsigned short
# endif
#if (S_IRWXU | S_IRWXG | S_IRWXO | S_ISUID | S_ISGID | S_ISVTX) == 07777
#undef mode_t
#define mode_t unsigned short
#endif
static const mode_t mode_flags[] ALIGN4 = {
S_IRUSR, S_IWUSR, S_IXUSR, S_ISUID,
@@ -35,14 +33,19 @@ static const mode_t mode_flags[] ALIGN4 = {
S_IROTH, S_IWOTH, S_IXOTH, S_ISVTX
};
/* The static const char arrays below are duplicated for the two cases
* because moving them ahead of the mode_flags declaration cause a text
* size increase with the gcc version I'm using. */
/* The previous version used "0pcCd?bB-?l?s???". However, the '0', 'C',
* and 'B' types don't appear to be available on linux. So I removed them. */
static const char type_chars[16] ALIGN1 = "?pc?d?b?-?l?s???";
/***************************************** 0123456789abcdef */
static const char mode_chars[7] ALIGN1 = "rwxSTst";
char* FAST_FUNC bb_mode_string(char buf[11], mode_t mode)
const char* FAST_FUNC bb_mode_string(mode_t mode)
{
static char buf[12];
char *p = buf;
int i, j, k;
@@ -64,7 +67,10 @@ char* FAST_FUNC bb_mode_string(char buf[11], mode_t mode)
i += 4;
} while (i < 12);
buf[10] = '\0';
/* Note: We don't bother with nul termination because bss initialization
* should have taken care of that for us. If the user scribbled in buf
* memory, they deserve whatever happens. But we'll at least assert. */
assert(buf[10] == 0);
return buf;
}
@@ -74,11 +80,12 @@ char* FAST_FUNC bb_mode_string(char buf[11], mode_t mode)
/* The previous version used "0pcCd?bB-?l?s???". However, the '0', 'C',
* and 'B' types don't appear to be available on linux. So I removed them. */
static const char type_chars[16] ALIGN1 = "?pc?d?b?-?l?s???";
/***************************************** 0123456789abcdef */
/********************************** 0123456789abcdef */
static const char mode_chars[7] ALIGN1 = "rwxSTst";
char* FAST_FUNC bb_mode_string(char buf[11], mode_t mode)
const char* FAST_FUNC bb_mode_string(mode_t mode)
{
static char buf[12];
char *p = buf;
int i, j, k, m;
@@ -102,7 +109,10 @@ char* FAST_FUNC bb_mode_string(char buf[11], mode_t mode)
}
} while (i < 3);
buf[10] = '\0';
/* Note: We don't bother with nul termination because bss initialization
* should have taken care of that for us. If the user scribbled in buf
* memory, they deserve whatever happens. But we'll at least assert. */
assert(buf[10] == 0);
return buf;
}
+2 -3
View File
@@ -16,14 +16,13 @@
int FAST_FUNC bb_parse_mode(const char *s, unsigned current_mode)
{
/* should be mode_t really, but in all Unixes these constants fit into uint16 */
static const uint16_t who_mask[] ALIGN2 = {
static const mode_t who_mask[] = {
S_ISUID | S_ISGID | S_ISVTX | S_IRWXU | S_IRWXG | S_IRWXO, /* a */
S_ISUID | S_IRWXU, /* u */
S_ISGID | S_IRWXG, /* g */
S_IRWXO /* o */
};
static const uint16_t perm_mask[] ALIGN2 = {
static const mode_t perm_mask[] = {
S_IRUSR | S_IRGRP | S_IROTH, /* r */
S_IWUSR | S_IWGRP | S_IWOTH, /* w */
S_IXUSR | S_IXGRP | S_IXOTH, /* x */
+15 -14
View File
@@ -363,7 +363,7 @@ des_init(struct des_ctx *ctx, const struct const_des_ctx *cctx)
old_rawkey0 = old_rawkey1 = 0;
old_salt = 0;
#endif
//saltbits = 0; /* not needed: we call setup_salt() before do_des() */
saltbits = 0;
bits28 = bits32 + 4;
bits24 = bits28 + 4;
@@ -481,11 +481,12 @@ des_init(struct des_ctx *ctx, const struct const_des_ctx *cctx)
return ctx;
}
/* Accepts 24-bit salt at max */
static void
setup_salt(struct des_ctx *ctx, uint32_t salt)
{
uint32_t invbits;
uint32_t obit, saltbit;
int i;
#if USE_REPETITIVE_SPEEDUP
if (salt == old_salt)
@@ -493,15 +494,15 @@ setup_salt(struct des_ctx *ctx, uint32_t salt)
old_salt = salt;
#endif
invbits = 0;
salt |= (1 << 24);
do {
invbits = (invbits << 1) + (salt & 1);
salt >>= 1;
} while (salt != 1);
saltbits = invbits;
saltbits = 0;
saltbit = 1;
obit = 0x800000;
for (i = 0; i < 24; i++) {
if (salt & saltbit)
saltbits |= obit;
saltbit <<= 1;
obit >>= 1;
}
}
static void
@@ -735,14 +736,14 @@ des_crypt(struct des_ctx *ctx, char output[DES_OUT_BUFSIZE],
des_setkey(ctx, (char *)keybuf);
/*
* salt_str - 2 chars of salt (converted to 12 bits)
* salt_str - 2 bytes of salt
* key - up to 8 characters
*/
output[0] = salt_str[0];
output[1] = salt_str[1];
salt = (ascii_to_bin(salt_str[1]) << 6)
| ascii_to_bin(salt_str[0]);
setup_salt(ctx, salt); /* set ctx->saltbits for do_des() */
setup_salt(ctx, salt);
/* Do it. */
do_des(ctx, /*0, 0,*/ &r0, &r1, 25 /* count */);
+15 -62
View File
@@ -8,68 +8,16 @@
*/
#include "libbb.h"
/* Returns 0 if the time structure contains an absolute UTC time which
* should not be subject to DST adjustment by the caller. */
int FAST_FUNC parse_datestr(const char *date_str, struct tm *ptm)
void FAST_FUNC parse_datestr(const char *date_str, struct tm *ptm)
{
char end = '\0';
time_t t;
#if ENABLE_DESKTOP
/*
* strptime is BIG: ~1k in uclibc, ~10k in glibc
* We need it for 'month_name d HH:MM:SS YYYY', supported by GNU date,
* but if we've linked it we might as well use it for everything.
*/
static const char fmt_str[] ALIGN1 =
"%R" "\0" /* HH:MM */
"%T" "\0" /* HH:MM:SS */
"%m.%d-%R" "\0" /* mm.dd-HH:MM */
"%m.%d-%T" "\0" /* mm.dd-HH:MM:SS */
"%Y.%m.%d-%R" "\0" /* yyyy.mm.dd-HH:MM */
"%Y.%m.%d-%T" "\0" /* yyyy.mm.dd-HH:MM:SS */
"%b %d %T %Y" "\0" /* month_name d HH:MM:SS YYYY */
"%Y-%m-%d %R" "\0" /* yyyy-mm-dd HH:MM */
"%Y-%m-%d %T" "\0" /* yyyy-mm-dd HH:MM:SS */
# if ENABLE_FEATURE_TIMEZONE
"%Y-%m-%d %R %z" "\0" /* yyyy-mm-dd HH:MM TZ */
"%Y-%m-%d %T %z" "\0" /* yyyy-mm-dd HH:MM:SS TZ */
# endif
"%Y-%m-%d %H" "\0" /* yyyy-mm-dd HH */
"%Y-%m-%d" "\0" /* yyyy-mm-dd */
/* extra NUL */;
struct tm save;
const char *fmt;
char *endp;
save = *ptm;
fmt = fmt_str;
while (*fmt) {
endp = strptime(date_str, fmt, ptm);
if (endp && *endp == '\0') {
# if ENABLE_FEATURE_TIMEZONE
if (strchr(fmt, 'z')) {
/* we have timezone offset: obtain Unix time_t */
ptm->tm_sec -= ptm->tm_gmtoff;
ptm->tm_isdst = 0;
t = timegm(ptm);
if (t == (time_t)-1)
break;
/* convert Unix time_t to struct tm in user's locale */
goto localise;
}
# endif
return 1;
}
*ptm = save;
while (*++fmt)
continue;
++fmt;
}
#else
const char *last_colon = strrchr(date_str, ':');
if (last_colon != NULL) {
/* Parse input and assign appropriately to ptm */
#if ENABLE_DESKTOP
const char *endp;
#endif
/* HH:MM */
if (sscanf(date_str, "%u:%u%c",
@@ -102,6 +50,14 @@ int FAST_FUNC parse_datestr(const char *date_str, struct tm *ptm)
ptm->tm_year -= 1900; /* Adjust years */
ptm->tm_mon -= 1; /* Adjust month from 1-12 to 0-11 */
} else
#if ENABLE_DESKTOP /* strptime is BIG: ~1k in uclibc, ~10k in glibc */
/* month_name d HH:MM:SS YYYY. Supported by GNU date */
if ((endp = strptime(date_str, "%b %d %T %Y", ptm)) != NULL
&& *endp == '\0'
) {
return; /* don't fall through to end == ":" check */
} else
#endif
{
bb_error_msg_and_die(bb_msg_invalid_date, date_str);
}
@@ -133,19 +89,17 @@ int FAST_FUNC parse_datestr(const char *date_str, struct tm *ptm)
ptm->tm_year -= 1900; /* Adjust years */
ptm->tm_mon -= 1; /* Adjust month from 1-12 to 0-11 */
} else
#endif /* ENABLE_DESKTOP */
if (date_str[0] == '@') {
time_t t;
if (sizeof(t) <= sizeof(long))
t = bb_strtol(date_str + 1, NULL, 10);
else /* time_t is 64 bits but longs are smaller */
t = bb_strtoll(date_str + 1, NULL, 10);
if (!errno) {
struct tm *lt;
IF_FEATURE_TIMEZONE(localise:)
lt = localtime(&t);
struct tm *lt = localtime(&t);
if (lt) {
*ptm = *lt;
return 0;
return;
}
}
end = '1';
@@ -262,7 +216,6 @@ int FAST_FUNC parse_datestr(const char *date_str, struct tm *ptm)
if (end != '\0') {
bb_error_msg_and_die(bb_msg_invalid_date, date_str);
}
return 1;
}
time_t FAST_FUNC validate_tm_time(const char *date_str, struct tm *ptm)
-16
View File
@@ -28,22 +28,6 @@
# ifndef PR_GET_NAME
# define PR_GET_NAME 16
# endif
# if ENABLE_FEATURE_SH_STANDALONE || ENABLE_FEATURE_PREFER_APPLETS || !BB_MMU
int FAST_FUNC re_execed_comm(void)
{
const char *e, *expected_comm;
char comm[16];
BUILD_BUG_ON(CONFIG_BUSYBOX_EXEC_PATH[0] != '/');
e = CONFIG_BUSYBOX_EXEC_PATH;
/* Hopefully (strrchr(e) - e) evaluates to constant at compile time: */
expected_comm = bb_busybox_exec_path + (strrchr(e, '/') - e) + 1;
prctl(PR_GET_NAME, (long)comm, 0, 0, 0);
//bb_error_msg("comm:'%.*s' expected:'%s'", 16, comm, expected_comm);
return strcmp(comm, expected_comm) == 0;
}
# endif
void FAST_FUNC set_task_comm(const char *comm)
{
/* okay if too long (truncates) */
+15 -7
View File
@@ -115,19 +115,27 @@ void FAST_FUNC xconnect(int s, const struct sockaddr *s_addr, socklen_t addrlen)
/* Return port number for a service.
* If "port" is a number use it as the port.
* If "port" is a name it is looked up in /etc/services.
* if NULL, return default_port
* If "port" is a name it is looked up in /etc/services,
* if it isnt found return default_port
*/
unsigned FAST_FUNC bb_lookup_port(const char *port, const char *protocol, unsigned port_nr)
unsigned FAST_FUNC bb_lookup_port(const char *port, const char *protocol, unsigned default_port)
{
unsigned port_nr = default_port;
if (port) {
int old_errno;
/* Since this is a lib function, we're not allowed to reset errno to 0.
* Doing so could break an app that is deferring checking of errno. */
old_errno = errno;
port_nr = bb_strtou(port, NULL, 10);
if (errno || port_nr > 65535) {
struct servent *tserv = getservbyname(port, protocol);
if (!tserv)
bb_error_msg_and_die("bad port '%s'", port);
port_nr = ntohs(tserv->s_port);
port_nr = default_port;
if (tserv)
port_nr = ntohs(tserv->s_port);
//FIXME: else: port string was garbage, but we don't report that???
}
errno = old_errno;
}
return (uint16_t)port_nr;
}
@@ -231,7 +239,7 @@ IF_NOT_FEATURE_IPV6(sa_family_t af = AF_INET;)
cp++; /* skip ':' */
port = bb_strtou(cp, NULL, 10);
if (errno || (unsigned)port > 0xffff) {
bb_error_msg("bad port '%s'", cp);
bb_error_msg("bad port spec '%s'", org_host);
if (ai_flags & DIE_ON_ERROR)
xfunc_die();
return NULL;
+30 -45
View File
@@ -123,7 +123,7 @@ char* FAST_FUNC xmalloc_realpath(const char *path)
#endif
}
char* FAST_FUNC xmalloc_realpath_coreutils(char *path)
char* FAST_FUNC xmalloc_realpath_coreutils(const char *path)
{
char *buf;
@@ -137,19 +137,32 @@ char* FAST_FUNC xmalloc_realpath_coreutils(char *path)
* (the directory must exist).
*/
if (!buf && errno == ENOENT) {
char *target, c, *last_slash;
size_t i;
target = xmalloc_readlink(path);
if (target) {
/*
* $ ln -s /bin/qwe symlink # note: /bin is a link to /usr/bin
* $ readlink -f symlink
* /usr/bin/qwe
* $ realpath symlink
* /usr/bin/qwe
*/
if (target[0] != '/') {
char *last_slash = strrchr(path, '/');
if (last_slash) {
*last_slash++ = '\0';
buf = xmalloc_realpath(path);
if (buf) {
unsigned len = strlen(buf);
buf = xrealloc(buf, len + strlen(last_slash) + 2);
buf[len++] = '/';
strcpy(buf + len, last_slash);
}
} else {
char *target = xmalloc_readlink(path);
if (target) {
char *cwd;
if (target[0] == '/') {
/*
* $ ln -s /bin/qwe symlink # note: /bin is a link to /usr/bin
* $ readlink -f symlink
* /usr/bin/qwe/target_does_not_exist
* $ realpath symlink
* /usr/bin/qwe/target_does_not_exist
*/
buf = xmalloc_realpath_coreutils(target);
free(target);
return buf;
}
/*
* $ ln -s target_does_not_exist symlink
* $ readlink -f symlink
@@ -157,41 +170,13 @@ char* FAST_FUNC xmalloc_realpath_coreutils(char *path)
* $ realpath symlink
* /CURDIR/target_does_not_exist
*/
char *cwd = xrealloc_getcwd_or_warn(NULL);
char *tmp = concat_path_file(cwd, target);
cwd = xrealloc_getcwd_or_warn(NULL);
buf = concat_path_file(cwd, target);
free(cwd);
free(target);
target = tmp;
}
buf = xmalloc_realpath_coreutils(target);
free(target);
return buf;
}
/* ignore leading and trailing slashes */
while (path[0] == '/' && path[1] == '/')
++path;
i = strlen(path) - 1;
while (i > 0 && path[i] == '/')
i--;
c = path[i + 1];
path[i + 1] = '\0';
last_slash = strrchr(path, '/');
if (last_slash == path)
buf = xstrdup(path);
else if (last_slash) {
*last_slash = '\0';
buf = xmalloc_realpath(path);
*last_slash++ = '/';
if (buf) {
unsigned len = strlen(buf);
buf = xrealloc(buf, len + strlen(last_slash) + 2);
buf[len++] = '/';
strcpy(buf + len, last_slash);
return buf;
}
}
path[i + 1] = c;
}
return buf;
+2 -2
View File
@@ -1,5 +1,7 @@
menu "Mail Utilities"
INSERT
config FEATURE_MIME_CHARSET
string "Default charset"
default "us-ascii"
@@ -7,6 +9,4 @@ config FEATURE_MIME_CHARSET
help
Default charset of the message.
INSERT
endmenu
+1 -1
View File
@@ -2261,7 +2261,7 @@ static FAST_FUNC BC_STATUS zbc_num_p(BcNum *a, BcNum *b, BcNum *restrict c, size
}
#define zbc_num_p(...) (zbc_num_p(__VA_ARGS__) COMMA_SUCCESS)
static NOINLINE BC_STATUS zbc_num_sqrt(BcNum *a, BcNum *restrict b, size_t scale)
static BC_STATUS zbc_num_sqrt(BcNum *a, BcNum *restrict b, size_t scale)
{
BcStatus s;
BcNum num1, num2, half, f, fprime, *x0, *x1, *temp;
+1 -1
View File
@@ -1820,7 +1820,7 @@ int less_main(int argc, char **argv)
getopt32(argv, "EMmN~IF"
IF_FEATURE_LESS_TRUNCATE("S")
IF_FEATURE_LESS_RAW("R")
/*ignored:*/"sX"
/*ignored:*/"s"
);
argv += optind;
num_files = argc - optind;
-26
View File
@@ -46,32 +46,6 @@ config VERBOSE_RESOLUTION_ERRORS
"can't resolve 'hostname.com'" and want to know more.
This may increase size of your executable a bit.
config FEATURE_ETC_NETWORKS
bool "Support /etc/networks"
default n
help
Enable support for network names in /etc/networks. This is
a rarely used feature which allows you to use names
instead of IP/mask pairs in route command.
config FEATURE_ETC_SERVICES
bool "Consult /etc/services even for well-known ports"
default n
help
Look up e.g. "telnet" and "http" in /etc/services file
instead of assuming ports 23 and 80.
This is almost never necessary (everybody uses standard ports),
and it makes sense to avoid reading this file.
If you disable this option, in the cases where port is explicitly
specified as a service name (e.g. "telnet HOST PORTNAME"),
it will still be looked up in /etc/services.
config FEATURE_HWIB
bool "Support infiniband HW"
default y
help
Support for printing infiniband addresses in network applets.
config FEATURE_TLS_SHA1
bool "In TLS code, support ciphers which use deprecated SHA1"
depends on TLS
+1 -1
View File
@@ -318,7 +318,7 @@ static void printf_xstrtou(const char *fmt)
printf(fmt, xstrtou(filedata, 0));
}
static NOINLINE void show_bridge_port(const char *name)
static void show_bridge_port(const char *name)
{
char pathbuf[IFNAMSIZ + sizeof("/brport/forward_delay_timer") + 8];
char *sfx;
+2 -1
View File
@@ -290,7 +290,8 @@ static const char ftpgetput_longopts[] ALIGN1 =
int ftpgetput_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
int ftpgetput_main(int argc UNUSED_PARAM, char **argv)
{
const char *port = NULL;
const char *port = "ftp";
/* socket to ftp server */
#if ENABLE_FTPPUT && !ENABLE_FTPGET
# define ftp_action ftp_send
+6 -23
View File
@@ -102,12 +102,6 @@
//config: help
//config: HTTP server.
//config:
//config:config FEATURE_HTTPD_PORT_DEFAULT
//config: int "Default port"
//config: default 80
//config: range 1 65535
//config: depends on HTTPD
//config:
//config:config FEATURE_HTTPD_RANGES
//config: bool "Support 'Ranges:' header"
//config: default y
@@ -274,9 +268,9 @@
//usage:#define httpd_full_usage "\n\n"
//usage: "Listen for incoming HTTP requests\n"
//usage: "\n -i Inetd mode"
//usage: "\n -f Run in foreground"
//usage: "\n -f Don't daemonize"
//usage: "\n -v[v] Verbose"
//usage: "\n -p [IP:]PORT Bind to IP:PORT (default *:"STR(CONFIG_FEATURE_HTTPD_PORT_DEFAULT)")"
//usage: "\n -p [IP:]PORT Bind to IP:PORT (default *:80)"
//usage: IF_FEATURE_HTTPD_SETUID(
//usage: "\n -u USER[:GRP] Set uid/gid after binding to port")
//usage: IF_FEATURE_HTTPD_BASIC_AUTH(
@@ -322,9 +316,6 @@
#define HEADER_READ_TIMEOUT 60
#define STR1(s) #s
#define STR(s) STR1(s)
static const char DEFAULT_PATH_HTTPD_CONF[] ALIGN1 = "/etc";
static const char HTTPD_CONF[] ALIGN1 = "httpd.conf";
static const char HTTP_200[] ALIGN1 = "HTTP/1.1 200 OK\r\n";
@@ -551,7 +542,7 @@ enum {
SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
IF_FEATURE_HTTPD_BASIC_AUTH(g_realm = "Web Server Authentication";) \
IF_FEATURE_HTTPD_RANGES(range_start = -1;) \
bind_addr_or_port = STR(CONFIG_FEATURE_HTTPD_PORT_DEFAULT); \
bind_addr_or_port = "80"; \
index_page = index_html; \
file_size = -1; \
} while (0)
@@ -1125,7 +1116,7 @@ static void send_headers(unsigned responseNum)
"Connection: close\r\n",
responseNum, responseString
#if ENABLE_FEATURE_HTTPD_DATE
, date_str
,date_str
#endif
);
}
@@ -1290,7 +1281,6 @@ static void send_headers_and_exit(int responseNum) NORETURN;
static void send_headers_and_exit(int responseNum)
{
IF_FEATURE_HTTPD_GZIP(content_gzip = 0;)
file_size = -1; /* no Last-Modified:, ETag:, Content-Length: */
send_headers(responseNum);
log_and_exit();
}
@@ -1879,21 +1869,14 @@ static NOINLINE void send_file_and_exit(const char *url, int what)
send_headers(HTTP_OK);
#if ENABLE_FEATURE_USE_SENDFILE
{
off_t offset;
# if ENABLE_FEATURE_HTTPD_RANGES
if (range_start < 0)
range_start = 0;
offset = range_start;
# else
offset = 0;
# endif
off_t offset = (range_start < 0) ? 0 : range_start;
while (1) {
/* sz is rounded down to 64k */
ssize_t sz = MAXINT(ssize_t) - 0xffff;
IF_FEATURE_HTTPD_RANGES(if (sz > range_len) sz = range_len;)
count = sendfile(STDOUT_FILENO, fd, &offset, sz);
if (count < 0) {
if (offset == range_start) /* was it the very 1st sendfile? */
if (offset == range_start)
break; /* fall back to read/write loop */
goto fin;
}
+1 -1
View File
@@ -20,7 +20,7 @@
//usage: "[OPTIONS]"
//usage:#define ifplugd_full_usage "\n\n"
//usage: "Network interface plug detection daemon\n"
//usage: "\n -n Run in foreground"
//usage: "\n -n Don't daemonize"
//usage: "\n -s Don't log to syslog"
//usage: "\n -i IFACE Interface"
//usage: "\n -f/-F Treat link detection error as link down/link up"
+1 -1
View File
@@ -152,7 +152,7 @@
//usage:#define iplink_trivial_usage
//usage: /*Usage:iplink*/"set IFACE [up|down] [arp on|off] [multicast on|off]\n"
//usage: " [promisc on|off] [mtu NUM] [name NAME] [qlen NUM] [address MAC]\n"
//usage: " [master IFACE | nomaster] [netns PID]"
//usage: " [master IFACE | nomaster]"
// * short help shows only "set" command, long help continues (with just one "\n")
// * and shows all other commands:
//usage:#define iplink_full_usage "\n"
+2 -33
View File
@@ -152,30 +152,6 @@ static void set_master(char *dev, int master)
xfunc_die();
}
/* Exits on error */
static void set_netns(char *dev, int netns)
{
struct rtnl_handle rth;
struct {
struct nlmsghdr n;
struct ifinfomsg i;
char buf[1024];
} req;
memset(&req, 0, sizeof(req));
req.n.nlmsg_len = NLMSG_LENGTH(sizeof(struct ifinfomsg));
req.n.nlmsg_flags = NLM_F_REQUEST;
req.n.nlmsg_type = RTM_NEWLINK;
req.i.ifi_family = preferred_family;
xrtnl_open(&rth);
req.i.ifi_index = xll_name_to_index(dev);
//printf("netns %i for %i\n", netns, req.i.ifi_index);
addattr_l(&req.n, sizeof(req), IFLA_NET_NS_PID, &netns, 4);
if (rtnl_talk(&rth, &req.n, 0, 0, NULL, NULL, NULL) < 0)
xfunc_die();
}
/* Exits on error */
static int get_address(char *dev, int *htype)
{
@@ -250,7 +226,6 @@ static int do_set(char **argv)
int qlen = -1;
int mtu = -1;
int master = -1;
int netns = -1;
char *newaddr = NULL;
char *newbrd = NULL;
struct ifreq ifr0, ifr1;
@@ -259,11 +234,11 @@ static int do_set(char **argv)
/* If you add stuff here, update iplink_full_usage */
static const char keywords[] ALIGN1 =
"up\0""down\0""name\0""mtu\0""qlen\0""multicast\0"
"arp\0""promisc\0""address\0""netns\0"
"arp\0""promisc\0""address\0"
"master\0""nomaster\0"
"dev\0" /* must be last */;
enum { ARG_up = 0, ARG_down, ARG_name, ARG_mtu, ARG_qlen, ARG_multicast,
ARG_arp, ARG_promisc, ARG_addr, ARG_netns,
ARG_arp, ARG_promisc, ARG_addr,
ARG_master, ARG_nomaster,
ARG_dev };
enum { PARM_on = 0, PARM_off };
@@ -301,9 +276,6 @@ static int do_set(char **argv)
master = xll_name_to_index(*argv);
} else if (key == ARG_nomaster) {
master = 0;
} else if (key == ARG_netns) {
NEXT_ARG();
netns = get_unsigned(*argv, "netns");
} else if (key >= ARG_dev) {
/* ^^^^^^ ">=" here results in "dev IFACE" treated as default */
if (key == ARG_dev) {
@@ -491,9 +463,6 @@ static int do_set(char **argv)
if (master != -1) {
set_master(dev, master);
}
if (netns != -1) {
set_netns(dev, netns);
}
if (mask)
do_chflags(dev, flags, mask);
return 0;
+1 -1
View File
@@ -216,7 +216,7 @@ int nc_main(int argc, char **argv)
close(sfd);
} else {
cfd = create_and_connect_stream_or_die(argv[0],
bb_lookup_port(argv[1], "tcp", 0));
argv[1] ? bb_lookup_port(argv[1], "tcp", 0) : 0);
}
}
+5 -2
View File
@@ -813,6 +813,8 @@ int nc_main(int argc UNUSED_PARAM, char **argv)
//if (option_mask32 & OPT_o) /* hexdump log */
if (option_mask32 & OPT_p) { /* local source port */
o_lport = bb_lookup_port(str_p, o_udpmode ? "udp" : "tcp", 0);
if (!o_lport)
bb_error_msg_and_die("bad local port '%s'", str_p);
}
//if (option_mask32 & OPT_r) /* randomize various things */
//if (option_mask32 & OPT_u) /* use UDP */
@@ -825,8 +827,9 @@ int nc_main(int argc UNUSED_PARAM, char **argv)
if (argv[0]) {
themaddr = xhost2sockaddr(argv[0],
bb_lookup_port(argv[1], o_udpmode ? "udp" : "tcp", 0)
);
argv[1]
? bb_lookup_port(argv[1], o_udpmode ? "udp" : "tcp", 0)
: 0);
}
/* create & bind network socket */
+1 -1
View File
@@ -335,7 +335,7 @@ enum {
OPT_debug = (1 << 0),
};
static NOINLINE int parse_reply(const unsigned char *msg, size_t len)
static int parse_reply(const unsigned char *msg, size_t len)
{
HEADER *header;
+2 -2
View File
@@ -78,7 +78,7 @@
//usage:#define ntpd_full_usage "\n\n"
//usage: "NTP client/server\n"
//usage: "\n -d[d] Verbose"
//usage: "\n -n Run in foreground"
//usage: "\n -n Do not daemonize"
//usage: "\n -q Quit after clock is set"
//usage: "\n -N Run at high priority"
//usage: "\n -w Do not set time (only query peers), implies -n"
@@ -1152,7 +1152,7 @@ fit(peer_t *p, double rd)
// return 0;
return 1;
}
static NOINLINE peer_t*
static peer_t*
select_and_cluster(void)
{
peer_t *p;
+2 -8
View File
@@ -68,12 +68,6 @@
//config: help
//config: Selecting this will make telnetd able to run standalone.
//config:
//config:config FEATURE_TELNETD_PORT_DEFAULT
//config: int "Default port"
//config: default 23
//config: range 1 65535
//config: depends on FEATURE_TELNETD_STANDALONE
//config:
//config:config FEATURE_TELNETD_INETD_WAIT
//config: bool "Support -w SEC option (inetd wait mode)"
//config: default y
@@ -109,7 +103,7 @@
//usage: "\n -K Close connection as soon as login exits"
//usage: "\n (normally wait until all programs close slave pty)"
//usage: IF_FEATURE_TELNETD_STANDALONE(
//usage: "\n -p PORT Port to listen on. Default "STR(CONFIG_FEATURE_TELNETD_PORT_DEFAULT)
//usage: "\n -p PORT Port to listen on"
//usage: "\n -b ADDR[:PORT] Address to bind to"
//usage: "\n -F Run in foreground"
//usage: "\n -i Inetd mode"
@@ -714,7 +708,7 @@ int telnetd_main(int argc UNUSED_PARAM, char **argv)
} else {
master_fd = 0;
if (!(opt & OPT_WAIT)) {
unsigned portnbr = CONFIG_FEATURE_TELNETD_PORT_DEFAULT;
unsigned portnbr = 23;
if (opt & OPT_PORT)
portnbr = xatou16(opt_portnbr);
master_fd = create_and_bind_stream_or_die(opt_bindaddr, portnbr);
+57 -95
View File
@@ -22,23 +22,47 @@
#include "tls.h"
// Usually enabled. You can disable some of them to force only
// specific ciphers to be advertized to server.
// (this would not exclude code to handle disabled ciphers, no code size win)
#define ALLOW_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 1
#define ALLOW_ECDHE_RSA_WITH_AES_128_CBC_SHA256 1
#define ALLOW_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 1
#define ALLOW_ECDHE_RSA_WITH_AES_128_GCM_SHA256 1
#define ALLOW_RSA_WITH_AES_128_CBC_SHA256 1
#define ALLOW_RSA_WITH_AES_256_CBC_SHA256 1
#define ALLOW_RSA_WITH_AES_128_GCM_SHA256 1
#define ALLOW_CURVE_P256 1
#define ALLOW_CURVE_X25519 1
// For testing (does everything except encrypting).
// works against "openssl s_server -cipher NULL"
// and against wolfssl-3.9.10-stable/examples/server/server.c:
#define ALLOW_RSA_NULL_SHA256 0
#define ALLOW_RSA_NULL_SHA256 0 // for testing (does everything except encrypting)
//Tested against kernel.org:
//#define CIPHER_ID TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA // ok, recvs SERVER_KEY_EXCHANGE *** matrixssl uses this on my box
//#define CIPHER_ID TLS_RSA_WITH_AES_256_CBC_SHA256 // ok, no SERVER_KEY_EXCHANGE
//#define CIPHER_ID TLS_DH_anon_WITH_AES_256_CBC_SHA // SSL_ALERT_HANDSHAKE_FAILURE
//^^^^^^^^^^^^^^^^^^^^^^^ (tested b/c this one doesn't req server certs... no luck, server refuses it)
//#define CIPHER_ID TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 // SSL_ALERT_HANDSHAKE_FAILURE
//#define CIPHER_ID TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 // SSL_ALERT_HANDSHAKE_FAILURE
//#define CIPHER_ID TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 // ok, recvs SERVER_KEY_EXCHANGE
//#define CIPHER_ID TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256
//#define CIPHER_ID TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384
//#define CIPHER_ID TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256 // SSL_ALERT_HANDSHAKE_FAILURE
//#define CIPHER_ID TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384
//#define CIPHER_ID TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256 // SSL_ALERT_HANDSHAKE_FAILURE
//#define CIPHER_ID TLS_RSA_WITH_AES_256_GCM_SHA384 // ok, no SERVER_KEY_EXCHANGE
//#define CIPHER_ID TLS_RSA_WITH_AES_128_GCM_SHA256 // ok, no SERVER_KEY_EXCHANGE
// works against wolfssl-3.9.10-stable/examples/server/server.c
// works for kernel.org
// does not work for cdn.kernel.org (e.g. downloading an actual tarball, not a web page)
// getting alert 40 "handshake failure" at once
// with GNU Wget 1.18, they agree on TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 (0xC02F) cipher
// fail: openssl s_client -connect cdn.kernel.org:443 -debug -tls1_2 -cipher AES256-SHA256
// fail: openssl s_client -connect cdn.kernel.org:443 -debug -tls1_2 -cipher AES256-GCM-SHA384
// fail: openssl s_client -connect cdn.kernel.org:443 -debug -tls1_2 -cipher AES128-SHA256
// ok: openssl s_client -connect cdn.kernel.org:443 -debug -tls1_2 -cipher AES128-GCM-SHA256
// ok: openssl s_client -connect cdn.kernel.org:443 -debug -tls1_2 -cipher AES128-SHA
// (TLS_RSA_WITH_AES_128_CBC_SHA - in TLS 1.2 it's mandated to be always supported)
//#define CIPHER_ID1 TLS_RSA_WITH_AES_256_CBC_SHA256 //0x003D
// Works with "wget https://cdn.kernel.org/pub/linux/kernel/v4.x/linux-4.9.5.tar.xz"
//#define CIPHER_ID2 TLS_RSA_WITH_AES_128_CBC_SHA //0x002F
// bug #11456:
// ftp.openbsd.org only supports ECDHE-RSA-AESnnn-GCM-SHAnnn or ECDHE-RSA-CHACHA20-POLY1305
//#define CIPHER_ID3 TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 //0xC02F
// host is.gd accepts only ECDHE-ECDSA-foo (the simplest which works: ECDHE-ECDSA-AES128-SHA 0xC009)
//#define CIPHER_ID4 TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA //0xC009
#define TLS_DEBUG 0
#define TLS_DEBUG_HASH 0
@@ -1464,20 +1488,9 @@ static ALWAYS_INLINE void fill_handshake_record_hdr(void *buf, unsigned type, un
static void send_client_hello_and_alloc_hsd(tls_state_t *tls, const char *sni)
{
#define NUM_CIPHERS (0 \
+ 4 * ENABLE_FEATURE_TLS_SHA1 \
+ ALLOW_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 \
+ ALLOW_ECDHE_RSA_WITH_AES_128_CBC_SHA256 \
+ ALLOW_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 \
+ ALLOW_ECDHE_RSA_WITH_AES_128_GCM_SHA256 \
+ 2 * ENABLE_FEATURE_TLS_SHA1 \
+ ALLOW_RSA_WITH_AES_128_CBC_SHA256 \
+ ALLOW_RSA_WITH_AES_256_CBC_SHA256 \
+ ALLOW_RSA_WITH_AES_128_GCM_SHA256 \
+ ALLOW_RSA_NULL_SHA256 \
)
#define NUM_CIPHERS (7 + 6 * ENABLE_FEATURE_TLS_SHA1 + ALLOW_RSA_NULL_SHA256)
static const uint8_t ciphers[] = {
0x00,2 * (1 + NUM_CIPHERS), //len16_be
0x00,2 + NUM_CIPHERS*2, //len16_be
0x00,0xFF, //not a cipher - TLS_EMPTY_RENEGOTIATION_INFO_SCSV
/* ^^^^^^ RFC 5746 Renegotiation Indication Extension - some servers will refuse to work with us otherwise */
#if ENABLE_FEATURE_TLS_SHA1
@@ -1488,22 +1501,14 @@ static void send_client_hello_and_alloc_hsd(tls_state_t *tls, const char *sni)
// 0xC0,0x18, // TLS_ECDH_anon_WITH_AES_128_CBC_SHA
// 0xC0,0x19, // TLS_ECDH_anon_WITH_AES_256_CBC_SHA
#endif
#if ALLOW_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256
0xC0,0x23, // 5 TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 - ok: wget https://is.gd/
#endif
// 0xC0,0x24, // TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 - can't do SHA384 yet
#if ALLOW_ECDHE_RSA_WITH_AES_128_CBC_SHA256
0xC0,0x27, // 6 TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 - ok: openssl s_server ... -cipher ECDHE-RSA-AES128-SHA256
#endif
// 0xC0,0x28, // TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384 - can't do SHA384 yet
#if ALLOW_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256
0xC0,0x2B, // 7 TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 - ok: wget https://is.gd/
#endif
// 0xC0,0x2C, // TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 - wget https://is.gd/: "TLS error from peer (alert code 20): bad MAC"
//TODO: GCM_SHA384 ciphers can be supported, only need sha384-based PRF?
#if ALLOW_ECDHE_RSA_WITH_AES_128_GCM_SHA256
0xC0,0x2F, // 8 TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 - ok: openssl s_server ... -cipher ECDHE-RSA-AES128-GCM-SHA256
#endif
// 0xC0,0x30, // TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 - openssl s_server ... -cipher ECDHE-RSA-AES256-GCM-SHA384: "decryption failed or bad record mac"
//possibly these too:
#if ENABLE_FEATURE_TLS_SHA1
@@ -1516,15 +1521,9 @@ static void send_client_hello_and_alloc_hsd(tls_state_t *tls, const char *sni)
0x00,0x2F, // 9 TLS_RSA_WITH_AES_128_CBC_SHA - ok: openssl s_server ... -cipher AES128-SHA
0x00,0x35, //10 TLS_RSA_WITH_AES_256_CBC_SHA - ok: openssl s_server ... -cipher AES256-SHA
#endif
#if ALLOW_RSA_WITH_AES_128_CBC_SHA256
0x00,0x3C, //11 TLS_RSA_WITH_AES_128_CBC_SHA256 - ok: openssl s_server ... -cipher AES128-SHA256
#endif
#if ALLOW_RSA_WITH_AES_256_CBC_SHA256
0x00,0x3D, //12 TLS_RSA_WITH_AES_256_CBC_SHA256 - ok: openssl s_server ... -cipher AES256-SHA256
#endif
#if ALLOW_RSA_WITH_AES_128_GCM_SHA256
0x00,0x9C, //13 TLS_RSA_WITH_AES_128_GCM_SHA256 - ok: openssl s_server ... -cipher AES128-GCM-SHA256
#endif
// 0x00,0x9D, // TLS_RSA_WITH_AES_256_GCM_SHA384 - openssl s_server ... -cipher AES256-GCM-SHA384: "decryption failed or bad record mac"
#if ALLOW_RSA_NULL_SHA256
0x00,0x3B, // TLS_RSA_WITH_NULL_SHA256
@@ -1533,16 +1532,12 @@ static void send_client_hello_and_alloc_hsd(tls_state_t *tls, const char *sni)
};
static const uint8_t supported_groups[] = {
0x00,0x0a, //extension_type: "supported_groups"
0x00,2 * (1 + ALLOW_CURVE_P256 + ALLOW_CURVE_X25519), //ext len
0x00,2 * (0 + ALLOW_CURVE_P256 + ALLOW_CURVE_X25519), //list len
#if ALLOW_CURVE_P256
0x00,0x17, //curve_secp256r1 (aka P256, aka prime256v1)
#endif
0x00,0x06, //ext len
0x00,0x04, //list len
0x00,0x17, //curve_secp256r1 (aka P256)
//0x00,0x18, //curve_secp384r1
//0x00,0x19, //curve_secp521r1
#if ALLOW_CURVE_X25519
0x00,0x1d, //curve_x25519 (RFC 7748)
#endif
//0x00,0x1e, //curve_x448 (RFC 7748)
};
//static const uint8_t signature_algorithms[] = {
@@ -1560,7 +1555,7 @@ static void send_client_hello_and_alloc_hsd(tls_state_t *tls, const char *sni)
uint8_t session_id_len;
/* uint8_t session_id[]; */
uint8_t cipherid_len16_hi, cipherid_len16_lo;
uint8_t cipherid[2 * (1 + NUM_CIPHERS)]; /* actually variable */
uint8_t cipherid[2 + NUM_CIPHERS*2]; /* actually variable */
uint8_t comprtypes_len;
uint8_t comprtypes[1]; /* actually variable */
/* Extensions (SNI shown):
@@ -1608,7 +1603,7 @@ static void send_client_hello_and_alloc_hsd(tls_state_t *tls, const char *sni)
memset(record->rand32, 0x11, sizeof(record->rand32));
/* record->session_id_len = 0; - already is */
BUILD_BUG_ON(sizeof(ciphers) != 2 * (1 + 1 + NUM_CIPHERS + 1));
BUILD_BUG_ON(sizeof(ciphers) != 2 + 2 + NUM_CIPHERS*2 + 2);
memcpy(&record->cipherid_len16_hi, ciphers, sizeof(ciphers));
ptr = (void*)(record + 1);
@@ -1705,32 +1700,41 @@ static void get_server_hello(tls_state_t *tls)
/* Set up encryption params based on selected cipher */
#if 0
#if ENABLE_FEATURE_TLS_SHA1
0xC0,0x09, // 1 TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA - ok: wget https://is.gd/
0xC0,0x0A, // 2 TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA - ok: wget https://is.gd/
0xC0,0x13, // 3 TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA - ok: openssl s_server ... -cipher ECDHE-RSA-AES128-SHA
0xC0,0x14, // 4 TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA - ok: openssl s_server ... -cipher ECDHE-RSA-AES256-SHA (might fail with older openssl)
// 0xC0,0x18, // TLS_ECDH_anon_WITH_AES_128_CBC_SHA
// 0xC0,0x19, // TLS_ECDH_anon_WITH_AES_256_CBC_SHA
#endif
0xC0,0x23, // 5 TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 - ok: wget https://is.gd/
// 0xC0,0x24, // TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 - can't do SHA384 yet
0xC0,0x27, // 6 TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 - ok: openssl s_server ... -cipher ECDHE-RSA-AES128-SHA256
// 0xC0,0x28, // TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384 - can't do SHA384 yet
0xC0,0x2B, // 7 TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 - ok: wget https://is.gd/
// 0xC0,0x2C, // TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 - wget https://is.gd/: "TLS error from peer (alert code 20): bad MAC"
//TODO: GCM_SHA384 ciphers can be supported, only need sha384-based PRF?
0xC0,0x2F, // 8 TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 - ok: openssl s_server ... -cipher ECDHE-RSA-AES128-GCM-SHA256
// 0xC0,0x30, // TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 - openssl s_server ... -cipher ECDHE-RSA-AES256-GCM-SHA384: "decryption failed or bad record mac"
//possibly these too:
#if ENABLE_FEATURE_TLS_SHA1
// 0xC0,0x35, // TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA
// 0xC0,0x36, // TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA
#endif
// 0xC0,0x37, // TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256
// 0xC0,0x38, // TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA384 - can't do SHA384 yet
#if ENABLE_FEATURE_TLS_SHA1
0x00,0x2F, // 9 TLS_RSA_WITH_AES_128_CBC_SHA - ok: openssl s_server ... -cipher AES128-SHA
0x00,0x35, //10 TLS_RSA_WITH_AES_256_CBC_SHA - ok: openssl s_server ... -cipher AES256-SHA
#endif
0x00,0x3C, //11 TLS_RSA_WITH_AES_128_CBC_SHA256 - ok: openssl s_server ... -cipher AES128-SHA256
0x00,0x3D, //12 TLS_RSA_WITH_AES_256_CBC_SHA256 - ok: openssl s_server ... -cipher AES256-SHA256
0x00,0x9C, //13 TLS_RSA_WITH_AES_128_GCM_SHA256 - ok: openssl s_server ... -cipher AES128-GCM-SHA256
// 0x00,0x9D, // TLS_RSA_WITH_AES_256_GCM_SHA384 - openssl s_server ... -cipher AES256-GCM-SHA384: "decryption failed or bad record mac"
#if ALLOW_RSA_NULL_SHA256
0x00,0x3B, // TLS_RSA_WITH_NULL_SHA256
#endif
#endif
cipherid1 = cipherid[1];
tls->cipher_id = 0x100 * cipherid[0] + cipherid1;
@@ -1883,12 +1887,10 @@ static void process_server_key(tls_state_t *tls, int len)
keybuf += 4;
switch (t32) {
case _0x03001d20: //curve_x25519
dbg("got x25519 eccPubKey\n");
tls->flags |= GOT_EC_CURVE_X25519;
memcpy(tls->hsd->ecc_pub_key32, keybuf, 32);
break;
case _0x03001741: //curve_secp256r1 (aka P256)
dbg("got P256 eccPubKey\n");
/* P256 point can be transmitted odd- or even-compressed
* (first byte is 3 or 2) or uncompressed (4).
*/
@@ -1901,6 +1903,7 @@ static void process_server_key(tls_state_t *tls, int len)
}
tls->flags |= GOT_EC_KEY;
dbg("got eccPubKey\n");
}
static void send_empty_client_cert(tls_state_t *tls)
@@ -1941,7 +1944,7 @@ static void send_client_key_exchange(tls_state_t *tls)
if (!(tls->flags & NEED_EC_KEY)) {
/* RSA */
if (!(tls->flags & GOT_CERT_RSA_KEY_ALG))
bb_simple_error_msg_and_die("server cert is not RSA");
bb_simple_error_msg("server cert is not RSA");
tls_get_random(premaster, RSA_PREMASTER_SIZE);
if (TLS_DEBUG_FIXED_SECRETS)
@@ -2327,47 +2330,6 @@ void FAST_FUNC tls_run_copy_loop(tls_state_t *tls, unsigned flags)
const int INBUF_STEP = 4 * 1024;
struct pollfd pfds[2];
#if 0
// Debug aid for comparing P256 implementations.
// Enable this, set SP_DEBUG and FIXED_SECRET to 1,
// and add
// tls_run_copy_loop(NULL, 0);
// e.g. at the very beginning of wget_main()
//
{
uint8_t ecc_pub_key32[2 * 32];
uint8_t pubkey2x32[2 * 32];
uint8_t premaster32[32];
//Fixed input key:
// memset(ecc_pub_key32, 0xee, sizeof(ecc_pub_key32));
//Fixed 000000000000000000000000000000000000ab000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
// memset(ecc_pub_key32, 0x00, sizeof(ecc_pub_key32));
// ecc_pub_key32[18] = 0xab;
//Random key:
// tls_get_random(ecc_pub_key32, sizeof(ecc_pub_key32));
//Biased random (almost all zeros or almost all ones):
srand(time(NULL) ^ getpid());
if (rand() & 1)
memset(ecc_pub_key32, 0x00, sizeof(ecc_pub_key32));
else
memset(ecc_pub_key32, 0xff, sizeof(ecc_pub_key32));
ecc_pub_key32[rand() & 0x3f] = rand();
xmove_fd(xopen("p256.OLD", O_WRONLY | O_CREAT | O_TRUNC), 2);
curve_P256_compute_pubkey_and_premaster(
pubkey2x32, premaster32,
/*point:*/ ecc_pub_key32
);
xmove_fd(xopen("p256.NEW", O_WRONLY | O_CREAT | O_TRUNC), 2);
curve_P256_compute_pubkey_and_premaster_NEW(
pubkey2x32, premaster32,
/*point:*/ ecc_pub_key32
);
exit(1);
}
#endif
pfds[0].fd = STDIN_FILENO;
pfds[0].events = POLLIN;
pfds[1].fd = tls->ifd;
+1 -4
View File
@@ -101,6 +101,7 @@ void xorbuf_aligned_AES_BLOCK_SIZE(void* buf, const void* mask) FAST_FUNC;
#include "tls_pstm.h"
#include "tls_symmetric.h"
#include "tls_aes.h"
#include "tls_aesgcm.h"
#include "tls_rsa.h"
@@ -116,7 +117,3 @@ void curve_x25519_compute_pubkey_and_premaster(
void curve_P256_compute_pubkey_and_premaster(
uint8_t *pubkey2x32, uint8_t *premaster32,
const uint8_t *peerkey2x32) FAST_FUNC;
void curve_P256_compute_pubkey_and_premaster_NEW(
uint8_t *pubkey2x32, uint8_t *premaster32,
const uint8_t *peerkey2x32) FAST_FUNC;
+65 -63
View File
@@ -63,22 +63,16 @@ static void fprime_select(byte *dst, const byte *zero, const byte *one, byte con
}
#endif
#if 0 /* constant-time */
static void fe_select(byte *dst,
const byte *src,
const byte *zero, const byte *one,
byte condition)
{
const byte mask = -condition;
int i;
for (i = 0; i < F25519_SIZE; i++)
dst[i] = dst[i] ^ (mask & (src[i] ^ dst[i]));
dst[i] = zero[i] ^ (mask & (one[i] ^ zero[i]));
}
#else
# define fe_select(dst, src, condition) do { \
if (condition) lm_copy(dst, src); \
} while (0)
#endif
#if 0 //UNUSED
static void raw_add(byte *x, const byte *p)
@@ -187,7 +181,7 @@ static void fprime_mul(byte *r, const byte *a, const byte *b,
#if 0 //UNUSED
static void fe_load(byte *x, word32 c)
{
int i;
word32 i;
for (i = 0; i < sizeof(c); i++) {
x[i] = c;
@@ -199,21 +193,6 @@ static void fe_load(byte *x, word32 c)
}
#endif
static void fe_reduce(byte *x, word32 c)
{
int i;
/* Reduce using 2^255 = 19 mod p */
x[31] = c & 127;
c = (c >> 7) * 19;
for (i = 0; i < F25519_SIZE; i++) {
c += x[i];
x[i] = (byte)c;
c >>= 8;
}
}
static void fe_normalize(byte *x)
{
byte minusp[F25519_SIZE];
@@ -221,7 +200,14 @@ static void fe_normalize(byte *x)
int i;
/* Reduce using 2^255 = 19 mod p */
fe_reduce(x, x[31]);
c = (x[31] >> 7) * 19;
x[31] &= 127;
for (i = 0; i < F25519_SIZE; i++) {
c += x[i];
x[i] = (byte)c;
c >>= 8;
}
/* The number is now less than 2^255 + 18, and therefore less than
* 2p. Try subtracting p, and conditionally load the subtracted
@@ -239,7 +225,7 @@ static void fe_normalize(byte *x)
minusp[31] = (byte)c;
/* Load x-p if no underflow */
fe_select(x, minusp, !(c & (1<<15)));
fe_select(x, minusp, x, (c >> 15) & 1);
}
static void lm_add(byte* r, const byte* a, const byte* b)
@@ -255,7 +241,14 @@ static void lm_add(byte* r, const byte* a, const byte* b)
}
/* Reduce with 2^255 = 19 mod p */
fe_reduce(r, c);
r[31] &= 127;
c = (c >> 7) * 19;
for (i = 0; i < F25519_SIZE; i++) {
c += r[i];
r[i] = (byte)c;
c >>= 8;
}
}
static void lm_sub(byte* r, const byte* a, const byte* b)
@@ -265,15 +258,21 @@ static void lm_sub(byte* r, const byte* a, const byte* b)
/* Calculate a + 2p - b, to avoid underflow */
c = 218;
for (i = 0; i < F25519_SIZE - 1; i++) {
for (i = 0; i + 1 < F25519_SIZE; i++) {
c += 65280 + ((word32)a[i]) - ((word32)b[i]);
r[i] = c;
c >>= 8;
}
c += ((word32)a[31]) - ((word32)b[31]);
r[31] = c & 127;
c = (c >> 7) * 19;
fe_reduce(r, c);
for (i = 0; i < F25519_SIZE; i++) {
c += r[i];
r[i] = c;
c >>= 8;
}
}
#if 0 //UNUSED
@@ -284,15 +283,21 @@ static void lm_neg(byte* r, const byte* a)
/* Calculate 2p - a, to avoid underflow */
c = 218;
for (i = 0; i < F25519_SIZE - 1; i++) {
for (i = 0; i + 1 < F25519_SIZE; i++) {
c += 65280 - ((word32)a[i]);
r[i] = c;
c >>= 8;
}
c -= ((word32)a[31]);
r[31] = c & 127;
c = (c >> 7) * 19;
fe_reduce(r, c);
for (i = 0; i < F25519_SIZE; i++) {
c += r[i];
r[i] = c;
c >>= 8;
}
}
#endif
@@ -315,7 +320,14 @@ static void fe_mul__distinct(byte *r, const byte *a, const byte *b)
r[i] = c;
}
fe_reduce(r, c);
r[31] &= 127;
c = (c >> 7) * 19;
for (i = 0; i < F25519_SIZE; i++) {
c += r[i];
r[i] = c;
c >>= 8;
}
}
#if 0 //UNUSED
@@ -339,7 +351,15 @@ static void fe_mul_c(byte *r, const byte *a, word32 b)
r[i] = c;
}
fe_reduce(r, c);
r[31] &= 127;
c >>= 7;
c *= 19;
for (i = 0; i < F25519_SIZE; i++) {
c += r[i];
r[i] = c;
c >>= 8;
}
}
static void fe_inv__distinct(byte *r, const byte *x)
@@ -528,32 +548,26 @@ static void curve25519(byte *result, const byte *e, const byte *q)
{
int i;
struct Z {
struct {
/* for bbox's special case of q == NULL meaning "use basepoint" */
/*static const*/ uint8_t basepoint9[CURVE25519_KEYSIZE]; // = {9};
/* from wolfssl-3.15.3/wolfssl/wolfcrypt/fe_operations.h */
/*static const*/ byte f25519_one[F25519_SIZE]; // = {1};
/* Predecessor: P_(m-1) */
byte xm1[F25519_SIZE]; // = {1};
byte zm1[F25519_SIZE]; // = {0};
/* Current point: P_m */
byte xm[F25519_SIZE];
byte zm[F25519_SIZE]; // = {1};
/* Temporaries */
byte xms[F25519_SIZE];
byte zms[F25519_SIZE];
/* Predecessor: P_(m-1) */
byte xm1[F25519_SIZE]; // = {1};
byte zm1[F25519_SIZE]; // = {0};
} z;
uint8_t *XM1 = (uint8_t*)&z + offsetof(struct Z,xm1); // gcc 11.0.0 workaround
#define basepoint9 z.basepoint9
#define f25519_one z.f25519_one
#define xm1 z.xm1
#define zm1 z.zm1
#define xm z.xm
#define zm z.zm
#define xms z.xms
#define zms z.zms
#define xm1 z.xm1
#define zm1 z.zm1
memset(&z, 0, sizeof(z));
f25519_one[0] = 1;
zm[0] = 1;
@@ -569,8 +583,8 @@ static void curve25519(byte *result, const byte *e, const byte *q)
for (i = 253; i >= 0; i--) {
const int bit = (e[i >> 3] >> (i & 7)) & 1;
// byte xms[F25519_SIZE];
// byte zms[F25519_SIZE];
byte xms[F25519_SIZE];
byte zms[F25519_SIZE];
/* From P_m and P_(m-1), compute P_(2m) and P_(2m-1) */
xc_diffadd(xm1, zm1, q, f25519_one, xm, zm, xm1, zm1);
@@ -583,22 +597,10 @@ static void curve25519(byte *result, const byte *e, const byte *q)
* bit = 1 --> (P_(2m+1), P_(2m))
* bit = 0 --> (P_(2m), P_(2m-1))
*/
#if 0
fe_select(xm1, xm, bit);
fe_select(zm1, zm, bit);
fe_select(xm, xms, bit);
fe_select(zm, zms, bit);
#else
// same as above in about 50 bytes smaller code, but
// requires that in-memory order is exactly xm1,zm1,xm,zm,xms,zms
if (bit) {
//memcpy(xm1, xm, 4 * F25519_SIZE);
//^^^ gcc 11.0.0 warns of overlapping memcpy
//memmove(xm1, xm, 4 * F25519_SIZE);
//^^^ gcc 11.0.0 warns of out-of-bounds access to xm1[]
memmove(XM1, XM1 + 2 * F25519_SIZE, 4 * F25519_SIZE);
}
#endif
fe_select(xm1, xm1, xm, bit);
fe_select(zm1, zm1, zm, bit);
fe_select(xm, xm, xms, bit);
fe_select(zm, zm, zms, bit);
}
/* Freeze out of projective coordinates */
+1
View File
@@ -283,3 +283,4 @@ extern int32 pstm_invmod(psPool_t *pool, pstm_int * a, pstm_int * b,
typedef int32 pstm_int;
#endif /* !DISABLE_PSTM */
#endif /* _h_PSTMATH */
+540 -1136
View File
File diff suppressed because it is too large. Load diff
+511
View File
@@ -0,0 +1,511 @@
/*
* Copyright (C) 2017 Denys Vlasenko
*
* Licensed under GPLv2, see file LICENSE in this source tree.
*/
/* The part below is a section of matrixssl-3-7-2b-open/crypto/cryptolib.h
* Changes are flagged with //bbox
*/
/******************************************************************************/
/* 32-bit Rotates */
/******************************************************************************/
#if defined(_MSC_VER)
/******************************************************************************/
/* instrinsic rotate */
#include <stdlib.h>
#pragma intrinsic(_lrotr,_lrotl)
#define ROR(x,n) _lrotr(x,n)
#define ROL(x,n) _lrotl(x,n)
/******************************************************************************/
#elif defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__)) && \
!defined(INTEL_CC) && !defined(PS_NO_ASM)
static ALWAYS_INLINE unsigned ROL(unsigned word, int i)
{
if (__builtin_constant_p(i)) { //box
// Rotates by constant use fewer registers,
// and on many Intel CPUs rotates by %cl take 2 cycles, not 1.
asm ("roll %2,%0"
:"=r" (word)
:"0" (word),"i" (i));
return word;
} //box
asm ("roll %%cl,%0"
:"=r" (word)
:"0" (word),"c" (i));
return word;
}
static ALWAYS_INLINE unsigned ROR(unsigned word, int i)
{
if (__builtin_constant_p(i)) { //box
asm ("rorl %2,%0"
:"=r" (word)
:"0" (word),"i" (i));
return word;
} //box
asm ("rorl %%cl,%0"
:"=r" (word)
:"0" (word),"c" (i));
return word;
}
/******************************************************************************/
#else
/* rotates the hard way */
#define ROL(x, y) \
( (((unsigned long)(x)<<(unsigned long)((y)&31)) | \
(((unsigned long)(x)&0xFFFFFFFFUL)>>(unsigned long)(32-((y)&31)))) & \
0xFFFFFFFFUL)
#define ROR(x, y) \
( ((((unsigned long)(x)&0xFFFFFFFFUL)>>(unsigned long)((y)&31)) | \
((unsigned long)(x)<<(unsigned long)(32-((y)&31)))) & 0xFFFFFFFFUL)
#endif /* 32-bit Rotates */
/******************************************************************************/
#ifdef HAVE_NATIVE_INT64
#ifdef _MSC_VER
#define CONST64(n) n ## ui64
#else
#define CONST64(n) n ## ULL
#endif
#endif
/******************************************************************************/
/*
Endian helper macros
*/
#if defined (ENDIAN_NEUTRAL)
#define STORE32L(x, y) { \
(y)[3] = (unsigned char)(((x)>>24)&255); \
(y)[2] = (unsigned char)(((x)>>16)&255); \
(y)[1] = (unsigned char)(((x)>>8)&255); \
(y)[0] = (unsigned char)((x)&255); \
}
#define LOAD32L(x, y) { \
x = ((unsigned long)((y)[3] & 255)<<24) | \
((unsigned long)((y)[2] & 255)<<16) | \
((unsigned long)((y)[1] & 255)<<8) | \
((unsigned long)((y)[0] & 255)); \
}
#define STORE64L(x, y) { \
(y)[7] = (unsigned char)(((x)>>56)&255); \
(y)[6] = (unsigned char)(((x)>>48)&255); \
(y)[5] = (unsigned char)(((x)>>40)&255); \
(y)[4] = (unsigned char)(((x)>>32)&255); \
(y)[3] = (unsigned char)(((x)>>24)&255); \
(y)[2] = (unsigned char)(((x)>>16)&255); \
(y)[1] = (unsigned char)(((x)>>8)&255); \
(y)[0] = (unsigned char)((x)&255); \
}
#define LOAD64L(x, y) { \
x = (((uint64)((y)[7] & 255))<<56)|(((uint64)((y)[6] & 255))<<48)| \
(((uint64)((y)[5] & 255))<<40)|(((uint64)((y)[4] & 255))<<32)| \
(((uint64)((y)[3] & 255))<<24)|(((uint64)((y)[2] & 255))<<16)| \
(((uint64)((y)[1] & 255))<<8)|(((uint64)((y)[0] & 255))); \
}
#define STORE32H(x, y) { \
(y)[0] = (unsigned char)(((x)>>24)&255); \
(y)[1] = (unsigned char)(((x)>>16)&255); \
(y)[2] = (unsigned char)(((x)>>8)&255); \
(y)[3] = (unsigned char)((x)&255); \
}
#define LOAD32H(x, y) { \
x = ((unsigned long)((y)[0] & 255)<<24) | \
((unsigned long)((y)[1] & 255)<<16) | \
((unsigned long)((y)[2] & 255)<<8) | \
((unsigned long)((y)[3] & 255)); \
}
#define STORE64H(x, y) { \
(y)[0] = (unsigned char)(((x)>>56)&255); \
(y)[1] = (unsigned char)(((x)>>48)&255); \
(y)[2] = (unsigned char)(((x)>>40)&255); \
(y)[3] = (unsigned char)(((x)>>32)&255); \
(y)[4] = (unsigned char)(((x)>>24)&255); \
(y)[5] = (unsigned char)(((x)>>16)&255); \
(y)[6] = (unsigned char)(((x)>>8)&255); \
(y)[7] = (unsigned char)((x)&255); \
}
#define LOAD64H(x, y) { \
x = (((uint64)((y)[0] & 255))<<56)|(((uint64)((y)[1] & 255))<<48) | \
(((uint64)((y)[2] & 255))<<40)|(((uint64)((y)[3] & 255))<<32) | \
(((uint64)((y)[4] & 255))<<24)|(((uint64)((y)[5] & 255))<<16) | \
(((uint64)((y)[6] & 255))<<8)|(((uint64)((y)[7] & 255))); \
}
#endif /* ENDIAN_NEUTRAL */
#ifdef ENDIAN_LITTLE
#define STORE32H(x, y) { \
(y)[0] = (unsigned char)(((x)>>24)&255); \
(y)[1] = (unsigned char)(((x)>>16)&255); \
(y)[2] = (unsigned char)(((x)>>8)&255); \
(y)[3] = (unsigned char)((x)&255); \
}
#define LOAD32H(x, y) { \
x = ((unsigned long)((y)[0] & 255)<<24) | \
((unsigned long)((y)[1] & 255)<<16) | \
((unsigned long)((y)[2] & 255)<<8) | \
((unsigned long)((y)[3] & 255)); \
}
#define STORE64H(x, y) { \
(y)[0] = (unsigned char)(((x)>>56)&255); \
(y)[1] = (unsigned char)(((x)>>48)&255); \
(y)[2] = (unsigned char)(((x)>>40)&255); \
(y)[3] = (unsigned char)(((x)>>32)&255); \
(y)[4] = (unsigned char)(((x)>>24)&255); \
(y)[5] = (unsigned char)(((x)>>16)&255); \
(y)[6] = (unsigned char)(((x)>>8)&255); \
(y)[7] = (unsigned char)((x)&255); \
}
#define LOAD64H(x, y) { \
x = (((uint64)((y)[0] & 255))<<56)|(((uint64)((y)[1] & 255))<<48) | \
(((uint64)((y)[2] & 255))<<40)|(((uint64)((y)[3] & 255))<<32) | \
(((uint64)((y)[4] & 255))<<24)|(((uint64)((y)[5] & 255))<<16) | \
(((uint64)((y)[6] & 255))<<8)|(((uint64)((y)[7] & 255))); }
#ifdef ENDIAN_32BITWORD
#define STORE32L(x, y) { \
unsigned long __t = (x); memcpy(y, &__t, 4); \
}
#define LOAD32L(x, y) memcpy(&(x), y, 4);
#define STORE64L(x, y) { \
(y)[7] = (unsigned char)(((x)>>56)&255); \
(y)[6] = (unsigned char)(((x)>>48)&255); \
(y)[5] = (unsigned char)(((x)>>40)&255); \
(y)[4] = (unsigned char)(((x)>>32)&255); \
(y)[3] = (unsigned char)(((x)>>24)&255); \
(y)[2] = (unsigned char)(((x)>>16)&255); \
(y)[1] = (unsigned char)(((x)>>8)&255); \
(y)[0] = (unsigned char)((x)&255); \
}
#define LOAD64L(x, y) { \
x = (((uint64)((y)[7] & 255))<<56)|(((uint64)((y)[6] & 255))<<48)| \
(((uint64)((y)[5] & 255))<<40)|(((uint64)((y)[4] & 255))<<32)| \
(((uint64)((y)[3] & 255))<<24)|(((uint64)((y)[2] & 255))<<16)| \
(((uint64)((y)[1] & 255))<<8)|(((uint64)((y)[0] & 255))); \
}
#else /* 64-bit words then */
#define STORE32L(x, y) \
{ unsigned long __t = (x); memcpy(y, &__t, 4); }
#define LOAD32L(x, y) \
{ memcpy(&(x), y, 4); x &= 0xFFFFFFFF; }
#define STORE64L(x, y) \
{ uint64 __t = (x); memcpy(y, &__t, 8); }
#define LOAD64L(x, y) \
{ memcpy(&(x), y, 8); }
#endif /* ENDIAN_64BITWORD */
#endif /* ENDIAN_LITTLE */
#ifdef ENDIAN_BIG
#define STORE32L(x, y) { \
(y)[3] = (unsigned char)(((x)>>24)&255); \
(y)[2] = (unsigned char)(((x)>>16)&255); \
(y)[1] = (unsigned char)(((x)>>8)&255); \
(y)[0] = (unsigned char)((x)&255); \
}
#define LOAD32L(x, y) { \
x = ((unsigned long)((y)[3] & 255)<<24) | \
((unsigned long)((y)[2] & 255)<<16) | \
((unsigned long)((y)[1] & 255)<<8) | \
((unsigned long)((y)[0] & 255)); \
}
#define STORE64L(x, y) { \
(y)[7] = (unsigned char)(((x)>>56)&255); \
(y)[6] = (unsigned char)(((x)>>48)&255); \
(y)[5] = (unsigned char)(((x)>>40)&255); \
(y)[4] = (unsigned char)(((x)>>32)&255); \
(y)[3] = (unsigned char)(((x)>>24)&255); \
(y)[2] = (unsigned char)(((x)>>16)&255); \
(y)[1] = (unsigned char)(((x)>>8)&255); \
(y)[0] = (unsigned char)((x)&255); \
}
#define LOAD64L(x, y) { \
x = (((uint64)((y)[7] & 255))<<56)|(((uint64)((y)[6] & 255))<<48) | \
(((uint64)((y)[5] & 255))<<40)|(((uint64)((y)[4] & 255))<<32) | \
(((uint64)((y)[3] & 255))<<24)|(((uint64)((y)[2] & 255))<<16) | \
(((uint64)((y)[1] & 255))<<8)|(((uint64)((y)[0] & 255))); \
}
#ifdef ENDIAN_32BITWORD
#define STORE32H(x, y) \
{ unsigned int __t = (x); memcpy(y, &__t, 4); }
#define LOAD32H(x, y) memcpy(&(x), y, 4);
#define STORE64H(x, y) { \
(y)[0] = (unsigned char)(((x)>>56)&255); \
(y)[1] = (unsigned char)(((x)>>48)&255); \
(y)[2] = (unsigned char)(((x)>>40)&255); \
(y)[3] = (unsigned char)(((x)>>32)&255); \
(y)[4] = (unsigned char)(((x)>>24)&255); \
(y)[5] = (unsigned char)(((x)>>16)&255); \
(y)[6] = (unsigned char)(((x)>>8)&255); \
(y)[7] = (unsigned char)((x)&255); \
}
#define LOAD64H(x, y) { \
x = (((uint64)((y)[0] & 255))<<56)|(((uint64)((y)[1] & 255))<<48)| \
(((uint64)((y)[2] & 255))<<40)|(((uint64)((y)[3] & 255))<<32)| \
(((uint64)((y)[4] & 255))<<24)|(((uint64)((y)[5] & 255))<<16)| \
(((uint64)((y)[6] & 255))<<8)| (((uint64)((y)[7] & 255))); \
}
#else /* 64-bit words then */
#define STORE32H(x, y) \
{ unsigned long __t = (x); memcpy(y, &__t, 4); }
#define LOAD32H(x, y) \
{ memcpy(&(x), y, 4); x &= 0xFFFFFFFF; }
#define STORE64H(x, y) \
{ uint64 __t = (x); memcpy(y, &__t, 8); }
#define LOAD64H(x, y) \
{ memcpy(&(x), y, 8); }
#endif /* ENDIAN_64BITWORD */
#endif /* ENDIAN_BIG */
#ifdef HAVE_NATIVE_INT64
#define ROL64c(x, y) \
( (((x)<<((uint64)(y)&63)) | \
(((x)&CONST64(0xFFFFFFFFFFFFFFFF))>>((uint64)64-((y)&63)))) & CONST64(0xFFFFFFFFFFFFFFFF))
#define ROR64c(x, y) \
( ((((x)&CONST64(0xFFFFFFFFFFFFFFFF))>>((uint64)(y)&CONST64(63))) | \
((x)<<((uint64)(64-((y)&CONST64(63)))))) & CONST64(0xFFFFFFFFFFFFFFFF))
#endif /* HAVE_NATIVE_INT64 */
/******************************************************************************/
/* The part below is taken almost verbatim from matrixssl-3-7-2b-open/crypto/symmetric/.
* Changes are flagged with //bbox
*/
/**
* @file symmetric.h
* @version 33ef80f (HEAD, tag: MATRIXSSL-3-7-2-OPEN, tag: MATRIXSSL-3-7-2-COMM, origin/master, origin/HEAD, master)
*
* Header for internal symmetric key cryptography support.
*/
/*
* Copyright (c) 2013-2015 INSIDE Secure Corporation
* Copyright (c) PeerSec Networks, 2002-2011
* All Rights Reserved
*
* The latest version of this code is available at http://www.matrixssl.org
*
* This software is open source; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This General Public License does NOT permit incorporating this software
* into proprietary programs. If you are unable to comply with the GPL, a
* commercial license for this software may be purchased from INSIDE at
* http://www.insidesecure.com/eng/Company/Locations
*
* This program is distributed in WITHOUT ANY WARRANTY; without even the
* implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* http://www.gnu.org/copyleft/gpl.html
*/
/******************************************************************************/
#ifndef _h_PS_SYMMETRIC
#define _h_PS_SYMMETRIC
/******************************************************************************/
#ifdef USE_AES
/******************************************************************************/
#ifndef USE_AES_CBC_EXTERNAL
typedef struct {
uint32 eK[64], dK[64];
int32 Nr;
} psAesKey_t;
typedef struct {
int32 blocklen;
unsigned char IV[16];
psAesKey_t key;
#if defined(USE_AES_GCM) || defined(USE_AES_CCM)
unsigned char EncCtr[16];
unsigned char CtrBlock[16];
#endif
#ifdef USE_AES_GCM
unsigned char gInit[16];
uint32 TagTemp[4];
unsigned char Hash_SubKey[16];
uint32 ProcessedBitCount[4];
uint32 InputBufferCount;
uint32 OutputBufferCount;
union
{
unsigned char Buffer[128];
uint32 BufferAlignment;
} Input;
#endif /* USE_AES_GCM */
#ifdef USE_AES_CCM
uint32_t ccmTagTemp[16 / sizeof(uint32_t)]; /* 32 */
union
{
/* Used for formatting IV. */
uint8_t Temporary[16];
/* Used for processing Mac. */
uint8_t Y0[16];
} u; /* 48 */
#endif /* USE_AES_CCM */
} psAesCipher_t;
#endif /* USE_AES_CBC_EXTERNAL */
#endif /* USE_AES */
#ifdef USE_IDEA
#define SSL_IDEA_KEY_LEN 16
#define SSL_IDEA_IV_LEN 8
#define SSL_IDEA_BLOCK_LEN 8
typedef struct {
uint16 key_schedule[52];
} psIdeaKey_t;
typedef struct {
psIdeaKey_t key;
uint32 IV[2];
short for_encryption;
short inverted;
} idea_CBC;
#endif
/******************************************************************************/
/******************************************************************************/
#ifdef USE_SEED
/******************************************************************************/
#define SSL_SEED_KEY_LEN 16
#define SSL_SEED_IV_LEN 16
typedef struct {
uint32 K[32], dK[32];
} psSeedKey_t;
typedef struct {
int32 blocklen;
unsigned char IV[16];
psSeedKey_t key;
} seed_CBC;
#endif /* USE_SEED */
/******************************************************************************/
/******************************************************************************/
#if defined(USE_3DES) || defined(USE_DES)
/******************************************************************************/
#define DES3_KEY_LEN 24
#define DES3_IV_LEN 8
#define DES_KEY_LEN 8
typedef struct {
uint32 ek[3][32], dk[3][32];
} psDes3Key_t;
/*
A block cipher CBC structure
*/
typedef struct {
int32 blocklen;
unsigned char IV[8];
psDes3Key_t key;
} des3_CBC;
#endif /* USE_3DES || USE_DES */
/******************************************************************************/
/******************************************************************************/
#ifdef USE_ARC4
typedef struct {
unsigned char state[256];
uint32 byteCount;
unsigned char x;
unsigned char y;
} psRc4Key_t;
#endif /* USE_ARC4 */
/******************************************************************************/
#ifdef USE_RC2
typedef struct {
unsigned xkey[64];
} psRc2Key_t;
typedef struct {
int32 blocklen;
unsigned char IV[8];
psRc2Key_t key;
} rc2_CBC;
#endif /* USE_RC2 */
/******************************************************************************/
/* Universal types and defines */
/******************************************************************************/
#define MAXBLOCKSIZE 24
typedef union {
#ifdef USE_RC2
rc2_CBC rc2;
#endif
#ifdef USE_ARC4
psRc4Key_t arc4;
#endif
#ifdef USE_3DES
des3_CBC des3;
#endif
#ifdef USE_AES
psAesCipher_t aes;
#endif
#ifdef USE_SEED
seed_CBC seed;
#endif
#ifdef USE_IDEA
idea_CBC idea;
#endif
} psCipherContext_t;
#define byte(x, n) (((x) >> (8 * (n))) & 255)
#endif /* _h_PS_SYMMETRIC */
/******************************************************************************/
+7 -22
View File
@@ -404,29 +404,14 @@ void FAST_FUNC udhcp_add_simple_option(struct dhcp_packet *packet, uint8_t code,
#endif
/* Find option 'code' in opt_list */
struct option_set* FAST_FUNC udhcp_find_option(struct option_set *opt_list, uint8_t code, bool dhcpv6)
struct option_set* FAST_FUNC udhcp_find_option(struct option_set *opt_list, uint8_t code)
{
IF_NOT_UDHCPC6(bool dhcpv6 = 0;)
uint8_t cur_code;
for (;;) {
if (!opt_list)
return opt_list; /* NULL */
if (!dhcpv6) {
cur_code = opt_list->data[OPT_CODE];
} else {
//FIXME: add support for code > 0xff
if (opt_list->data[D6_OPT_CODE] != 0)
return NULL;
cur_code = opt_list->data[D6_OPT_CODE + 1];
}
if (cur_code >= code) {
if (cur_code == code)
return opt_list;
return NULL;
}
while (opt_list && opt_list->data[OPT_CODE] < code)
opt_list = opt_list->next;
}
if (opt_list && opt_list->data[OPT_CODE] == code)
return opt_list;
return NULL;
}
/* Parse string to IP in network order */
@@ -514,7 +499,7 @@ static NOINLINE void attach_option(
}
#endif
existing = udhcp_find_option(*opt_list, optflag->code, dhcpv6);
existing = udhcp_find_option(*opt_list, optflag->code);
if (!existing) {
/* make a new option */
uint8_t *p = udhcp_insert_new_option(opt_list, optflag->code, length, dhcpv6);
+8 -29
View File
@@ -38,27 +38,13 @@ struct dhcp_packet {
#define BROADCAST_FLAG 0x8000 /* "I need broadcast replies" */
uint32_t ciaddr; /* client IP (if client is in BOUND, RENEW or REBINDING state) */
uint32_t yiaddr; /* 'your' (client) IP address */
/* IP address of "next server" (usually meant to be an TFTP server)
* to use in bootstrap, returned in DHCPOFFER, DHCPACK by server: */
/* IP address of next server to use in bootstrap, returned in DHCPOFFER, DHCPACK by server */
uint32_t siaddr_nip;
/* RFC 951 (BOOTP): "place my (server) IP address in the 'siaddr' field"
* (IOW: unconditionally, not just if we are also a TFTP server).
* DHCP servers don't have to do this, they add SERVER_ID option
* to their reply packets to let client identify lease-giving server.
*/
uint32_t gateway_nip; /* aka 'giaddr': relay agent IP address, else 0 */
uint32_t gateway_nip; /* aka 'giaddr': relay agent IP address */
uint8_t chaddr[16]; /* link-layer client hardware address (MAC) */
uint8_t sname[64]; /* server host name (ASCIZ) */
/* RFC 951 (BOOTP): "If the client wishes to restrict booting
* to a particular server name, it may place [it] in 'sname'"
*/
uint8_t file[128]; /* boot file name (ASCIZ) */
/* RFC 951 (BOOTP): in client requests, "...can be a 'generic' name
* such as 'unix' or 'gateway'; this means 'boot the named program
* configured for my machine'"
*/
/* BOOTP fields end here, BOOTP says optional uint8_t vend[64] follows */
uint32_t cookie; /* DHCP magic bytes: 99,130,83,99 decimal */
uint32_t cookie; /* fixed first four option bytes (99,130,83,99 dec) */
uint8_t options[DHCP_OPTIONS_BUFSIZE + CONFIG_UDHCPC_SLACK_FOR_BUGGY_SERVERS];
};
#define DHCP_PKT_SNAME_LEN 64
@@ -156,21 +142,18 @@ struct dhcp_scan_state {
//#define DHCP_NTP_SERVER 0x2a
//#define DHCP_WINS_SERVER 0x2c
#define DHCP_REQUESTED_IP 0x32 /* 50: sent by client if specific IP is wanted */
#define DHCP_LEASE_TIME 0x33 /* 51: 32bit big-endian */
#define DHCP_OPTION_OVERLOAD 0x34 /* 52: 1 byte */
#define DHCP_MESSAGE_TYPE 0x35 /* 53: 1 byte */
#define DHCP_LEASE_TIME 0x33 /* 51: */
#define DHCP_OPTION_OVERLOAD 0x34 /* 52: */
#define DHCP_MESSAGE_TYPE 0x35 /* 53: */
#define DHCP_SERVER_ID 0x36 /* 54: server's IP */
#define DHCP_PARAM_REQ 0x37 /* 55: list of options client wants */
//#define DHCP_ERR_MESSAGE 0x38 /* 56: error message when sending NAK etc */
#define DHCP_MAX_SIZE 0x39 /* 57: 16bit big-endian */
// 0x3a /* 58: from server: renew time, 32bit big-endian */
// 0x3b /* 59: from server: rebind time, 32bit big-endian */
#define DHCP_MAX_SIZE 0x39 /* 57: */
#define DHCP_VENDOR 0x3c /* 60: client's vendor (a string) */
#define DHCP_CLIENT_ID 0x3d /* 61: by default client's MAC addr, but may be arbitrarily long */
//#define DHCP_TFTP_SERVER_NAME 0x42 /* 66: same as 'sname' field */
//#define DHCP_BOOT_FILE 0x43 /* 67: same as 'file' field */
//#define DHCP_USER_CLASS 0x4d /* 77: RFC 3004. set of LASCII strings. "I am a printer" etc */
// 0x50 /* 80: rapid commit ("I'm ok with getting immediate ACK, not just OFFER"), 0 bytes */
#define DHCP_FQDN 0x51 /* 81: client asks to update DNS to map its FQDN to its new IP */
//#define DHCP_PCODE 0x64 /* 100: RFC 4833. IEEE 1003.1 TZ string */
//#define DHCP_TCODE 0x65 /* 101: RFC 4833. Reference to the TZ database string */
@@ -245,11 +228,7 @@ void udhcp_add_simple_option(struct dhcp_packet *packet, uint8_t code, uint32_t
char *dname_dec(const uint8_t *cstr, int clen, const char *pre) FAST_FUNC;
uint8_t *dname_enc(/*const uint8_t *cstr, int clen,*/ const char *src, int *retlen) FAST_FUNC;
#endif
#if !ENABLE_UDHCPC6
#define udhcp_find_option(opt_list, code, dhcpv6) \
udhcp_find_option(opt_list, code)
#endif
struct option_set *udhcp_find_option(struct option_set *opt_list, uint8_t code, bool dhcpv6) FAST_FUNC;
struct option_set *udhcp_find_option(struct option_set *opt_list, uint8_t code) FAST_FUNC;
// RFC 2131 Table 5: Fields and options used by DHCP clients
//
+2 -3
View File
@@ -888,8 +888,7 @@ int send_d6_release(struct in6_addr *server_ipv6, struct in6_addr *our_cur_ipv6)
if (client6_data.ia_pd)
opt_ptr = mempcpy(opt_ptr, client6_data.ia_pd, client6_data.ia_pd->len + 2+2);
/* Client-id */
///vda
ci = udhcp_find_option(client_data.options, D6_OPT_CLIENTID, /*dhcpv6:*/ 1);
ci = udhcp_find_option(client_data.options, D6_OPT_CLIENTID);
if (ci)
opt_ptr = mempcpy(opt_ptr, ci->data, D6_OPT_DATA + 2+2 + 6);
@@ -1273,7 +1272,7 @@ int udhcpc6_main(int argc UNUSED_PARAM, char **argv)
}
clientid_mac_ptr = NULL;
if (!udhcp_find_option(client_data.options, D6_OPT_CLIENTID, /*dhcpv6:*/ 1)) {
if (!udhcp_find_option(client_data.options, D6_OPT_CLIENTID)) {
/* not set, set the default client ID */
clientid_mac_ptr = udhcp_insert_new_option(
&client_data.options, D6_OPT_CLIENTID,
+3 -3
View File
@@ -658,7 +658,7 @@ static void add_client_options(struct dhcp_packet *packet)
// This will be needed if we remove -V VENDOR_STR in favor of
// -x vendor:VENDOR_STR
//if (!udhcp_find_option(packet.options, DHCP_VENDOR, /*dhcpv6:*/ 0))
//if (!udhcp_find_option(packet.options, DHCP_VENDOR))
// /* not set, set the default vendor ID */
// ...add (DHCP_VENDOR, "udhcp "BB_VER) opt...
}
@@ -676,7 +676,7 @@ static void add_serverid_and_clientid_options(struct dhcp_packet *packet, uint32
* If the client used a 'client identifier' when it obtained the lease,
* it MUST use the same 'client identifier' in the DHCPRELEASE message.
*/
ci = udhcp_find_option(client_data.options, DHCP_CLIENT_ID, /*dhcpv6:*/ 0);
ci = udhcp_find_option(client_data.options, DHCP_CLIENT_ID);
if (ci)
udhcp_add_binary_option(packet, ci->data);
}
@@ -1328,7 +1328,7 @@ int udhcpc_main(int argc UNUSED_PARAM, char **argv)
}
clientid_mac_ptr = NULL;
if (!(opt & OPT_C) && !udhcp_find_option(client_data.options, DHCP_CLIENT_ID, /*dhcpv6:*/ 0)) {
if (!(opt & OPT_C) && !udhcp_find_option(client_data.options, DHCP_CLIENT_ID)) {
/* not suppressed and not set, create default client ID */
clientid_mac_ptr = udhcp_insert_new_option(
&client_data.options, DHCP_CLIENT_ID,
+11 -26
View File
@@ -27,7 +27,7 @@
//kbuild:lib-$(CONFIG_FEATURE_UDHCP_RFC3397) += domain_codec.o
//usage:#define udhcpd_trivial_usage
//usage: "[-fS] [-I ADDR] [-a MSEC]" IF_FEATURE_UDHCP_PORT(" [-P PORT]") " [CONFFILE]"
//usage: "[-fS] [-I ADDR]" IF_FEATURE_UDHCP_PORT(" [-P PORT]") " [CONFFILE]"
//usage:#define udhcpd_full_usage "\n\n"
//usage: "DHCP server\n"
//usage: "\n -f Run in foreground"
@@ -451,8 +451,6 @@ static NOINLINE void read_config(const char *file)
server_data.start_ip = ntohl(server_data.start_ip);
server_data.end_ip = ntohl(server_data.end_ip);
if (server_data.start_ip > server_data.end_ip)
bb_error_msg_and_die("bad start/end IP range in %s", file);
}
static void write_leases(void)
@@ -614,10 +612,6 @@ static void send_packet_to_relay(struct dhcp_packet *dhcp_pkt)
udhcp_send_kernel_packet(dhcp_pkt,
server_data.server_nip, SERVER_PORT,
dhcp_pkt->gateway_nip, SERVER_PORT,
/* Yes, relay agents receive (and send) all their packets on SERVER_PORT,
* even those which are clients' requests and would normally
* (i.e. without relay) use CLIENT_PORT. See RFC 1542.
*/
server_data.interface);
}
@@ -864,6 +858,7 @@ int udhcpd_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
int udhcpd_main(int argc UNUSED_PARAM, char **argv)
{
int server_socket = -1, retval;
uint8_t *state;
unsigned timeout_end;
unsigned num_ips;
unsigned opt;
@@ -882,12 +877,6 @@ int udhcpd_main(int argc UNUSED_PARAM, char **argv)
/* Setup the signal pipe on fds 3,4 - must be before openlog() */
udhcp_sp_setup();
#define OPT_f (1 << 0)
#define OPT_S (1 << 1)
#define OPT_I (1 << 2)
#define OPT_v (1 << 3)
#define OPT_a (1 << 4)
#define OPT_P (1 << 5)
opt = getopt32(argv, "^"
"fSI:va:"IF_FEATURE_UDHCP_PORT("P:")
"\0"
@@ -898,24 +887,24 @@ int udhcpd_main(int argc UNUSED_PARAM, char **argv)
, &str_a
IF_FEATURE_UDHCP_PORT(, &str_P)
IF_UDHCP_VERBOSE(, &dhcp_verbose)
);
if (!(opt & OPT_f)) { /* no -f */
);
if (!(opt & 1)) { /* no -f */
bb_daemonize_or_rexec(0, argv);
logmode = LOGMODE_NONE;
}
/* update argv after the possible vfork+exec in daemonize */
argv += optind;
if (opt & OPT_S) {
if (opt & 2) { /* -S */
openlog(applet_name, LOG_PID, LOG_DAEMON);
logmode |= LOGMODE_SYSLOG;
}
if (opt & OPT_I) {
if (opt & 4) { /* -I */
len_and_sockaddr *lsa = xhost_and_af2sockaddr(str_I, 0, AF_INET);
server_data.server_nip = lsa->u.sin.sin_addr.s_addr;
free(lsa);
}
#if ENABLE_FEATURE_UDHCP_PORT
if (opt & OPT_P) {
if (opt & 32) { /* -P */
SERVER_PORT = xatou16(str_P);
CLIENT_PORT = SERVER_PORT + 1;
}
@@ -935,7 +924,7 @@ int udhcpd_main(int argc UNUSED_PARAM, char **argv)
bb_simple_info_msg("started, v"BB_VER);
option = udhcp_find_option(server_data.options, DHCP_LEASE_TIME, /*dhcpv6:*/ 0);
option = udhcp_find_option(server_data.options, DHCP_LEASE_TIME);
server_data.max_lease_sec = DEFAULT_LEASE_TIME;
if (option) {
move_from_unaligned32(server_data.max_lease_sec, option->data + OPT_DATA);
@@ -971,7 +960,6 @@ int udhcpd_main(int argc UNUSED_PARAM, char **argv)
struct dhcp_packet packet;
int bytes;
int tv;
uint8_t *msg_type;
uint8_t *server_id_opt;
uint8_t *requested_ip_opt;
uint32_t requested_nip;
@@ -1029,9 +1017,6 @@ int udhcpd_main(int argc UNUSED_PARAM, char **argv)
* socket read inside this call is restarted on caught signals.
*/
bytes = udhcp_recv_kernel_packet(&packet, server_socket);
//NB: we do not check source port here. Should we?
//It should be CLIENT_PORT for clients,
//or SERVER_PORT for relay agents (in which case giaddr must be != 0.0.0.0)
if (bytes < 0) {
/* bytes can also be -2 ("bad packet data") */
if (bytes == -1 && errno != EINTR) {
@@ -1049,8 +1034,8 @@ int udhcpd_main(int argc UNUSED_PARAM, char **argv)
bb_info_msg("not a REQUEST%s", ", ignoring packet");
continue;
}
msg_type = udhcp_get_option(&packet, DHCP_MESSAGE_TYPE);
if (!msg_type || msg_type[0] < DHCP_MINTYPE || msg_type[0] > DHCP_MAXTYPE) {
state = udhcp_get_option(&packet, DHCP_MESSAGE_TYPE);
if (state == NULL || state[0] < DHCP_MINTYPE || state[0] > DHCP_MAXTYPE) {
bb_info_msg("no or bad message type option%s", ", ignoring packet");
continue;
}
@@ -1086,7 +1071,7 @@ int udhcpd_main(int argc UNUSED_PARAM, char **argv)
move_from_unaligned32(requested_nip, requested_ip_opt);
}
switch (msg_type[0]) {
switch (state[0]) {
case DHCPDISCOVER:
log1("received %s", "DISCOVER");
+23 -40
View File
@@ -17,8 +17,7 @@
//usage:#define dhcprelay_trivial_usage
//usage: "CLIENT_IFACE[,CLIENT_IFACE2]... SERVER_IFACE [SERVER_IP]"
//usage:#define dhcprelay_full_usage "\n\n"
//usage: "Relay DHCP requests between clients and server.\n"
//usage: "Without SERVER_IP, requests are broadcast on SERVER_IFACE."
//usage: "Relay DHCP requests between clients and server"
#include "common.h"
@@ -32,7 +31,7 @@
/* This list holds information about clients. The xid_* functions manipulate this list. */
struct xid_item {
unsigned timestamp;
unsigned iface_no;
int client;
uint32_t xid;
struct sockaddr_in ip;
struct xid_item *next;
@@ -41,7 +40,7 @@ struct xid_item {
#define dhcprelay_xid_list (*(struct xid_item*)bb_common_bufsiz1)
#define INIT_G() do { setup_common_bufsiz(); } while (0)
static struct xid_item *xid_add(uint32_t xid, struct sockaddr_in *ip, unsigned iface_no)
static struct xid_item *xid_add(uint32_t xid, struct sockaddr_in *ip, int client)
{
struct xid_item *item;
@@ -51,7 +50,7 @@ static struct xid_item *xid_add(uint32_t xid, struct sockaddr_in *ip, unsigned i
/* add xid entry */
item->ip = *ip;
item->xid = xid;
item->iface_no = iface_no;
item->client = client;
item->timestamp = monotonic_sec();
item->next = dhcprelay_xid_list.next;
dhcprelay_xid_list.next = item;
@@ -128,10 +127,10 @@ static int get_dhcp_packet_type(struct dhcp_packet *p)
* make_iface_list - parses client/server interface names
* returns array
*/
static char **make_iface_list(char **client_and_server_ifaces, unsigned *client_number)
static char **make_iface_list(char **client_and_server_ifaces, int *client_number)
{
char *s, **iface_list;
unsigned i, cn;
int i, cn;
/* get number of items */
cn = 2; /* 1 server iface + at least 1 client one */
@@ -166,9 +165,9 @@ static char **make_iface_list(char **client_and_server_ifaces, unsigned *client_
/* Creates listen sockets (in fds) bound to client and server ifaces,
* and returns numerically max fd.
*/
static unsigned init_sockets(char **iface_list, unsigned num_clients, int *fds)
static int init_sockets(char **iface_list, int num_clients, int *fds)
{
unsigned i, n;
int i, n;
n = 0;
for (i = 0; i < num_clients; i++) {
@@ -196,14 +195,13 @@ static int sendto_ip4(int sock, const void *msg, int msg_len, struct sockaddr_in
* p - packet to send
* client - number of the client
*/
static void pass_to_server(struct dhcp_packet *p, int packet_len, unsigned from_iface_no, int *fds,
static void pass_to_server(struct dhcp_packet *p, int packet_len, int client, int *fds,
struct sockaddr_in *client_addr, struct sockaddr_in *server_addr)
{
int type;
/* check packet_type */
type = get_dhcp_packet_type(p);
//FIXME: the above does not consider packet_len!
if (type != DHCPDISCOVER && type != DHCPREQUEST
&& type != DHCPDECLINE && type != DHCPRELEASE
&& type != DHCPINFORM
@@ -212,10 +210,7 @@ static void pass_to_server(struct dhcp_packet *p, int packet_len, unsigned from_
}
/* create new xid entry */
xid_add(p->xid, client_addr, from_iface_no);
//TODO: since we key request/reply pairs on xid values, shouldn't we drop new requests
//with xid accidentally matching a xid of one of requests we currently hold
//waiting for their replies?
xid_add(p->xid, client_addr, client);
/* forward request to server */
/* note that we send from fds[0] which is bound to SERVER_PORT (67).
@@ -234,30 +229,25 @@ static void pass_to_client(struct dhcp_packet *p, int packet_len, int *fds)
int type;
struct xid_item *item;
/* check packet type */
type = get_dhcp_packet_type(p);
//FIXME: the above does not consider packet_len!
if (type != DHCPOFFER && type != DHCPACK && type != DHCPNAK) {
return;
}
/* check xid */
item = xid_find(p->xid);
if (!item) {
return;
}
//NB: RFC 1542 section 4.1 seems to envision the logic that
//relay agents use giaddr (dhcp_msg.gateway_nip in our code)
//to find out on which interface to reply.
//(server is meant to copy giaddr from our request packet to its reply).
//Above, we don't use that logic, instead we use xid as a key.
/* check packet type */
type = get_dhcp_packet_type(p);
if (type != DHCPOFFER && type != DHCPACK && type != DHCPNAK) {
return;
}
//TODO: also do it if (p->flags & htons(BROADCAST_FLAG)) is set!
if (item->ip.sin_addr.s_addr == htonl(INADDR_ANY))
item->ip.sin_addr.s_addr = htonl(INADDR_BROADCAST);
sendto_ip4(fds[item->iface_no], p, packet_len, &item->ip);
/* ^^^ if send error occurred, we can't do much, hence no check */
if (sendto_ip4(fds[item->client], p, packet_len, &item->ip) != 0) {
return; /* send error occurred */
}
/* remove xid entry */
xid_del(p->xid);
@@ -269,7 +259,7 @@ int dhcprelay_main(int argc UNUSED_PARAM, char **argv)
struct sockaddr_in server_addr;
char **iface_list;
int *fds;
unsigned num_sockets, max_socket;
int num_sockets, max_socket;
uint32_t our_nip;
INIT_G();
@@ -303,7 +293,7 @@ int dhcprelay_main(int argc UNUSED_PARAM, char **argv)
// every N minutes?
fd_set rfds;
struct timeval tv;
unsigned i;
int i;
FD_ZERO(&rfds);
for (i = 0; i < num_sockets; i++)
@@ -314,17 +304,15 @@ int dhcprelay_main(int argc UNUSED_PARAM, char **argv)
int packlen;
struct dhcp_packet dhcp_msg;
/* from server */
/* server */
if (FD_ISSET(fds[0], &rfds)) {
packlen = udhcp_recv_kernel_packet(&dhcp_msg, fds[0]);
//NB: we do not check source port here. Should we?
//It should be SERVER_PORT.
if (packlen > 0) {
pass_to_client(&dhcp_msg, packlen, fds);
}
}
/* from clients */
/* clients */
for (i = 1; i < num_sockets; i++) {
struct sockaddr_in client_addr;
socklen_t addr_size;
@@ -337,11 +325,6 @@ int dhcprelay_main(int argc UNUSED_PARAM, char **argv)
(struct sockaddr *)(&client_addr), &addr_size);
if (packlen <= 0)
continue;
//NB: we do not check source port here. Should we?
//It should be CLIENT_PORT for clients.
//It can be SERVER_PORT for relay agents (in which case giaddr must be != 0.0.0.0),
//but is it even supported to chain relay agents like this?
//(we still copy client_addr.port and use it to reply to the port we got request from)
/* Get our IP on corresponding client_iface */
// RFC 1542
+16 -45
View File
@@ -135,8 +135,7 @@
//usage:#define wget_trivial_usage
//usage: IF_FEATURE_WGET_LONG_OPTIONS(
//usage: "[-cqS] [--spider] [-O FILE] [-o LOGFILE] [--header STR]\n"
//usage: " [--post-data STR | --post-file FILE] [-Y on/off]\n"
//usage: "[-cqS] [--spider] [-O FILE] [-o LOGFILE] [--header 'HEADER: VALUE'] [-Y on/off]\n"
/* Since we ignore these opts, we don't show them in --help */
/* //usage: " [--no-cache] [--passive-ftp] [-t TRIES]" */
/* //usage: " [-nv] [-nc] [-nH] [-np]" */
@@ -149,9 +148,6 @@
//usage: "Retrieve files via HTTP or FTP\n"
//usage: IF_FEATURE_WGET_LONG_OPTIONS(
//usage: "\n --spider Only check URL existence: $? is 0 if exists"
//usage: "\n --header STR Add STR (of form 'header: value') to headers"
//usage: "\n --post-data STR Send STR using POST method"
//usage: "\n --post-file FILE Send FILE using POST method"
//usage: IF_FEATURE_WGET_OPENSSL(
//usage: "\n --no-check-certificate Don't validate the server's certificate"
//usage: )
@@ -211,33 +207,29 @@ enum {
HDR_HOST = (1<<0),
HDR_USER_AGENT = (1<<1),
HDR_RANGE = (1<<2),
HDR_CONTENT_TYPE = (1<<3),
HDR_AUTH = (1<<4) * ENABLE_FEATURE_WGET_AUTHENTICATION,
HDR_PROXY_AUTH = (1<<5) * ENABLE_FEATURE_WGET_AUTHENTICATION,
HDR_AUTH = (1<<3) * ENABLE_FEATURE_WGET_AUTHENTICATION,
HDR_PROXY_AUTH = (1<<4) * ENABLE_FEATURE_WGET_AUTHENTICATION,
};
static const char wget_user_headers[] ALIGN1 =
"Host:\0"
"User-Agent:\0"
"Range:\0"
"Content-Type:\0"
# if ENABLE_FEATURE_WGET_AUTHENTICATION
"Authorization:\0"
"Proxy-Authorization:\0"
# endif
;
# define USR_HEADER_HOST (G.user_headers & HDR_HOST)
# define USR_HEADER_USER_AGENT (G.user_headers & HDR_USER_AGENT)
# define USR_HEADER_RANGE (G.user_headers & HDR_RANGE)
# define USR_HEADER_CONTENT_TYPE (G.user_headers & HDR_CONTENT_TYPE)
# define USR_HEADER_AUTH (G.user_headers & HDR_AUTH)
# define USR_HEADER_PROXY_AUTH (G.user_headers & HDR_PROXY_AUTH)
# define USR_HEADER_HOST (G.user_headers & HDR_HOST)
# define USR_HEADER_USER_AGENT (G.user_headers & HDR_USER_AGENT)
# define USR_HEADER_RANGE (G.user_headers & HDR_RANGE)
# define USR_HEADER_AUTH (G.user_headers & HDR_AUTH)
# define USR_HEADER_PROXY_AUTH (G.user_headers & HDR_PROXY_AUTH)
#else /* No long options, no user-headers :( */
# define USR_HEADER_HOST 0
# define USR_HEADER_USER_AGENT 0
# define USR_HEADER_RANGE 0
# define USR_HEADER_CONTENT_TYPE 0
# define USR_HEADER_AUTH 0
# define USR_HEADER_PROXY_AUTH 0
# define USR_HEADER_HOST 0
# define USR_HEADER_USER_AGENT 0
# define USR_HEADER_RANGE 0
# define USR_HEADER_AUTH 0
# define USR_HEADER_PROXY_AUTH 0
#endif
/* Globals */
@@ -252,7 +244,6 @@ struct globals {
char *dir_prefix;
#if ENABLE_FEATURE_WGET_LONG_OPTIONS
char *post_data;
char *post_file;
char *extra_headers;
unsigned char user_headers; /* Headers mentioned by the user */
#endif
@@ -301,13 +292,10 @@ enum {
WGET_OPT_POST_DATA = (1 << 12) * ENABLE_FEATURE_WGET_LONG_OPTIONS,
WGET_OPT_SPIDER = (1 << 13) * ENABLE_FEATURE_WGET_LONG_OPTIONS,
WGET_OPT_NO_CHECK_CERT = (1 << 14) * ENABLE_FEATURE_WGET_LONG_OPTIONS,
WGET_OPT_POST_FILE = (1 << 15) * ENABLE_FEATURE_WGET_LONG_OPTIONS,
/* hijack this bit for other than opts purposes: */
WGET_NO_FTRUNCATE = (1 << 31)
};
#define WGET_OPT_POST (WGET_OPT_POST_DATA | WGET_OPT_POST_FILE)
enum {
PROGRESS_START = -1,
PROGRESS_END = 0,
@@ -1225,7 +1213,7 @@ static void download_one_url(const char *url)
target.path);
} else {
SENDFMT(sfp, "%s /%s HTTP/1.1\r\n",
(option_mask32 & WGET_OPT_POST) ? "POST" : "GET",
(option_mask32 & WGET_OPT_POST_DATA) ? "POST" : "GET",
target.path);
}
if (!USR_HEADER_HOST)
@@ -1258,20 +1246,9 @@ static void download_one_url(const char *url)
fputs(G.extra_headers, sfp);
}
if (option_mask32 & WGET_OPT_POST_FILE) {
int fd = xopen_stdin(G.post_file);
G.post_data = xmalloc_read(fd, NULL);
close(fd);
}
if (G.post_data) {
/* If user did not override it... */
if (!USR_HEADER_CONTENT_TYPE) {
SENDFMT(sfp,
"Content-Type: application/x-www-form-urlencoded\r\n"
);
}
if (option_mask32 & WGET_OPT_POST_DATA) {
SENDFMT(sfp,
"Content-Type: application/x-www-form-urlencoded\r\n"
"Content-Length: %u\r\n"
"\r\n"
"%s",
@@ -1512,7 +1489,6 @@ IF_DESKTOP( "tries\0" Required_argument "t")
"post-data\0" Required_argument "\xfe"
"spider\0" No_argument "\xfd"
"no-check-certificate\0" No_argument "\xfc"
"post-file\0" Required_argument "\xfb"
/* Ignored (we always use PASV): */
IF_DESKTOP( "passive-ftp\0" No_argument "\xf0")
/* Ignored (we don't support caching) */
@@ -1556,9 +1532,6 @@ IF_DESKTOP( "no-parent\0" No_argument "\xf0")
*/
"\0"
"-1" /* at least one URL */
IF_FEATURE_WGET_LONG_OPTIONS(":\xfe--\xfb")
IF_FEATURE_WGET_LONG_OPTIONS(":\xfe--\xfe")
IF_FEATURE_WGET_LONG_OPTIONS(":\xfb--\xfb")
IF_FEATURE_WGET_LONG_OPTIONS(":\xff::") /* --header is a list */
LONGOPTS
, &G.fname_out, &G.fname_log, &G.dir_prefix,
@@ -1568,7 +1541,6 @@ IF_DESKTOP( "no-parent\0" No_argument "\xf0")
NULL /* -n[ARG] */
IF_FEATURE_WGET_LONG_OPTIONS(, &headers_llist)
IF_FEATURE_WGET_LONG_OPTIONS(, &G.post_data)
IF_FEATURE_WGET_LONG_OPTIONS(, &G.post_file)
);
#if 0 /* option bits debug */
if (option_mask32 & WGET_OPT_RETRIES) bb_error_msg("-t NUM");
@@ -1577,7 +1549,6 @@ IF_DESKTOP( "no-parent\0" No_argument "\xf0")
if (option_mask32 & WGET_OPT_POST_DATA) bb_error_msg("--post-data");
if (option_mask32 & WGET_OPT_SPIDER) bb_error_msg("--spider");
if (option_mask32 & WGET_OPT_NO_CHECK_CERT) bb_error_msg("--no-check-certificate");
if (option_mask32 & WGET_OPT_POST_FILE) bb_error_msg("--post-file");
exit(0);
#endif
argv += optind;
+1 -8
View File
@@ -5,12 +5,7 @@
menu "Process Utilities"
config FEATURE_FAST_TOP
bool "Faster /proc scanning code (+100 bytes)"
default n # all "fast or small" options default to small
help
This option makes top and ps ~20% faster (or 20% less CPU hungry),
but code size is slightly bigger.
INSERT
config FEATURE_SHOW_THREADS
bool "Support thread display in ps/pstree/top"
@@ -20,6 +15,4 @@ config FEATURE_SHOW_THREADS
Enables the ps -T option, showing of threads in pstree,
and 'h' command in top.
INSERT
endmenu
+1 -1
View File
@@ -505,7 +505,7 @@ static void cpuid(unsigned int *eax, unsigned int *ebx, unsigned int *ecx,
unsigned int *edx)
{
/* EAX value specifies what information to return */
asm (
__asm__(
" pushl %%ebx\n" /* Save EBX */
" cpuid\n"
" movl %%ebx, %1\n" /* Save content of EBX */
+14 -18
View File
@@ -443,19 +443,17 @@ static void parse_o(char* opt)
opt = comma + 1;
continue;
}
// opt points to last spec in comma separated list.
// This one can have =HEADER part.
new = new_out_t();
if (equal)
*equal = '\0';
*new = *find_out_spec(opt);
if (!equal)
break;
*equal++ = '=';
new->header = equal;
comma = strchr(equal, ',');
if (comma)
*comma = '\0';
break;
}
// opt points to last spec in comma separated list.
// This one can have =HEADER part.
new = new_out_t();
if (equal)
*equal = '\0';
*new = *find_out_spec(opt);
if (equal) {
*equal = '=';
new->header = equal + 1;
// POSIX: the field widths shall be ... at least as wide as
// the header text (default or overridden value).
// If the header text is null, such as -o user=,
@@ -463,12 +461,10 @@ static void parse_o(char* opt)
// default header text
if (new->header[0]) {
new->width = strlen(new->header);
print_header = 1;
}
if (!comma)
break;
//*comma = ','; /* no, new->header should stay NUL-terminated */
opt = comma + 1;
}
} else
print_header = 1;
}
static void alloc_line_buffer(void)
+15 -1
View File
@@ -29,6 +29,7 @@ struct fileblock {
static void writeheader(const char *path, struct stat *sb, int type)
{
struct tar_header_t header;
int i, sum;
memset(&header, 0, TAR_BLOCK_SIZE);
strcpy(header.name, path);
@@ -39,7 +40,20 @@ static void writeheader(const char *path, struct stat *sb, int type)
sprintf(header.size, "%o", (unsigned)sb->st_size);
sprintf(header.mtime, "%llo", sb->st_mtime & 077777777777LL);
header.typeflag = type;
chksum_and_xwrite_tar_header(STDOUT_FILENO, &header);
strcpy(header.magic, "ustar "); /* like GNU tar */
/* 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... */
header.chksum[7] = ' ';
sum = ' ' * 7;
for (i = 0; i < TAR_BLOCK_SIZE; i++)
sum += ((unsigned char*)&header)[i];
sprintf(header.chksum, "%06o", sum);
xwrite(STDOUT_FILENO, &header, TAR_BLOCK_SIZE);
}
static void archivefile(const char *path)
+262 -291
View File
File diff suppressed because it is too large. Load diff
@@ -1 +0,0 @@
Ok
@@ -1,16 +0,0 @@
# Note: bash would need:
#shopt -s expand_aliases
# to enable aliases in non-interactive mode
alias BEGIN={ END=}
BEGIN
cat <<- EOF > /dev/null
$(:)
EOF
END
: <<- EOF &&
$(:)
EOF
BEGIN
echo Ok
END
@@ -1 +0,0 @@
Ok
@@ -1,8 +0,0 @@
# Note: bash would need:
#shopt -s expand_aliases
# to enable aliases in non-interactive mode
alias a="case x in " b=x
a
b) echo BAD;;
*) echo Ok;;
esac
@@ -2,7 +2,4 @@
1 1
1 1
1 1
6 6
7 7
7 7
Ok:0
@@ -2,8 +2,4 @@ echo 1 $((0++1))
echo 1 $((0--1))
x=-1; echo 1 $((0-$x))
x=+1; echo 1 $((0+$x))
a=3
echo 6 $((a+++3)) # a++ + 3
echo 7 $(((a)+++3)) # a + + + 3
echo 7 $(((a)+++3)) # a + + + 3
echo Ok:$?
+24 -54
View File
@@ -43,60 +43,40 @@ Format: 'expected actual'
4 4
29 29
5 5
unary plus, minus
-4 -4
4 4
conditional expressions
1 1
32 32
32 32
1 1
1 1
32 32
check that the unevaluated part of the ternary operator does not do evaluation or assignment
20 20
30 30
20 20
30 30
check precedence of assignment vs. conditional operator
./arith.tests: line 116: arithmetic syntax error
check precedence of assignment vs. conditional operator
associativity of assignment-operator operator
./arith.tests: line 117: arithmetic syntax error
6 6
6,5,3 6,5,3
octal, hex
263 263
255 255
40 40
other bases
10 10
10 10
10 10
10 10
10 10
10 10
36 36
36 36
62 62
63 63
missing number after base
0 0
./arith.tests: line 162: arithmetic syntax error
./arith.tests: line 164: divide by zero
./arith.tests: let: line 165: arithmetic syntax error
./arith.tests: line 166: arithmetic syntax error
./arith.tests: let: line 167: arithmetic syntax error
./arith.tests: line 163: arithmetic syntax error
./arith.tests: line 165: divide by zero
./arith.tests: let: line 166: arithmetic syntax error
./arith.tests: line 167: arithmetic syntax error
./arith.tests: let: line 168: arithmetic syntax error
abc
def
ghi
./arith.tests: line 190: arithmetic syntax error
./arith.tests: line 191: arithmetic syntax error
16 16
./arith.tests: line 195: arithmetic syntax error
./arith.tests: line 196: malformed ?: operator
./arith.tests: line 197: arithmetic syntax error
./arith.tests: line 196: arithmetic syntax error
./arith.tests: line 197: malformed ?: operator
./arith.tests: line 198: arithmetic syntax error
9 9
./arith.tests: line 204: arithmetic syntax error
./arith.tests: line 207: arithmetic syntax error
./arith.tests: line 205: arithmetic syntax error
./arith.tests: line 208: arithmetic syntax error
9 9
9 9
9 9
@@ -117,17 +97,14 @@ ghi
3 3
4 4
4 4
7 7
./arith.tests: line 256: arithmetic syntax error
./arith.tests: line 258: arithmetic syntax error
./arith.tests: line 257: arithmetic syntax error
./arith.tests: line 259: arithmetic syntax error
./arith.tests: line 261: arithmetic syntax error
./arith.tests: line 260: arithmetic syntax error
./arith.tests: line 262: arithmetic syntax error
./arith.tests: line 263: arithmetic syntax error
4 4
7 7
-7 -7
7
7
./arith1.sub: line 2: arithmetic syntax error
./arith1.sub: line 3: arithmetic syntax error
./arith1.sub: line 4: arithmetic syntax error
@@ -142,12 +119,11 @@ ghi
2 2
-2 -2
1 1
7
7
7
7
7
7
./arith1.sub: line 37: arithmetic syntax error
./arith2.sub: line 2: arithmetic syntax error
./arith2.sub: line 3: arithmetic syntax error
./arith2.sub: line 4: arithmetic syntax error
./arith2.sub: line 5: arithmetic syntax error
5 5
1 1
6 6
@@ -156,17 +132,11 @@ ghi
1 1
4 4
0 0
-7
-7
7
7
-7 -7
-7 -7
7 7
7 7
./arith2.sub: line 42: arithmetic syntax error
./arith2.sub: line 47: arithmetic syntax error
8 12
./arith.tests: line 289: arithmetic syntax error
./arith.tests: line 290: arithmetic syntax error
42
42
42
./arith.tests: line 301: a[b[c]d]=e: not found
./arith.tests: line 302: a[b[c]d]=e: not found
+28 -27
View File
@@ -75,11 +75,11 @@ echo 4 $(( iv &= 4 ))
echo 29 $(( iv += (jv + 9)))
echo 5 $(( (iv + 4) % 7 ))
echo unary plus, minus
# unary plus, minus
echo -4 $(( +4 - 8 ))
echo 4 $(( -4 + 8 ))
echo conditional expressions
# conditional expressions
echo 1 $(( 4<5 ? 1 : 32))
echo 32 $(( 4>5 ? 1 : 32))
echo 32 $(( 4>(2+3) ? 1 : 32))
@@ -87,7 +87,8 @@ echo 1 $(( 4<(2+3) ? 1 : 32))
echo 1 $(( (2+2)<(2+3) ? 1 : 32))
echo 32 $(( (2+2)>(2+3) ? 1 : 32))
echo check that the unevaluated part of the ternary operator does not do evaluation or assignment
# check that the unevaluated part of the ternary operator does not do
# evaluation or assignment
x=i+=2
y=j+=2
#ash# declare -i i=1 j=1
@@ -108,20 +109,20 @@ echo 20 $((1 ? 20 : (x+=2)))
echo 30 $((0 ? (y+=2) : 30))
#ash# echo $i,$y # ash mishandles this
echo check precedence of assignment vs. conditional operator
# check precedence of assignment vs. conditional operator
# should be an error
#ash# declare -i x=2
x=2
#ashnote# bash reports error but continues, ash aborts - using subshell to 'emulate' bash:
( y=$((1 ? 20 : x+=2)) )
echo check precedence of assignment vs. conditional operator
# check precedence of assignment vs. conditional operator
#ash# declare -i x=2
x=2
# ash says "line NNN: syntax error: 0 ? x+=2 : 20"
#ash# echo 20 $((0 ? x+=2 : 20))
echo associativity of assignment-operator operator
# associativity of assignment-operator operator
#ash# declare -i i=1 j=2 k=3
i=1
j=2
@@ -129,7 +130,7 @@ k=3
echo 6 $((i += j += k))
echo 6,5,3 $i,$j,$k
echo octal, hex
# octal, hex
echo 263 $(( 0x100 | 007 ))
echo 255 $(( 0xff ))
#ash# echo 255 $(( 16#ff ))
@@ -138,25 +139,25 @@ echo 255 $(( 0xff ))
echo 40 $(( 8 ^ 32 ))
echo other bases
echo 10 $(( 16#a ))
echo 10 $(( 32#a ))
echo 10 $(( 56#a ))
echo 10 $(( 64#a ))
echo 10 $(( 16#A ))
echo 10 $(( 32#A ))
echo 36 $(( 56#A ))
echo 36 $(( 64#A ))
echo 62 $(( 64#@ ))
echo 63 $(( 64#_ ))
#ash# # other bases
#ash# echo 10 $(( 16#a ))
#ash# echo 10 $(( 32#a ))
#ash# echo 10 $(( 56#a ))
#ash# echo 10 $(( 64#a ))
#ash#
#ash# echo 10 $(( 16#A ))
#ash# echo 10 $(( 32#A ))
#ash# echo 36 $(( 56#A ))
#ash# echo 36 $(( 64#A ))
#ash#
#ash# echo 62 $(( 64#@ ))
#ash# echo 63 $(( 64#_ ))
#ash# # weird bases (error)
#ash# echo $(( 3425#56 ))
echo missing number after base
echo 0 $(( 2# ))
#ash# # missing number after base
#ash# echo 0 $(( 2# ))
# these should generate errors
( echo $(( 7 = 43 )) )
@@ -251,8 +252,8 @@ echo 3 $x
echo 4 $(( ++x ))
echo 4 $x
# ++ is not a inc operator on non-variable, it is the + + sequence
echo 7 $(( ++7 ))
# bash 3.2 apparently thinks that ++7 is 7
#ash# echo 7 $(( ++7 ))
( echo $(( 7-- )) )
( echo $(( --x=7 )) )
@@ -266,9 +267,9 @@ echo 4 $x
echo 7 $(( +7 ))
echo -7 $(( -7 ))
# ++ is not a inc operator on non-variable, it is the + + sequence
echo $(( ++7 ))
echo $(( --7 ))
# bash 3.2 apparently thinks that ++7 is 7
#ash# echo $(( ++7 ))
#ash# echo $(( --7 ))
${THIS_SH} ./arith1.sub
${THIS_SH} ./arith2.sub
+2 -2
View File
@@ -35,6 +35,6 @@ echo 1 $a
#ash# (( ++ ))
( echo $(( +++7 )) )
# ++ is not a inc operator on non-variable, it is the + + sequence
echo $(( ++ + 7 ))
# bash 3.2 apparently thinks that ++ +7 is 7
#ash# echo $(( ++ + 7 ))
#ash# (( -- ))
+13 -9
View File
@@ -1,4 +1,4 @@
# ++ and -- are not inc/dec operators on non-variables, they are + + and - - sequences
# bash 3.2 apparently thinks that ++7 is 7 etc
( echo $(( --7 )) )
( echo $(( ++7 )) )
( echo $(( -- 7 )) )
@@ -37,17 +37,21 @@ echo 4 $(( 4 - -- a ))
echo 0 $a
#ash# (( -- ))
# -- is not a dec operator on non-variable, it is the - - sequence
echo $(( ---7 ))
# bash 3.2 apparently thinks that ---7 is -7
#ash# echo $(( ---7 ))
( echo $(( -- - 7 )) )
#ash# (( ++ ))
# ++ is not a inc operator on non-variable, it is the + + sequence
echo $(( ++7 ))
# bash 3.2: 7
#ash# echo 7 $(( ++7 ))
( echo $(( ++ + 7 )) )
echo -7 $(( ++-7 ))
echo -7 $(( ++ - 7 ))
# bash 3.2: -7
#ash# echo -7 $(( ++-7 ))
# bash 3.2: -7
#ash# echo -7 $(( ++ - 7 ))
echo 7 $(( +--7 ))
echo 7 $(( -- + 7 ))
# bash 3.2: 7
#ash# echo 7 $(( +--7 ))
# bash 3.2: 7
#ash# echo 7 $(( -- + 7 ))
-6
View File
@@ -1,6 +0,0 @@
./SCRIPT.sh:
/proc/N/comm: SCRIPT.sh
exec ./SCRIPT.sh:
/proc/N/comm: SCRIPT.sh
sh ./SCRIPT.sh:
/proc/N/comm: ash
Loaded 100 of 157 files, more files were not shown because too many files have changed in this diff. Show more