Compare commits

...
177 Commits
Author SHA1 Message Date
Denys Vlasenko e512aeb0fb Bump version to 1.35.0
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-12-26 17:55:58 +01:00
Denys Vlasenko 97c00ae134 httpd: fix compile failure if !FEATURE_HTTPD_RANGES
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-12-26 14:29:37 +01:00
Dominique Martinet 4fe954c148 sed: do not ignore 'g' modifier when match starts with ^
It is perfectly valid to start a regex with ^ and have other patterns
with \| that can match more than once, e.g. the following example
should print ca, as illustrated with gnu sed:
$ echo 'abca' | sed -e 's/^a\|b//g'
ca

busybox before patch:
$ echo 'abca' | busybox sed -e 's/^a\|b//g'
bca

busybox after patch:
$ echo 'abca' | ./busybox sed -e 's/^a\|b//g'
ca

regcomp handles ^ perfectly well as illustrated with the second 'a' that
did not match in the example, we ca leave the non-repeating to it if
appropriate.
The check had been added before using regcomp and was required at the
time (f36635cec6) but no longer makes sense now.

(tested with glibc and musl libc)

function                                             old     new   delta
add_cmd                                             1189    1176     -13

Signed-off-by: Dominique Martinet <asmadeus@codewreck.org>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-12-25 04:20:28 +01:00
Sören Tempel a05a3d5932 ed: align output of read command with POSIX.1-2008
POSIX.1-2008 mandates the following regarding the read command:

	If the read is successful, and -s was not specified, the number
	of bytes read shall be written to standard output in the
	following format:

	    "%d\n", <number of bytes read>

This commit aligns the output of busybox ed with POSIX.1-2008 by
removing the file name from the output for the read command.

This slipped through in 4836a0708fd0aaeb82871a3762b40fcf4b61e812.

function                                             old     new   delta
.rodata                                           104203  104196      -7
readLines                                            409     388     -21
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 0/2 up/down: 0/-28)             Total: -28 bytes

Signed-off-by: Sören Tempel <soeren+git@soeren-tempel.net>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-12-19 23:17:52 +01:00
Sören Tempel f26eb796e2 ed: fix current line number for file passed via the command-line
POSIX.1-2008 mandates the following regarding the file command-line
argument:

	If the file argument is given, ed shall simulate an e command
	on the file named by the pathname […]

The specification for the e command mandates the following behaviour
regarding the current line number in POSIX.1-2008:

	The current line number shall be set to the address of the last
	line of the buffer.

However, without this commit, busybox ed will set the current line
number to 1 if a file is given on the command-line and this file is not
empty (lastNum != 0). This is incorrect and fixed in this commit by not
modifying the current line number in ed_main(). As such, the current
line number will be zero for empty files and otherwise be set to the
address of the last line of the buffer.

function                                             old     new   delta
ed_main                                              144     128     -16

Signed-off-by: Sören Tempel <soeren+git@soeren-tempel.net>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-12-19 23:16:02 +01:00
Matthew Slowe 7d49fedc86 timeout: add support for "timeout -k KILL_SECS"
function                                             old     new   delta
timeout_main                                         307     373     +66
timeout_wait                                           -      42     +42
.rodata                                           104201  104203      +2
packed_usage                                       34097   34096      -1
------------------------------------------------------------------------------
(add/remove: 1/0 grow/shrink: 2/1 up/down: 110/-1)            Total: 109 bytes

Signed-off-by: Matthew Slowe <foo@mafoo.org.uk>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-12-17 23:11:17 +01:00
Denys Vlasenko c1eac153e8 cmp: code shrink
function                                             old     new   delta
.rodata                                           104203  104201      -2

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-12-17 22:43:45 +01:00
Sören Tempel bfd8738154 ed: add support for -p command-line option as mandated by POSIX
The POSIX.1-2008 specification of ed(1) mandates two command-line
options: -p (for specifying a prompt string) and -s (to suppress writing
of byte counts). This commit adds support for the former. Furthermore,
it also changes the default prompt string to an empty string (instead
of ": ") since this is also mandated by POSIX:

	-p string Use string as the prompt string when in command mode.
	          By default, there shall be no prompt string.

function                                             old     new   delta
ed_main                                              112     144     +32
packed_usage                                       34074   34097     +23
doCommands                                          1889    1887      -2
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 2/1 up/down: 55/-2)              Total: 53 bytes

Signed-off-by: Sören Tempel <soeren+git@soeren-tempel.net>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-12-17 22:35:25 +01:00
Walter Lozano 579894bfd2 cmp: add support for -n
Add support to for "-n" to cmp in order to compare at most n bytes.

function                                             old     new   delta
cmp_main                                             552     589     +37
.rodata                                           104198  104203      +5
packed_usage                                       34102   34074     -28
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 2/1 up/down: 42/-28)             Total: 14 bytes

Signed-off-by: Walter Lozano <walter.lozano@collabora.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-12-17 22:07:06 +01:00
Denys Vlasenko 00d10cb6eb docs/embedded-scripts.txt: whitespace fix
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-12-17 21:38:02 +01:00
Aaro Koskinen aaade69ce9 find: implement -samefile
function                                             old     new   delta
parse_params                                        1461    1606    +145
func_samefile                                          -      42     +42
packed_usage                                       34079   34102     +23
static.params                                        261     271     +10
------------------------------------------------------------------------------
(add/remove: 1/0 grow/shrink: 3/0 up/down: 220/0)             Total: 220 bytes

Signed-off-by: Aaro Koskinen <aaro.koskinen@iki.fi>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-12-17 21:33:15 +01:00
Ron Yorston 7105e4afdd printf: allow 0 as a flag and allow multiple flags
The '%' character in a format specification may be followed by
one or more flags from the list "+- #0".  BusyBox printf didn't
support the '0' flag or allow multiple flags to be provided.
As a result the formats '%0*d' and '%0 d' were considered to be
invalid.

The lack of support for '0' was pointed out by Andrew Snyder on the
musl mailing list:

   https://www.openwall.com/lists/musl/2021/12/14/2

function                                             old     new   delta
printf_main                                          860     891     +31
.rodata                                            99281   99282      +1
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 2/0 up/down: 32/0)               Total: 32 bytes

Signed-off-by: Ron Yorston <rmy@pobox.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-12-17 21:13:26 +01:00
Denys Vlasenko b720629dfe httpd: do not send Last-Modified / ETag / Content-Length for error pages
function                                             old     new   delta
send_headers                                         713     701     -12
send_headers_and_exit                                 20      34     +14

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-12-17 21:02:16 +01:00
Denys Vlasenko 70683faf38 httpd: don't send Content-Length in error pages header
function                                             old     new   delta
send_headers                                         701     713     +12

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-12-17 20:37:58 +01:00
Peter Korsgaard cb91a818c8 libarchive/get_header_ar.c: fix extraction of archives from binutils in deterministic mode
GNU binutils in deterministic mode (ar rD or built with
--enable-deterministic-archives) hard codes file mode to 0644 (NOT 0100644)
since https://github.com/bminor/binutils-gdb/commit/36e4dce69dd2

This confuses busybox ar x (data_extract_all):

touch a; ar rD a.ar a
ar: creating a.ar

busybox ar x a.ar
ar: unrecognized file type
hexdump -C a.ar
00000000  21 3c 61 72 63 68 3e 0a  61 2f 20 20 20 20 20 20  |!<arch>.a/      |
00000010  20 20 20 20 20 20 20 20  30 20 20 20 20 20 20 20  |        0       |
00000020  20 20 20 20 30 20 20 20  20 20 30 20 20 20 20 20  |    0     0     |
00000030  36 34 34 20 20 20 20 20  30 20 20 20 20 20 20 20  |644     0       |
00000040  20 20 60 0a                                       |  `.|

As a workaround, force the mode bits to S_IFREG, as nothing else makes sense
for ar.

function                                             old     new   delta
get_header_ar                                        539     542      +3

Signed-off-by: Peter Korsgaard <peter@korsgaard.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-12-12 23:34:43 +01:00
Denys Vlasenko e67b80f473 udhcpc6: fix udhcp_find_option to actually find DHCP6 options
udhcp_insert_new_option treats code for IPv6 as follows:

new->data[D6_OPT_CODE] = code >> 8;
new->data[D6_OPT_CODE + 1] = code & 0xff;

udhcp_find_option tests the code as follows:

while (opt_list && opt_list->data[OPT_CODE] < code)
...
if (opt_list && opt_list->data[OPT_CODE] == code)

So yes, OPT_CODE and D6_OPT_CODE are both 0, but the D6_OPT_CLIENTID =
1 value means that the 1 is in the seconds byte, and udhcp_find_option
is only looking at the first byte,  So the send_d6_release can never
find it the created option.

function                                             old     new   delta
udhcp_find_option                                     28      53     +25
attach_option                                        276     284      +8
udhcpc6_main                                        2602    2607      +5
perform_d6_release                                   262     267      +5
udhcpd_main                                         1518    1520      +2
udhcpc_main                                         2542    2544      +2
add_serverid_and_clientid_options                     46      48      +2
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 7/0 up/down: 49/0)               Total: 49 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-12-12 17:13:54 +01:00
Martin Kaiser 9b67880719 Makefile.flags: use all cflags for crypt and rt checks
To check if libcrypt and librt are available, we check if we can
compile and link a simple test program.

These checks do not match the actual linking if CONFIG_STATIC is enabled.
For CONFIG_STATIC, CFLAGS_busybox is set to -static. The checks don't use
CFLAGS_busybox and detect a shared libcrypt or librt. If we link busybox
later and we have no static libcrypt or librt, linking will fail.

Update the libcrypt and librt checks to use CFLAGS_busybox.

Signed-off-by: Martin Kaiser <martin@kaiser.cx>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-12-12 13:16:40 +01:00
Ildar Shaimordanov b9fba185c5 wget: allow end-users to customize Content-Type for --post-data and --post-file
More explanation in this PR:
https://github.com/rmyorston/busybox-w32/pull/233

The real use-case:
wget https://api.github.com/markdown/raw --header "Content-Type: text/plain"

function                                             old     new   delta
wget_main                                           2560    2581     +21
wget_user_headers                                     62      76     +14
.rodata                                           104196  104197      +1
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 3/0 up/down: 36/0)               Total: 36 bytes

Signed-off-by: Ildar Shaimordanov <ildar.shaimordanov@gmail.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-12-12 03:22:43 +01:00
Denys Vlasenko c7b90dc4d1 uudecode: special-case "/dev/stdout", closes 14241
function                                             old     new   delta
uudecode_main                                        295     322     +27

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-12-12 00:34:15 +01:00
Denys Vlasenko 27df6aeef2 tls: P256: factor out "multiply then reduce" operation
function                                             old     new   delta
sp_256_mont_mul_and_reduce_8                           -      44     +44
sp_256_ecc_mulmod_8                                  517     442     -75
------------------------------------------------------------------------------
(add/remove: 1/0 grow/shrink: 0/1 up/down: 44/-75)            Total: -31 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-12-11 23:27:40 +01:00
Denys Vlasenko b240733ae7 tls: x25519: code shrink by factoring out common code
function                                             old     new   delta
fe_reduce                                              -      37     +37
lm_add                                                67      43     -24
fe_mul_c                                              62      38     -24
fe_mul__distinct                                     138     112     -26
curve25519                                           800     767     -33
lm_sub                                                98      64     -34
------------------------------------------------------------------------------
(add/remove: 1/0 grow/shrink: 0/5 up/down: 37/-141)          Total: -104 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-12-01 15:09:44 +01:00
Denys Vlasenko 8514b4166d tls: P256: enable 64-bit version of montgomery reduction
After more testing, (1) I'm more sure it is indeed correct, and
(2) it is a significant speedup - we do a lot of those multiplications.

function                                             old     new   delta
sp_512to256_mont_reduce_8                            191     223     +32

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-11-28 21:43:51 +01:00
Denys Vlasenko 90b0d33044 tls: P256: add 64-bit montgomery reduce (disabled), small optimization in 32-bit code
function                                             old     new   delta
sp_512to256_mont_reduce_8                            191     185      -6

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-11-28 15:44:08 +01:00
Denys Vlasenko 832626227e tls: P256: add comment on logic in sp_512to256_mont_reduce_8, no code changes
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-11-28 12:55:20 +01:00
Denys Vlasenko 00b5051cd2 libbb: code shrink in des encryption, in setup_salt()
function                                             old     new   delta
pw_encrypt                                           978     971      -7
.rodata                                           108208  108192     -16
des_crypt                                           1211    1181     -30
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 0/3 up/down: 0/-53)             Total: -53 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-11-28 12:21:23 +01:00
Denys Vlasenko cfb615781d tls: P256: simplify sp_256_mont_inv_8 (no need for a temporary)
function                                             old     new   delta
sp_256_ecc_mulmod_8                                  543     517     -26

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-11-28 11:15:34 +01:00
Bernhard Reutner-Fischer bfefa6ab6c libarchive: remove duplicate forward declaration
Signed-off-by: Bernhard Reutner-Fischer <rep.dot.nop@gmail.com>
2021-11-28 10:53:22 +01:00
Denys Vlasenko 1b93c7c4ec tls: P256: pad struct sp_point to 64 bits (on 64-bit arches)
function                                             old     new   delta
curve_P256_compute_pubkey_and_premaster              198     190      -8

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-11-28 02:56:02 +01:00
Denys Vlasenko 0b13ab66f4 tls: P256: trivial x86-64 fix
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-11-27 19:36:23 +01:00
Denys Vlasenko f92ae1dc4b tls: P256: change logic so that we don't need double-wide vectors everywhere
Change sp_256to512z_mont_{mul,sqr}_8 to not require/zero upper 256 bits.
There is only one place where we actually used that (and that's why there
used to be zeroing memset of top half!). Fix up that place.
As a bonus, 256x256->512 multiply no longer needs to care for
"r overlaps a or b" case.

This shrinks sp_point structure as well, not just temporaries.

function                                             old     new   delta
sp_256to512z_mont_mul_8                              150       -    -150
sp_256_mont_mul_8                                      -     147    +147
sp_256to512z_mont_sqr_8                                7       -      -7
sp_256_mont_sqr_8                                      -       7      +7
sp_256_ecc_mulmod_8                                  494     543     +49
sp_512to256_mont_reduce_8                            243     249      +6
sp_256_point_from_bin2x32                             73      70      -3
sp_256_proj_point_dbl_8                              353     345      -8
sp_256_proj_point_add_8                              544     499     -45
------------------------------------------------------------------------------
(add/remove: 2/2 grow/shrink: 2/3 up/down: 209/-213)           Total: -4 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-11-27 19:27:03 +01:00
Denys Vlasenko 9c671fe3dd tls: P256: do not open-code copying of struct variables
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-11-27 18:42:27 +01:00
Denys Vlasenko dcfd8d3d10 tls: P256: fix sp_256_div2_8 - it wouldn't use a[] if low bit is 0
It worked by chance because the only caller passed both parameters
as two pointers to the same array.
My fault (I made this error when converting from 26-bit code).

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-11-27 16:24:49 +01:00
Denys Vlasenko 8cbb70365f tls: P256: remove redundant zeroing in sp_256_map_8
Previous change made it obvious that we zero out already-zeroed high bits

function                                             old     new   delta
sp_256_ecc_mulmod_8                                  534     494     -40

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-11-27 15:50:40 +01:00
Denys Vlasenko 4415f7bc06 tls: P256: explain which functions use double-wide arrays, no code changes
function                                             old     new   delta
sp_512to256_mont_reduce_8                              -     243    +243
sp_256to512z_mont_mul_8                                -     150    +150
sp_256to512z_mont_sqr_8                                -       7      +7
sp_256_mont_sqr_8                                      7       -      -7
sp_256_mont_mul_8                                    150       -    -150
sp_256_mont_reduce_8                                 243       -    -243
------------------------------------------------------------------------------
(add/remove: 3/3 grow/shrink: 0/0 up/down: 400/-400)            Total: 0 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-11-27 15:47:26 +01:00
Denys Vlasenko bbda85c74b tls: P256: remove constant-time trick in sp_256_proj_point_add_8
function                                             old     new   delta
sp_256_proj_point_add_8                              576     544     -32

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-11-27 15:06:57 +01:00
Denys Vlasenko 26c8522522 tls: P256: do not open-code copying of struct variables
function                                             old     new   delta
sp_256_ecc_mulmod_8                                  536     534      -2

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-11-27 15:00:14 +01:00
Denys Vlasenko 446d136109 tls: tweak debug printout
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-11-27 12:03:43 +01:00
Denys Vlasenko 4bc9da1071 tls: P256: 64-bit optimizations
function                                             old     new   delta
sp_256_proj_point_dbl_8                              421     428      +7
sp_256_point_from_bin2x32                             78      84      +6
sp_256_cmp_8                                          38      42      +4
sp_256_to_bin_8                                       28      31      +3
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 4/0 up/down: 20/0)               Total: 20 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-11-27 11:28:11 +01:00
Denys Vlasenko 15f7d618ea which: add -a to help text
function                                             old     new   delta
packed_usage                                       34075   34079      +4

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-11-09 13:51:22 +01:00
Ariadne Conill 836b79211d cpio: add support for --renumber-inodes like GNU cpio
The --renumber-inodes option renumbers the inodes starting from 1,
so that the sequence of inodes is always stable.  This helps with
reproducibility.

function                                             old     new   delta
cpio_o                                               961    1045     +84
.rodata                                            78422   78440     +18
bbconfig_config_bz2                                 6168    6164      -4
packed_usage                                       25764   25756      -8
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 2/2 up/down: 102/-12)            Total: 90 bytes

Signed-off-by: Ariadne Conill <ariadne@dereferenced.org>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-10-13 17:56:17 +02:00
Ariadne Conill 8aa5585ff4 cpio: add support for --ignore-devno like GNU cpio
The --ignore-devno option is used to set device numbers to (0, 0).
This can be useful in verifying whether a CPIO archive is reproducible.

function                                             old     new   delta
cpio_o                                               922     961     +39
.rodata                                            78407   78422     +15
bbconfig_config_bz2                                 6161    6167      +6
packed_usage                                       25770   25764      -6
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 3/1 up/down: 60/-6)              Total: 54 bytes

Signed-off-by: Ariadne Conill <ariadne@dereferenced.org>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-10-13 17:53:15 +02:00
Denys Vlasenko aaf3d5ba74 shell: tweak --help
Even though formally it is -s [ARGS], "sh -s" without ARGS
is the same as just "sh". And we are already over 80 chars wide
for ash --help, so make it shorter.

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-10-13 11:25:42 +02:00
Denys Vlasenko 62f1eed1e1 hush: in a comment, document what -i might be doing
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-10-13 00:09:07 +02:00
Sören Tempel c33bbcb92f ed: align output of read/write commands with POSIX-1.2008
POSIX.1-2008 mandates the following regarding the write command:

	If the command is successful, 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>

function                                             old     new   delta
readLines                                            447     409     -38
doCommands                                          1940    1889     -51
.rodata                                           104219  104163     -56
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 0/3 up/down: 0/-145)           Total: -145 bytes

Signed-off-by: Sören Tempel <soeren+git@soeren-tempel.net>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-10-12 17:32:03 +02:00
Denys Vlasenko 94c78aa0b9 config system: move some options closer to relevalnt tool subdirectories
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-10-12 13:23:29 +02:00
Denys Vlasenko 7c3e96d4b3 shell: use more compact SHELL_ASH / HUSH config defines. no code changes
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-10-12 01:24:32 +02:00
Denys Vlasenko f4fcd74a6e shell: do not read user database for every prompt - only for those which need it
function                                             old     new   delta
get_user_strings                                       -      52     +52
get_homedir_or_NULL                                    -      23     +23
parse_and_put_prompt                                 823     838     +15
null_str                                               1       -      -1
complete_cmd_dir_file                                814     812      -2
deinit_S                                              51      42      -9
read_line_input                                     3059    3015     -44
------------------------------------------------------------------------------
(add/remove: 2/1 grow/shrink: 1/3 up/down: 90/-56)             Total: 34 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-10-11 23:08:31 +02:00
Denys Vlasenko 6ba1f2d0bc tar: prevent malicious archives with enormous long name sizes OOMing the machine
function                                             old     new   delta
get_header_tar                                      1707    1752     +45

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-10-11 19:28:39 +02:00
Denys Vlasenko aec8fbfb83 whitespace fix
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-10-11 19:11:06 +02:00
Denys Vlasenko 5acf5e1f87 shell: fix script's comm field if ENABLE_FEATURE_PREFER_APPLETS=y
function                                             old     new   delta
re_execed_comm                                         -      46     +46
main                                                  72      86     +14
------------------------------------------------------------------------------
(add/remove: 1/0 grow/shrink: 1/0 up/down: 60/0)               Total: 60 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-10-11 18:44:00 +02:00
Denys Vlasenko 23aba8a9a6 tls: code shrink curve25519
function                                             old     new   delta
fe_select                                             39       -     -39
curve25519                                           849     800     -49
------------------------------------------------------------------------------
(add/remove: 0/1 grow/shrink: 0/1 up/down: 0/-88)             Total: -88 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-10-11 16:31:47 +02:00
Denys Vlasenko 74ee3f2f73 tls: remove unused tls_symmetric.h (was used by old "big" AES code)
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-10-11 13:46:30 +02:00
Bernhard Reutner-Fischer 376b2ceff6 chrt: silence analyzer warning
warning: use of uninitialized value ‘priority’ [CWE-457] [-Wanalyzer-use-of-uninitialized-value]

chrt_main                                            499     496      -3
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 0/1 up/down: 0/-3)               Total: -3 bytes
   text	   data	    bss	    dec	    hex	filename
 972157	   4235	   1840	 978232	  eed38	busybox_old
 972154	   4235	   1840	 978229	  eed35	busybox_unstripped

Signed-off-by: Bernhard Reutner-Fischer <rep.dot.nop@gmail.com>
2021-10-10 17:29:18 +02:00
Denys Vlasenko d8e39b5917 find: code shrink -{m,a,c}{time,min}
function                                             old     new   delta
time_cmp                                               -     181    +181
func_mmin                                            171      31    -140
func_mtime                                           180      34    -146
------------------------------------------------------------------------------
(add/remove: 1/0 grow/shrink: 0/2 up/down: 181/-286)         Total: -105 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-10-10 15:18:12 +02:00
Denys Vlasenko d3dbf4ac05 *: add more beneficial NOINLINEs
function                                             old     new   delta
dec_main                                               -    1729   +1729  -41 bytes
fallbackQSort3                                         -     671    +671  -70 bytes
verify_sun                                             -     481    +481 -107 bytes
verify                                              1330     742    -588
fallbackSort                                        1469     728    -741
unpack_xz_stream                                    2306     536   -1770
------------------------------------------------------------------------------
(add/remove: 3/0 grow/shrink: 0/3 up/down: 2881/-3099)       Total: -218 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-10-10 14:32:05 +02:00
Denys Vlasenko 53b2fdcdba *: add NOINLINEs where code noticeably shrinks
function                                             old     new   delta
display                                               85    1463   +1378  -73 bytes
select_and_cluster                                     -    1088   +1088 -139 bytes
parse_reply                                            -     979    +979 -109 bytes
zbc_num_sqrt                                           -     632    +632 -191 bytes
show_bridge_port                                       -     585    +585  -56 bytes
sp_256_proj_point_add_8                                -     576    +576  -45 bytes
encode_then_append_var_plusminus                       -     554    +554 -118 bytes
read_mode_db                                           -     537    +537  -47 bytes
fbset_main                                          1331     747    -584
sp_256_ecc_mulmod_8                                 1157     536    -621
brctl_main                                          2189    1548    -641
expand_one_var                                      2544    1872    -672
zxc_vm_process                                      6412    5589    -823
send_queries                                        1813     725   -1088
recv_and_process_peer_pkt                           2245    1018   -1227
bb_dump_dump                                        1531      80   -1451
------------------------------------------------------------------------------
(add/remove: 7/0 grow/shrink: 1/8 up/down: 6329/-7107)       Total: -778 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-10-10 13:50:53 +02:00
YU Jincheng 5156b24553 Make const ptr assign as function call in clang
- This can act as memory barrier in clang to avoid
  read before assign of a const ptr

Signed-off-by: LoveSy <shana@zju.edu.cn>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-10-09 22:30:45 +02:00
Ismael Luceno 04ad683bf9 find: implement -amin, -atime, -cmin, and -ctime
function                                             old     new   delta
func_mtime                                           130     180     +50
func_mmin                                            121     171     +50
static.params                                        235     261     +26
parse_params                                        1435    1461     +26
packed_usage                                       34025   34033      +8
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 5/0 up/down: 160/0)             Total: 160 bytes

Signed-off-by: Ismael Luceno <ismael@iodev.co.uk>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-10-09 21:45:59 +02:00
Denys Vlasenko 49bcf9f40c hush: speed up ${x//\*/|} too
function                                             old     new   delta
expand_one_var                                      2502    2544     +42

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-10-09 03:52:04 +02:00
Denys Vlasenko 5aaeb550b7 ash: speed up ${x//\*/|} too, make it independent of ASH_OPTIMIZE_FOR_SIZE
function                                             old     new   delta
subevalvar                                          1503    1545     +42

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-10-09 03:33:22 +02:00
Alin Mr 21e8dbfd9d ash.c: speedup ${s:} substring (no quotes)
This trivial patch makes ${s:...} at least as fast as ${s#??..}
in simple tests. It's probably faster for longer substrings,
but then one wouldn't use ${s#"1024???s"} anyway -
one would switch away from sh.

function                                             old     new   delta
subevalvar                                          1457    1503     +46

Signed-off-by: Alin Mr <almr.oss@outlook.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-10-09 02:15:52 +02:00
Ron Yorston 94eb1c4dc6 libbb: better coreutils compatibility for realpath
Add some tests which coreutils realpath pass but BusyBox realpath
fails (bar one).  Adjust xmalloc_realpath_coreutils() so the tests
pass:

- Expand symbolic links before testing whether the last path component
  exists.

- When the link target is a relative path canonicalize it by passing
  it through xmalloc_realpath_coreutils() as already happens for
  absolute paths.

- Ignore trailing slashes when finding the last path component and
  correctly handle the case where the only slash is at the start of
  the path.  This requires ignoring superfluous leading slashes.

- Undo all changes to the path so error messages from the caller show
  the original filename.

function                                             old     new   delta
xmalloc_realpath_coreutils                           214     313     +99

Signed-off-by: Ron Yorston <rmy@pobox.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-10-09 01:47:12 +02:00
Denys Vlasenko 86ba007b84 xxd: fix -p -r, closes 13881
function                                             old     new   delta
xxd_main                                             893     890      -3

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-10-08 23:03:54 +02:00
Denys Vlasenko d315a77a79 resize: use tcgetattr(TCSAFLUSH) instead of TCSANOW, closes 13811
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-10-08 22:18:24 +02:00
Andrej Valek ecac9853f2 mktemp: add --tmpdir option
Make mktemp more compatible with coreutils.
- add "--tmpdir" option
- add long variants for "d,q,u" options

Note: Upstream ca-certificate update script started using this option.

function                                             old     new   delta
.rodata                                           104179  104219     +40
mktemp_main                                          186     194      +8
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 2/0 up/down: 48/0)               Total: 48 bytes

Signed-off-by: Andrej Valek <andrej.valek@siemens.com>
Signed-off-by: Peter Marko <peter.marko@siemens.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-10-08 21:02:56 +02:00
Denys Vlasenko b198e9aa93 tar: improve comments, add FIXMEs. no code changes
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-10-08 19:34:20 +02:00
Denys Vlasenko 049775b2ef libbb.h: fix logic selecting incorrect BB_STRTOOFF for !LFS configs
BB_STRTOOFF() was equal to bb_strtou(). On x86_64, it's incorrect.

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-10-08 15:54:40 +02:00
Denys Vlasenko 84874785c2 httpd: if range is not specified, correctly fall back to read/write loop
range_start was staying -1, and comparison meant to detect
"is it the first sendfile that failed, or not the first?"
was making incorrect decision. The result: nothing is sent.

function                                             old     new   delta
send_file_and_exit                                   865     877     +12

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-10-08 15:41:08 +02:00
Denys Vlasenko 50c5b36dd7 help: s/Don't daemonize/Run in foreground/g
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-10-08 15:02:53 +02:00
Denys Vlasenko d2e0d3f514 mdev: tweak --help
function                                             old     new   delta
packed_usage                                       33993   34008     +15

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-10-08 14:30:50 +02:00
Denys Vlasenko cf4dc4a09d mount: "mount -o rw ...." should not fall back to RO mount
The reported case was an attempt to remount,rw a CD-ROM:

  mount -o remount,rw /mnt/sr0

which "succeeded" by falling back to RO:

  mount("/dev/sr0", "/mnt/sr0", 0x412862, MS_REMOUNT|MS_SILENT|MS_RELATIME, "nojoliet,check=s,map=n,blocksize"...) = -1 EROFS (Read-only file system)
  ...
  mount("/dev/sr0", "/mnt/sr0", 0x412862, MS_RDONLY|MS_REMOUNT|MS_SILENT|MS_RELATIME, "nojoliet,check=s,map=n,blocksize"...) = 0

Clearly, not what was intended!

function                                             old     new   delta
parse_mount_options                                  241     267     +26
mount_main                                          1198    1211     +13
singlemount                                         1301    1313     +12
inetd_main                                          1919    1911      -8
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 3/1 up/down: 51/-8)              Total: 43 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-10-08 02:20:10 +02:00
Nicholas Niro c28313bb17 ip: added support for setting netns on devices
function                                             old     new   delta
set_netns                                              -     130    +130
do_iplink                                           1252    1315     +63
.rodata                                           104173  104179      +6
packed_usage                                       34020   33993     -27
------------------------------------------------------------------------------
(add/remove: 1/0 grow/shrink: 2/1 up/down: 199/-27)           Total: 172 bytes

Signed-off-by: Nicholas Niro <blowfist@xroutine.net>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-10-07 23:24:56 +02:00
Denys Vlasenko eb048a450c ps: fix -o pid=PID,args interpreting entire "PID,args" as header
procps-ng 3.3.15 does not do this.
(It could, allowing commas in headers and requiring
"ps -opid=PID -oargs" form for this case, but it does not).

function                                             old     new   delta
parse_o                                              167     190     +23

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-10-07 21:55:16 +02:00
Ismael Luceno 421c8767ba find: Unify time comparisons
Split the common part into a function, to be reused.

The tail call is optimized, meaning now mmin/mtime just prepare arguments
and jump into the common code, thus near zero overhead.

This reduces code size slightly, e.g. on x86_64:
   text    data     bss     dec     hex filename
   4806       0       0    4806    12c6 findutils/find.o.orig
   4782       0       0    4782    12ae findutils/find.o

Of course, the savings are even greater when implementing atime/ctime
variants.

Signed-off-by: Ismael Luceno <ismael@iodev.co.uk>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-10-07 16:40:37 +02:00
Ismael Luceno 0084c44799 config: find: Fix mtime/mmin description
s/modified time/modification time/

Signed-off-by: Ismael Luceno <ismael@iodev.co.uk>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-10-07 16:38:32 +02:00
YU Jinchengandcanyie 1f925038ab *: generalize "const trick"
While at it, change all "__asm__" to "asm"

Co-authored-by: canyie <31466456+canyie@users.noreply.github.com>
Signed-off-by: YU Jincheng <shana@zju.edu.cn>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-10-07 15:22:35 +02:00
Denys Vlasenko 17e6fb06b3 tls: whitespace fix
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-10-06 21:22:36 +02:00
Denys Vlasenko 5e9c617021 tls: P256: sp_256_sub_8_p256_mod always subtracts in-place, use that
i386:

function                                             old     new   delta
sp_256_mont_reduce_8                                 245     243      -2
sp_256_mont_dbl_8                                     26      24      -2
sp_256_ecc_mulmod_8                                 1161    1157      -4
sp_256_proj_point_dbl_8                              359     353      -6
sp_256_sub_8_p256_mod                                 71      32     -39
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 0/5 up/down: 0/-53)             Total: -53 bytes

non-asm code:

function                                             old     new   delta
sp_256_sub_8_p256_mod                                  -      12     +12
sp_256_mont_reduce_8                                 250     243      -7
sp_256_mont_dbl_8                                     31      24      -7
sp_256_ecc_mulmod_8                                 1171    1157     -14
sp_256_proj_point_dbl_8                              374     353     -21
------------------------------------------------------------------------------
(add/remove: 1/0 grow/shrink: 0/4 up/down: 12/-49)            Total: -37 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-10-06 20:19:30 +02:00
Denys Vlasenko 87e3f2e9f8 tls: P256: x86-64 optimized sp_256_sub_8_p256_mod
function                                             old     new   delta
sp_256_sub_8_p256_mod                                  -      53     +53
sp_256_mont_reduce_8                                 223     217      -6
sp_256_mont_dbl_8                                     38      32      -6
sp_256_ecc_mulmod_8                                 1535    1529      -6
sp_256_proj_point_dbl_8                              469     454     -15
------------------------------------------------------------------------------
(add/remove: 1/0 grow/shrink: 0/4 up/down: 53/-33)             Total: 20 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-10-06 19:59:39 +02:00
Denys Vlasenko 911344a998 tls: P256: x86-64 assembly
function                                             old     new   delta
sp_256_mont_mul_8                                    127     155     +28
sp_256_proj_point_dbl_8                              448     469     +21
sp_256_mont_sub_8                                     23      35     +12
sp_256_mont_dbl_8                                     26      38     +12
sp_256_sub_8                                          44      49      +5
sp_256_ecc_mulmod_8                                 1530    1535      +5
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 6/0 up/down: 83/0)               Total: 83 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-10-06 17:17:34 +02:00
Denys Vlasenko 22fd8fd3f4 tls: P256: tweak arm assembly (currently disabled)
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-10-06 16:10:49 +02:00
Denys Vlasenko d74993d31d tls: P@256: remove "header comment is kept intact" comment
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-10-06 14:28:47 +02:00
Denys Vlasenko 567eefcaf8 tls: P256: do not dumplicate sp_256_sub_8()
function                                             old     new   delta
sp_256_proj_point_dbl_8                              359     374     +15
sp_256_ecc_mulmod_8                                 1159    1171     +12
sp_256_mont_reduce_8                                 245     250      +5
sp_256_mont_dbl_8                                     26      31      +5
sp_256_sub_8_p256_mod                                 43       -     -43
------------------------------------------------------------------------------
(add/remove: 0/1 grow/shrink: 4/0 up/down: 37/-43)             Total: -6 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-10-06 14:25:54 +02:00
Denys Vlasenko 00f2cceb6a tls: P256: shrink sp_256_mul_add_8 a bit more
function                                             old     new   delta
sp_256_mont_reduce_8                                 257     245     -12

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-10-06 10:15:29 +02:00
Denys Vlasenko c784284615 tls: P256: propagate constants, create dedicated "subtract p256_mod" function
8 instances of this subtraction probably warrant a few bytes more of code.

function                                             old     new   delta
sp_256_sub_8_p256_mod                                  -      71     +71
sp_256_mont_sub_8                                      -      29     +29
sp_256_mont_dbl_8                                      -      26     +26
sp_256_mont_reduce_8                                 262     257      -5
sp_256_ecc_mulmod_8                                 1171    1161     -10
sp_256_proj_point_dbl_8                              374     359     -15
static.sp_256_mont_sub_8                              29       -     -29
static.sp_256_mont_dbl_8                              31       -     -31
------------------------------------------------------------------------------
(add/remove: 3/2 grow/shrink: 0/3 up/down: 126/-90)            Total: 36 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-10-06 01:11:48 +02:00
Denys Vlasenko 2430fcfd8d tls: optimize sp_256_mont_reduce_8 in P256
The code size decrease is small, but we eliminate ALL multiplies!

function                                             old     new   delta
sp_256_mont_reduce_8                                 268     262      -6

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-10-06 00:24:03 +02:00
Denys Vlasenko bbd723ebec tls: optimize sp_256_mul_8 in P256
function                                             old     new   delta
sp_256_mont_mul_8                                    151     150      -1

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-10-05 23:19:18 +02:00
Denys Vlasenko 3b411ebbfc tls: replace "26-bit" P256 code with 32-bit one.
function                                             old     new   delta
sp_256_ecc_mulmod_8                                    -    1171   +1171
sp_256_mod_mul_norm_8                                  -     834    +834
sp_256_proj_point_dbl_8                                -     374    +374
sp_256_mont_reduce_8                                   -     268    +268
sp_256_mont_mul_8                                      -     151    +151
sp_256_sub_8                                           -      76     +76
sp_256_add_8                                           -      76     +76
sp_256_cmp_8                                           -      38     +38
static.sp_256_mont_dbl_8                               -      31     +31
static.sp_256_mont_sub_8                               -      29     +29
sp_256_to_bin_8                                        -      28     +28
sp_256_point_from_bin2x32                             50      73     +23
sp_256_mont_sqr_8                                      -       7      +7
sp_256_mont_sqr_10                                     7       -      -7
p256_mod                                              40      32      -8
curve_P256_compute_pubkey_and_premaster              186     167     -19
sp_256_sub_10                                         22       -     -22
sp_256_add_10                                         22       -     -22
sp_256_cmp_10                                         24       -     -24
sp_256_norm_10                                        31       -     -31
static.sp_256_mont_sub_10                             49       -     -49
static.sp_256_mont_dbl_10                             52       -     -52
static.sp_256_mul_add_10                              82       -     -82
sp_256_from_bin_10                                   119       -    -119
sp_256_to_bin_10                                     120       -    -120
sp_256_mont_reduce_10                                178       -    -178
sp_256_mont_mul_10                                   214       -    -214
sp_256_proj_point_dbl_10                             451       -    -451
sp_256_ecc_mulmod_10                                1216       -   -1216
sp_256_mod_mul_norm_10                              1305       -   -1305
------------------------------------------------------------------------------
(add/remove: 12/15 grow/shrink: 1/2 up/down: 3106/-3919)     Total: -813 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-10-05 20:01:38 +02:00
Denys Vlasenko 55578f2fb7 tls: fix the case of sp_256_mont_tpl_10() leaving striay high bits
It has no effect on correctness, but interferes with compating internal state
of different implementations.

function                                             old     new   delta
sp_256_proj_point_dbl_10                             443     451      +8
static.sp_256_mont_sub_10                             46      49      +3
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 2/0 up/down: 11/0)               Total: 11 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-10-05 19:46:39 +02:00
Denys Vlasenko 81d8af1970 tls: fix (what looks like) a rare corner case bug in P256
function                                             old     new   delta
static.sp_256_mont_sub_10                             30      46     +16

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-10-05 17:31:33 +02:00
Denys Vlasenko 92402d5e0a tls: remove one overzealous debugging statement
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-10-05 14:01:52 +02:00
Denys Vlasenko 137864f559 tls: add debugging scaffolding to P256 code
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-10-05 13:50:11 +02:00
Denys Vlasenko 389329efbe tls: another P256 code shrink
Propagate constant arrays and scalars deeper down call chain.
Use sp_256_mont_mul_10 to implement sp_256_mont_sqr_10.

function                                             old     new   delta
sp_256_mont_mul_10                                     -     214    +214
sp_256_mont_reduce_10                                  -     178    +178
sp_256_mont_sqr_10                                     -       7      +7
static.sp_256_mont_reduce_10                         178       -    -178
static.sp_256_mont_mul_10                            214       -    -214
static.sp_256_mont_sqr_10                            234       -    -234
------------------------------------------------------------------------------
(add/remove: 3/3 grow/shrink: 0/0 up/down: 399/-626)         Total: -227 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-10-05 13:39:33 +02:00
Denys Vlasenko e730505034 tls: P256 code shrink
function                                             old     new   delta
sp_256_to_bin_10                                       -     120    +120
sp_256_from_bin_10                                     -     119    +119
sp_256_proj_point_dbl_10                             446     443      -3
curve_P256_compute_pubkey_and_premaster              191     186      -5
sp_256_point_from_bin2x32                             62      50     -12
sp_256_to_bin                                        120       -    -120
static.sp_256_from_bin                               149       -    -149
------------------------------------------------------------------------------
(add/remove: 2/2 grow/shrink: 0/3 up/down: 239/-289)          Total: -50 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-10-05 13:32:04 +02:00
Denys Vlasenko 934bb01d51 tls: "server cert is not RSA" is a fatal error
function                                             old     new   delta
tls_handshake                                       2022    2019      -3

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-10-01 22:03:09 +02:00
Ron Yorston ed9aa89269 wget: implement --post-file
Add the --post-file option to send form data from a file.  As with
--post-data it's up to the user to ensure that the data is encoded
as appropriate:  all wget does is stuff the provided data into
the request.

The --post-data and --post-file options are mutually exclusive and
only one instance of either may be given.

Additionally:

- update the usage message to include missing details of the --post-data
  and --header options;

- free POST data if FEATURE_CLEAN_UP is enabled.

function                                             old     new   delta
packed_usage                                       34158   34214     +56
wget_main                                           2762    2805     +43
.rodata                                            99225   99240     +15
static.wget_longopts                                 266     278     +12
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 4/0 up/down: 126/0)             Total: 126 bytes

Signed-off-by: Ron Yorston <rmy@pobox.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-10-01 14:55:18 +02:00
Denys Vlasenko 1f5a44d20c tls: add scaffolding to selectively disable ciphers. no code changes
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-10-01 14:27:10 +02:00
Denys Vlasenko 7714518f1a tls: code shrink P256 code
function                                             old     new   delta
sp_256_to_bin                                        148     120     -28

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-10-01 13:51:39 +02:00
Denys Vlasenko ac36e70074 tls: remove unused define
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-09-30 00:03:23 +02:00
Ismael Luceno 35727f5741 less: Ignore -X
The flag disables termcap init/deinit of the terminal, which the applet
doesn't do anyway.

Signed-off-by: Ismael Luceno <ismael@iodev.co.uk>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-09-28 23:22:47 +02:00
Denys Vlasenko 5b026d1ecf ash: fix compile breakage in !ENABLE_ASH_ALIAS config
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-09-28 17:41:56 +02:00
Denys Vlasenko 03ed86b39e libbb: code shrink in main() and scripted_main()
function                                             old     new   delta
main                                                  68      65      -3
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 0/1 up/down: 0/-3)               Total: -3 bytes
   text	   data	    bss	    dec	    hex	filename
   1472	    560	     16	   2048	    800	busybox_old
   1398	    552	     16	   1966	    7ae	busybox_unstripped

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-09-28 17:40:59 +02:00
Denys Vlasenko 1be73dd9ad shell: fix parsing of $(( (v)++ + NUM ))
function                                             old     new   delta
evaluate_string                                      988    1011     +23

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-09-26 13:29:25 +02:00
Denys Vlasenko 62e433131b shell: enable more tests which are passing now
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-09-25 22:35:17 +02:00
Denys Vlasenko d84a604830 shell: fix arithmentic evaluation of "++7" and such (it is + + 7, i.e. 7)
function                                             old     new   delta
evaluate_string                                      945     988     +43

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-09-25 22:04:45 +02:00
Denys Vlasenko 627821e42b libbb/lineedit: tweak #if indenting, no code changes
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-09-25 19:36:35 +02:00
Ron Yorston 56f0e886db cal: implement -m
Some people prefer the week to start on Monday.  Add the '-m'
option to support this.

function                                             old     new   delta
cal_main                                             926     966     +40
day_array                                            316     337     +21
packed_usage                                       34151   34158      +7
.rodata                                            99224   99225      +1
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 4/0 up/down: 69/0)               Total: 69 bytes

Signed-off-by: Ron Yorston <rmy@pobox.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-09-21 15:25:37 +02:00
Ron Yorston f27a6a94a7 libbb: code shrink parse_datestr (again)
Commit 9fe1548bb (date,touch: allow timezone offsets in dates)
mentioned the similarity between '@' format dates and those with
timezone offsets.  It didn't notice that as a result there's
common code which can be shared.

function                                             old     new   delta
parse_datestr                                        730     687     -43
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 0/1 up/down: 0/-43)             Total: -43 bytes

Signed-off-by: Ron Yorston <rmy@pobox.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-09-18 22:55:46 +02:00
Denys Vlasenko 6d2463ac01 libbb/lineedit: do not escape %^=+}]:, escape ~? in tab completion
function                                             old     new   delta
.rodata                                           104185  104180      -5

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-09-17 17:33:32 +02:00
Denys Vlasenko 6279aec03d libbb: clarify what bb_mode_string() generates
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-09-17 17:10:38 +02:00
Ron Yorston 3a65435eaa libbb: ensure mode_string is NUL terminated
If the mode_string array is no longer static we can't rely on
it being NUL terminated.

function                                             old     new   delta
bb_mode_string                                       115     118      +3

Signed-off-by: Ron Yorston <rmy@pobox.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-09-17 16:51:01 +02:00
Denys Vlasenko 59ac467dc6 libbb: eliminate a static data array in bb_mode_string()
function                                             old     new   delta
print_stat                                           861     869      +8
header_verbose_list_ar                                73      77      +4
display_single                                       975     979      +4
header_verbose_list                                  237     239      +2
bb_mode_string                                       124     115      -9
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 4/1 up/down: 18/-9)               Total: 9 bytes
   text	   data	    bss	    dec	    hex	filename
1043136	    559	   5052	1048747	 1000ab	busybox_old
1043153	    559	   5020	1048732	 10009c	busybox_unstripped

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-09-17 01:18:31 +02:00
Denys Vlasenko 4958c18134 libbb: code shrink bb_parse_mode
function                                             old     new   delta
bb_parse_mode                                        393     398      +5
static.who_mask                                       16       8      -8
static.perm_mask                                      24      12     -12
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 1/2 up/down: 5/-20)             Total: -15 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-09-17 00:47:23 +02:00
Denys Vlasenko 2df4e0a370 chmod: correctly report changed modes
Chmod used to incorrectly report as changed even files for which the
mode did not change. This was caused by extra bits in the st_mode, that
were not present when parsed from passed argument in the form of octal
number.

Patch by Wolf <wolf@wolfsden.cz>.

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-09-17 00:39:21 +02:00
Ron Yorston 9fe1548bbf date,touch: allow timezone offsets in dates
Allow ISO 8601 style dates to include a timezone offset.  Like
the '@' format these dates aren't relative to the user's current
timezone and shouldn't be subject to DST adjustment.

- The implementation uses the strptime() '%z' format specifier.
  This an extension which may not be available so the use of
  timezones is a configuration option.

- The 'touch' applet has been updated to respect whether DST
  adjustment is required, matching 'date'.

function                                             old     new   delta
parse_datestr                                        624     730    +106
static.fmt_str                                       106     136     +30
touch_main                                           388     392      +4
date_main                                            818     819      +1
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 4/0 up/down: 141/0)             Total: 141 bytes

Signed-off-by: Ron Yorston <rmy@pobox.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-09-17 00:11:30 +02:00
Ron Yorston 83e20cb81c getopt: code shrink
function                                             old     new   delta
.rodata                                            99277   99290     +13
normalize                                            177     142     -35
getopt_main                                          675     622     -53
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 1/2 up/down: 13/-88)            Total: -75 bytes

Signed-off-by: Ron Yorston <rmy@pobox.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-09-16 01:09:32 +02:00
Denys Vlasenko 704c596563 ash: introduce bash-like $FUNCNAME
Patch adapted from Roberto A. Foglietta <roberto.foglietta@gmail.com>
work.

function                                             old     new   delta
lookupvar                                            106     150     +44
evalfun                                              369     408     +39
ash_main                                            1218    1242     +24
varinit_data                                         156     168     +12
.rodata                                           104162  104172     +10
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 5/0 up/down: 129/0)             Total: 129 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-09-15 19:31:44 +02:00
Ron Yorston 3512ef8018 libbb: code shrink parse_datestr
The default build uses strptime() in parse_datestr() to support the
'month_name d HH:MM:SS YYYY' format of GNU date.  If we've linked
with strptime() there's an advantage is using it for other formats
too.

There's no change to the non-default, non-DESKTOP build.

function                                             old     new   delta
fmt_str                                                -     106    +106
.rodata                                            99216   99145     -71
parse_datestr                                        948     624    -324
------------------------------------------------------------------------------
(add/remove: 1/0 grow/shrink: 0/2 up/down: 106/-395)         Total: -289 bytes

Signed-off-by: Ron Yorston <rmy@pobox.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-09-15 08:09:45 +02:00
Ron Yorston 5726df5f94 ash: let ignoreeof only affect interactive shells
Commit fb7d6c89 from Harald van Dijk's gwsh variant of ash
(https://github.com/hvdijk/gwsh):

    ignoreeof is documented as only having an effect for interactive shells,
    but is implemented as having mostly the same effect for interactive
    shells as for non-interactive shells. Change the implementation to match
    the documentation.

    Test case:

      $SHELL -o ignoreeof /dev/null

function                                             old     new   delta
cmdloop                                              359     361      +2
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 1/0 up/down: 2/0)                 Total: 2 bytes

Signed-off-by: Ron Yorston <rmy@pobox.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-09-14 08:25:58 +02:00
Ron Yorston 50239a665c ash: stopped jobs should only prevent exit from interactive shell
When the user tries to exit an interactive shell with stopped jobs
present the shell issues a warning and only exits if the user
insists by trying to exit again.

This shouldn't apply to non-interactive shells.

Reported-by: Roberto A. Foglietta <roberto.foglietta@gmail.com>
Signed-off-by: Ron Yorston <rmy@pobox.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-09-14 08:16:15 +02:00
Ron Yorston 0beee20977 ash: fix ignoreeof option
The ignoreeof option should prevent an interactive shell from
exiting on EOF.  This hasn't worked in BusyBox ash since commit
727752d2d (ash: better fix for ash -c 'echo 5&' and ash -c 'sleep 5&'
with testcase).

Commit 3b4d04b77e (ash: input: Allow two consecutive calls to pungetc)
pulled in improved support for multiple calls to pungetc from dash,
thus rendering much of commit 727752d2d obsolete.  Removing this old
code fixes the problem with ignoreeof.

function                                             old     new   delta
__pgetc                                              605     587     -18
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 0/1 up/down: 0/-18)             Total: -18 bytes

Signed-off-by: Ron Yorston <rmy@pobox.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-09-14 08:16:15 +02:00
Denys Vlasenko 9346ea9550 df: "support" -H as an alias of -h
function                                             old     new   delta
df_main                                             1065    1068      +3
.rodata                                           104232  104233      +1
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 2/0 up/down: 4/0)                 Total: 4 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-09-11 00:47:03 +02:00
Denys Vlasenko 40f2dd7dd2 httpd: fix config deps
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-09-10 10:07:42 +02:00
Denys Vlasenko c00bcf2d2c libbb: reuse "bad port" error message string
function                                             old     new   delta
.rodata                                           104251  104232     -19

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-09-10 09:48:55 +02:00
Denys Vlasenko c421388dca blkdiscard: accept -f (force) as no-op
function                                             old     new   delta
.rodata                                           104250  104251      +1

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-09-10 00:20:05 +02:00
Denys Vlasenko 0599e0f87b basename: implement -a and -s SUFFIX
function                                             old     new   delta
basename_main                                        145     207     +62
packed_usage                                       33914   33950     +36
.rodata                                           104241  104250      +9
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 3/0 up/down: 107/0)             Total: 107 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-09-09 23:45:13 +02:00
Denys Vlasenko 7ab9cd2398 libbb: make bb_lookup_port() abort on bad port names
Also, no need to preserve errno

function                                             old     new   delta
.rodata                                           104247  104241      -6
bb_lookup_port                                        97      83     -14
nc_main                                             1039    1018     -21
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 0/3 up/down: 0/-41)             Total: -41 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-09-09 22:00:44 +02:00
Sergey Ponomarev 82c5eb8e46 httpd,telnetd: make default port configurable
BusyBox on Termux can't use ports less than 1024 it's patched to change default port for httpd to 8080 and telnetd to 8023.

https://github.com/termux/termux-packages/blob/master/packages/busybox/0011-networking-telnetd-default-port.patch
https://github.com/termux/termux-packages/blob/master/packages/busybox/0010-networking-httpd-default-port.patch

To avoid such patches we can make port configurable.

function                                             old     new   delta
packed_usage                                       33920   33914      -6

Signed-off-by: Sergey Ponomarev <stokito@gmail.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-09-09 21:42:48 +02:00
Denys Vlasenko 857800c655 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-09 19:26:39 +02:00
Denys Vlasenko e60c56932e awk: code shrink
function                                             old     new   delta
awk_printf                                           652     651      -1

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-09-09 19:13:32 +02:00
Denys Vlasenko 8a0adba9f6 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-09 18:58:39 +02:00
Ron Yorston 305a30d80b 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-09 18:12:21 +02:00
Denys Vlasenko eb60777769 ash: eval: Prevent recursive PS4 expansion
Date: Wed, 27 May 2020 13:19:10 +1000
eval: Prevent recursive PS4 expansion

    Yaroslav Halchenko <yoh@onerussian.com> wrote:
    > I like to (ab)use PS4 and set -x for tracing execution of scripts.
    > Reporting time and PID is very useful in this context.
    >
    > I am not 100% certain if bash's behavior (of actually running the command
    > embedded within PS4 string, probably eval'ing it) is actually POSIX
    > compliant, posh seems to not do that; but I think it is definitely not
    > desired for dash to just stall:
    >
    > - the script:
    > #!/bin/sh
    > set -x
    > export PS4='+ $(date +%T.%N) [$$] '
    > echo "lets go"
    > sleep 1
    > echo "done $var"
    >
    > - bash:
    > /tmp > bash --posix test.sh
    > +export 'PS4=+ $(date +%T.%N) [$$] '
    > +PS4='+ $(date +%T.%N) [$$] '
    > + 09:15:48.982296333 [2764323] echo 'lets go'
    > lets go
    > + 09:15:48.987829613 [2764323] sleep 1
    > + 09:15:49.994485037 [2764323] echo 'done '
    > done
    >
    ...
    > - dash: (stalls it set -x)
    > /tmp > dash test.sh
    > +export PS4=+ $(date +%T.%N) [$$]
    > ^C^C

    This patch fixes the infinite loop caused by repeated expansions
    of PS4.

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-09-09 16:29:37 +02:00
Denys Vlasenko 48cb983b13 ash: parser: Get rid of PEOA
Upstream commit:

    Date: Wed, 27 May 2020 12:19:13 +1000
    parser: Get rid of PEOA

    PEOA is a special character used to mark an alias as being finished
    so that we don't enter an infinite loop with nested aliases.  It
    complicates the parser because we have to ensure that it is skipped
    where necessary and not copied to the resulting token text.

    This patch removes it and instead delays the marking of aliases
    until the second pgetc.  This has the same effect as the current
    PEOA code while keeping the complexities within the input code.

This adds ~32 bytes of global data:

function                                             old     new   delta
__pgetc                                                -     512    +512
freestrings                                            -      95     +95
popfile                                               86     110     +24
pushstring                                           141     160     +19
basepf                                                76      84      +8
syntax_index_table                                   258     257      -1
S_I_T                                                 30      28      -2
.rodata                                           104255  104247      -8
pgetc_without_PEOA                                    13       -     -13
xxreadtoken                                          230     215     -15
popstring                                            158     120     -38
readtoken1                                          3110    3045     -65
pgetc                                                547      22    -525
------------------------------------------------------------------------------
(add/remove: 2/1 grow/shrink: 3/7 up/down: 658/-667)           Total: -9 bytes
   text	   data	    bss	    dec	    hex	filename
1043102	    559	   5020	1048681	 100069	busybox_old
1043085	    559	   5052	1048696	 100078	busybox_unstripped

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-09-08 09:52:04 +02:00
Denys Vlasenko 8c68ae8416 ash: parser: Fix alias expansion after heredoc or newlines
Upstream commit:

    Date: Wed, 29 Apr 2020 00:19:59 +1000
    parser: Fix alias expansion after heredoc or newlines

    This script should print OK:

        alias a="case x in " b=x
        a
        b) echo BAD;; esac

        alias BEGIN={ END=}
        BEGIN
    	cat <<- EOF > /dev/null
    		$(:)
    	EOF
        END
        : <<- EOF &&
    		$(:)
        EOF
        BEGIN
    	echo OK
        END

    However, because the value of checkkwd is either zeroed when it
    shouldn't, or isn't zeroed when it should, dash currently gets
    it wrong in every case.

    This patch fixes it by saving checkkwd and zeroing it where needed.

function                                             old     new   delta
readtoken                                            157     176     +19

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-09-08 01:43:12 +02:00
Denys Vlasenko c540256127 ash: use pgetc_eatbnl() in more places, take 3
Adding previously skipped "readtoken1(pgetc_eatbnl(), syntax_type..." change
from upstream commit:

    Date:   Thu Mar 8 08:37:11 2018 +0100
    parser: use pgetc_eatbnl() in more places

    dash has a pgetc_eatbnl function in parser.c which skips any
    backslash-newline combinations. It's not used everywhere it could be.
    There is also some duplicated backslash-newline handling elsewhere in
    parser.c. Replace most of the calls to pgetc() with calls to
    pgetc_eatbnl() and remove the duplicated backslash-newline handling.

Testcase:
	PS1='\
	:::'
should result in ::: prompt, not <newline>::: prompt

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-09-08 01:13:40 +02:00
Denys Vlasenko 1c06ddd8bb ash: parser: Save and restore heredoclist in expandstr
Upstream commit:

    Date: Sun, 17 May 2020 23:36:25 +1000
    parser: Save and restore heredoclist in expandstr

    On Sun, May 17, 2020 at 01:19:28PM +0100, Harald van Dijk wrote:
    > This still does not restore the state completely. It does not clean up any
    > pending heredocs. I see:
    >
    >   $ PS1='$(<<EOF "'
    >   src/dash: 1: Syntax error: Unterminated quoted string
    >   $(<<EOF ":
    >   >
    >
    > That is, after entering the ':' command, the shell is still trying to read
    > the heredoc from the prompt.

    This patch saves and restores the heredoclist in expandstr.

    It also removes a bunch of unnecessary volatiles as those variables
    are only referenced in case of a longjmp other than one started by
    a signal like SIGINT.

function                                             old     new   delta
expandstr                                            268     255     -13

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-09-08 00:56:53 +02:00
Denys Vlasenko 30af5938af ash: parser: Fix handling of empty aliases
Upstream commit:

    Date: Tue, 28 Apr 2020 01:15:26 +1000
    parser: Fix handling of empty aliases

    Dash was incorrectly handling empty aliases. When attempting to use an
    empty alias with nothing else, I'm (incorrectly) prompted for more
    input:

    ```
    $ alias empty=''
    $ empty
    >
    ```

    Other shells (e.g., bash, yash) correctly handle the lone, empty alias as an
    empty command:

    ```
    $ alias empty=''
    $ empty
    $
    ```

    The problem here is that we incorrectly enter the loop eating TNLs
    in readtoken().  This patch fixes it by setting checkkwd correctly.

function                                             old     new   delta
list                                                 351     355      +4

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-09-08 00:39:16 +02:00
Denys Vlasenko 6a9b3f7acf shuf: add a TODO, code shrink
function                                             old     new   delta
shuf_main                                            501     500      -1

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-09-07 22:51:42 +02:00
Denys Vlasenko 574b9c446d hush: fix var_LINENO3.tests failure
function                                             old     new   delta
parse_and_run_string                                  40      62     +22
i_getch                                              105     102      -3
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 1/1 up/down: 22/-3)              Total: 19 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-09-07 21:44:44 +02:00
Denys Vlasenko bcff3a7b5a shell/ash_test/run-all: unset locale/language variables
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-09-07 18:24:08 +02:00
Denys Vlasenko 64aa86b720 ash: LINENO starts from 0 in -c SCRIPT mode
The var_LINENO3.tests fails for hush: it does start from 0, but does not increment.

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-09-07 18:16:45 +02:00
Denys Vlasenko d6c9cbc072 ash: fix LINENO in functions
From larger patch by Roberto A. Foglietta <roberto.foglietta@gmail.com>

function                                             old     new   delta
evalfun                                              348     369     +21
ash_main                                            1202    1218     +16
setinputstring                                        65      73      +8
lookupvar                                            116     106     -10
evaltree                                             772     753     -19
evalsubshell                                         192     173     -19
evalfor                                              175     156     -19
evalcase                                             273     254     -19
evalcommand                                         1560    1536     -24
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 3/6 up/down: 45/-110)           Total: -65 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-09-07 18:01:49 +02:00
Denys Vlasenko 0d7dfa9012 ash: support testsuite for !FEATURE_SUID_CONFIG_QUIET configs
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-09-07 17:34:58 +02:00
Denys Vlasenko e53c7dbafc hush: fix set -n to act immediately, not just after run_list()
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-09-07 02:25:52 +02:00
Denys Vlasenko f415e21a7d ash: eval: Do not cache value of eflag in evaltree
Upsteam commit:

    Date: Mon, 17 May 2021 15:19:23 +0800
    eval: Do not cache value of eflag in evaltree

    Patrick Brünn <P.Bruenn@beckhoff.com> wrote:
    > Since we are migrating to Debian bullseye, we discovered a new behavior
    > with our scripts, which look like this:
    >>cleanup() {
    >>        set +e
    >>        rmdir ""
    >>}
    >>set -eu
    >>trap 'cleanup' EXIT INT TERM
    >>echo 'Hello world!'
    >
    > With old dash v0.5.10.2 this script would return 0 as we expected it.
    > But since commit 62cf6955f8abe875752d7163f6f3adbc7e49ebae it returns
    > the last exit code of our cleanup function.
    ...
    Thanks for the report.  This is actually a fairly old bug with
    set -e that's just been exposed by the exit status change.  What's
    really happening is that cleanup itself is triggering a set -e
    exit incorrectly because evaltree cached the value of eflag prior
    to the function call.

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-09-07 02:01:03 +02:00
Denys Vlasenko 41beb53787 ash: eval: Check nflag in evaltree instead of cmdloop
Upstream commit:

    Date: Thu, 4 Jun 2020 21:53:55 +1000
    eval: Check nflag in evaltree instead of cmdloop

    This patch moves the nflag check from cmdloop into evaltree.  This
    is so that nflag will be in force even if we enter the shell via a
    path other than cmdloop, e.g., through sh -c.

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-09-07 01:52:21 +02:00
Roberto A. Foglietta e0bf3df020 ash: add bash-like ERR trap and set -E
While at it, stop incrementing LINENO inside traps

function                                             old     new   delta
evaltree                                             567     762    +195
evalfun                                              268     348     +80
trapcmd                                              286     333     +47
dotrap                                               129     157     +28
exitshell                                            120     139     +19
readtoken1                                          3096    3110     +14
nlprompt                                              25      39     +14
nlnoprompt                                            19      33     +14
.rodata                                           104245  104255     +10
forkchild                                            610     617      +7
optletters_optnames                                   64      68      +4
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 11/0 up/down: 432/0)            Total: 432 bytes

Signed-off-by: Roberto A. Foglietta <roberto.foglietta@gmail.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-09-07 01:28:50 +02:00
Denys Vlasenko 4b032a4d6c 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-06 17:38:18 +02:00
Daniel Thau 7d06d6e186 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-05 03:42:51 +02:00
Denys Vlasenko f4ba69d476 shuf: make -i 99999999990-100000000000 work even on 32 bits
function                                             old     new   delta
shuf_main                                            443     501     +58
.rodata                                           104238  104245      +7
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 2/0 up/down: 65/0)               Total: 65 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-09-04 17:00:22 +02:00
Denys Vlasenko 8aa626ffff udhcp: add comments, no code changes
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-09-04 01:50:42 +02:00
Denys Vlasenko d7e39f26d7 examples/var_service/fw/run: allow extif's to be more than one iface
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-09-02 23:53:48 +02:00
Ron Yorston 4a36ef11ac 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-02 17:49:00 +02:00
Denys Vlasenko f02691939e dhcprelay: change two more variables to unsigned
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-09-02 17:09:12 +02:00
Denys Vlasenko 3f2d969db9 udhcp: clarify aspects of relay operation, add TODOs and FIXMEs, tweak --help
function                                             old     new   delta
packed_usage                                       33891   33920     +29
dhcprelay_main                                       943     926     -17
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 1/1 up/down: 29/-17)             Total: 12 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-09-02 16:24:52 +02:00
Denys Vlasenko 62d0c8e028 udhcpd: check config file for bad IP ranges (start > end)
function                                             old     new   delta
.rodata                                           104209  104238     +29
read_config                                          208     225     +17
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 2/0 up/down: 46/0)               Total: 46 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-09-02 14:40:54 +02:00
Denys Vlasenko d99dee944e udhcpd: update --help to include -a MSEC
function                                             old     new   delta
packed_usage                                       33886   33891      +5

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-09-02 14:02:23 +02:00
Ron Yorston a51d953b95 vi: further changes to colon addresses
Improved error messages:

- specify when a search fails or a mark isn't set;
- warn when line addresses are out of range or when a range of
  lines is reversed.

Addresses are limited to the number of lines in the file so a
command like ':2000000000' (go to the two billionth line) no
longer causes a long pause.

Improved vi compatibility of '+' and '-' operators that aren't
followed immediately by a number:

   :4+++=       7
   :3-2=        1
   :3 - 2=      4 (yes, really!)

In a command like ':,$' the empty address before the separator now
correctly refers to the current line.  (The similar case ':1,' was
already being handled.)

And all with a tidy reduction in bloat (32-bit build):

function                                             old     new   delta
colon                                               4029    4069     +40
.rodata                                            99348   99253     -95
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 1/1 up/down: 40/-95)            Total: -55 bytes

Signed-off-by: Ron Yorston <rmy@pobox.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-08-29 20:07:20 +02:00
Denys Vlasenko 6d3da732a5 bzip: make ftab[] and crc32table[] member arrays of EState, do not allocate
function                                             old     new   delta
mainSort                                             941     986     +45
fallbackSort                                        1471    1469      -2
add_pair_to_block                                    194     188      -6
compressStream                                       543     515     -28
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 1/3 up/down: 45/-36)              Total: 9 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-08-29 15:32:42 +02:00
Denys Vlasenko 49a2e484b5 shuf: in -i RANGE, accept numbers up to width of pointers
function                                             old     new   delta
.rodata                                           108468  108474      +6
shuf_main                                            555     542     -13

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-08-29 14:39:01 +02:00
Denys Vlasenko 60f4843468 shuf: with -i LOW-HIGH, do not allow any argv's
function                                             old     new   delta
shuf_main                                            436     441      +5

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-08-23 15:52:34 +02:00
Denys Vlasenko d59f539d57 shuf: tweak --help text
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-08-23 15:48:22 +02:00
Denys Vlasenko 1b661122a8 mount: code shrink
function                                             old     new   delta
append_mount_options                                 174     157     -17

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-08-23 02:31:26 +02:00
Denys Vlasenko dbdf9e0ab1 mount: with -w, do not fall back to read-only mounts
function                                             old     new   delta
mount_it_now                                         364     358      -6

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-08-23 02:30:13 +02:00
Ron Yorston 922b58b3e4 tar,smemcap: silence compiler warning
gcc 11.2.1 complains that the tar header checksum might overflow
the checksum field.  It won't and using an unsigned int for the
calculation seems to convince the compiler too.

Signed-off-by: Ron Yorston <rmy@pobox.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-08-22 15:44:57 +02:00
Denys Vlasenko 1e7ca18591 Regularize "NUL terminated input" --help texts
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-08-22 15:43:29 +02:00
Ron Yorston 8817e285b7 shuf: speed-up when limited output is requested
A user noted that the following command was slower than they
expected:

   busybox shuf -i "1500000000-$(date +%s)" -n 5

At time of writing the range contains 128 million values.  On my
system this takes 7.7s whereas 'shuf' from coreutils takes a
handful of milliseconds.

Optimise BusyBox 'shuf' for cases where -n is specified by stopping
shuffling once the required number of lines have been processed.
On my system the time for the example is reduced to 0.4s.

function                                             old     new   delta
shuf_main                                            520     540     +20
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 1/0 up/down: 20/0)               Total: 20 bytes

v2: Code shrink.  Since outlines <= numlines:
    - the loop in shuffle_lines() only needs to test the value of
      outlines;
    - shuffle_lines() can be called unconditionally.
    Update timing to allow for the 13 million seconds elapsed since v1.

Signed-off-by: Ron Yorston <rmy@pobox.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-08-22 15:40:21 +02:00
Ron Yorston 74c4f356ae vi: code shrink print_literal()
Simplify the function print_literal() which is used to format a
string that may contain unprintable characters or control
characters.

- Unprintable characters were being displayed in normal text rather
  than the bold used for the rest of the message.  This doesn't seem
  particularly helpful and it upsets the calculation of the width
  of the message in show_status_line().  Use '?' rather than '.' for
  unprintable characters.

- Newlines in the string were displayed as both '^J' and '$', which
  is somewhat redundant.

function                                             old     new   delta
not_implemented                                      199     108     -91
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 0/1 up/down: 0/-91)             Total: -91 bytes

Signed-off-by: Ron Yorston <rmy@pobox.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-08-22 00:09:57 +02:00
Ron Yorston 08ad934ac4 vi: searches in colon commands should wrap
The '/' and '?' search commands wrap to the other end of the buffer
if the search target isn't found.  When searches are used to specify
addresses in colon commands they should do the same.

(In traditional vi and vim this behaviour is controlled by the
'wrapscan' option.  BusyBox vi doesn't have this option and always
uses the default behaviour.)

function                                             old     new   delta
colon                                               4033    4077     +44
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 1/0 up/down: 44/0)               Total: 44 bytes

Signed-off-by: Ron Yorston <rmy@pobox.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-08-22 00:09:57 +02:00
Ron Yorston 4357569fdc rev: correct output for long input lines
The input buffer is initialised to a reasonable size and extended
if necessary.  When this happened the offset into the buffer wasn't
reset to zero so subsequent lines were appended to the long line.

Fix this and add some tests.

function                                             old     new   delta
rev_main                                             377     368      -9
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 0/1 up/down: 0/-9)               Total: -9 bytes

Signed-off-by: Ron Yorston <rmy@pobox.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-08-22 00:08:18 +02:00
Denys Vlasenko 62d5a1e56f tar,smemcap: commonalyze checksumming code for tar header
function                                             old     new   delta
chksum_and_xwrite_tar_header                           -      99     +99
writeheader                                          280     199     -81
chksum_and_xwrite                                    102       -    -102
------------------------------------------------------------------------------
(add/remove: 2/1 grow/shrink: 0/1 up/down: 99/-183)           Total: -84 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-08-20 17:58:49 +02:00
Ron Yorston 38e9c8c95b vi: don't right shift empty lines
The right shift command ('>') shouldn't affect empty lines.

function                                             old     new   delta
do_cmd                                              4860    4894     +34
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 1/0 up/down: 34/0)               Total: 34 bytes

Signed-off-by: Ron Yorston <rmy@pobox.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-08-20 15:26:09 +02:00
Ron Yorston f9217cd235 vi: support ~/.exrc
Run initialisation commands from ~/.exrc.  As with EXINIT these
commands are processed before the first file is loaded.

Commands starting with double quotes are ignored.  This is how
comments are often included in .exrc.

function                                             old     new   delta
vi_main                                              268     406    +138
colon                                               4033    4071     +38
.rodata                                           108411  108442     +31
packed_usage                                       34128   34118     -10
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 3/1 up/down: 207/-10)           Total: 197 bytes

Signed-off-by: Ron Yorston <rmy@pobox.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-08-20 15:26:09 +02:00
Ron Yorston f07772f19e vi: changes to handling of -c and EXINIT
Rewrite handling of command line arguments so any number of -c
commands will be processed.  Previously only two -c commands
were allowed (or one if EXINIT was set).

Process commands from EXINIT before the first file is read into
memory, as specified by POSIX.

function                                             old     new   delta
run_cmds                                               -      77     +77
.rodata                                           108410  108411      +1
vi_main                                              305     268     -37
edit_file                                            816     764     -52
------------------------------------------------------------------------------
(add/remove: 1/0 grow/shrink: 1/2 up/down: 78/-89)            Total: -11 bytes

Signed-off-by: Ron Yorston <rmy@pobox.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-08-20 15:26:09 +02:00
Denys Vlasenko 29b53ef03f udhcp: fix build breakage on MIPS
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-08-20 13:38:16 +02:00
Denys Vlasenko 9d286a0a55 Start 1.35.0 development cycle
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-08-19 15:06:57 +02:00
160 changed files with 3887 additions and 2577 deletions

No files matched your search

+1 -1
View File
@@ -1,5 +1,5 @@
VERSION = 1
PATCHLEVEL = 34
PATCHLEVEL = 35
SUBLEVEL = 0
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) -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)
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)
ifeq ($(CRYPT_AVAILABLE),y)
LDLIBS += crypt
endif
+2 -1
View File
@@ -196,9 +196,10 @@ static int write_ar_archive(archive_handle_t *handle)
static void FAST_FUNC header_verbose_list_ar(const file_header_t *file_header)
{
const char *mode = bb_mode_string(file_header->mode);
char mode[12];
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
@@ -0,0 +1,35 @@
/*
* 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));
}
+53 -1
View File
@@ -38,6 +38,20 @@
//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))
@@ -74,7 +88,13 @@
//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 Input is separated by NULs"
//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: )
/* GNU cpio 2.9 --help (abridged):
@@ -162,17 +182,22 @@ 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);
@@ -206,6 +231,9 @@ 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;
@@ -260,6 +288,10 @@ 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;
}
@@ -278,6 +310,11 @@ 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) {
@@ -285,6 +322,10 @@ 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)
@@ -304,6 +345,11 @@ 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 */
@@ -379,6 +425,12 @@ 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
static NOINLINE
void fallbackQSort3(uint32_t* fmap,
uint32_t* eclass,
int32_t loSt,
+3 -4
View File
@@ -99,9 +99,8 @@ 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));
s->crc32table = crc32_filltable(NULL, 1);
crc32_filltable(s->crc32table, 1);
s->state = BZ_S_INPUT;
s->mode = BZ_M_RUNNING;
@@ -369,8 +368,8 @@ void BZ2_bzCompressEnd(bz_stream *strm)
s = strm->state;
free(s->arr1);
free(s->arr2);
free(s->ftab);
free(s->crc32table);
//free(s->ftab); // made it array member of s
//free(s->crc32table); // ditto
free(s);
}
+7 -4
View File
@@ -134,7 +134,7 @@ typedef struct EState {
/* for doing the block sorting */
uint32_t *arr1;
uint32_t *arr2;
uint32_t *ftab;
//uint32_t *ftab; //moved into this struct, see below
uint16_t *quadrant;
int32_t budget;
@@ -160,9 +160,6 @@ typedef struct EState {
uint32_t bsBuff;
int32_t bsLive;
/* guess what */
uint32_t *crc32table;
/* block and combined CRCs */
uint32_t blockCRC;
uint32_t combinedCRC;
@@ -185,6 +182,12 @@ 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];
+5 -1
View File
@@ -92,8 +92,12 @@ 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));
typed->mode = read_num(ar.formatted.mode, 8, sizeof(ar.formatted.mode)) | S_IFREG;
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));
+9 -3
View File
@@ -147,6 +147,12 @@ 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;
@@ -331,8 +337,6 @@ 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 */
@@ -341,7 +345,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.
@@ -390,6 +394,7 @@ 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);
@@ -400,6 +405,7 @@ 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;
+3 -2
View File
@@ -9,6 +9,7 @@ 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];
@@ -29,7 +30,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(file_header->mode),
bb_mode_string(modestr, file_header->mode),
user,
group,
file_header->size,
@@ -46,7 +47,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(file_header->mode),
bb_mode_string(modestr, 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 enum xz_ret XZ_FUNC dec_main(struct xz_dec *s, struct xz_buf *b)
static NOINLINE enum xz_ret XZ_FUNC dec_main(struct xz_dec *s, struct xz_buf *b)
{
enum xz_ret ret;
+2 -29
View File
@@ -254,32 +254,6 @@ 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)
{
@@ -310,7 +284,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(fd, &header);
chksum_and_xwrite_tar_header(fd, &header);
/* Write filename[/] and pad the block. */
/* dir=0: writes 'name<NUL>', pads */
@@ -441,8 +415,7 @@ static int writeTarHeader(struct TarBallInfo *tbInfo,
header_name, S_ISDIR(statbuf->st_mode));
# endif
/* Now write the header out to disk */
chksum_and_xwrite(tbInfo->tarFd, &header);
chksum_and_xwrite_tar_header(tbInfo->tarFd, &header);
/* Now do the verbose thing (or not) */
if (tbInfo->verboseFlag) {
+13 -1
View File
@@ -74,7 +74,19 @@ int resize_main(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
+ (1 << SIGTERM)
+ (1 << SIGALRM)
, onintr);
tcsetattr(STDERR_FILENO, TCSANOW, &new);
/* 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);
/* save_cursor_pos 7
* scroll_whole_screen [r
+15 -4
View File
@@ -5,10 +5,6 @@
menu "Coreutils"
INSERT
comment "Common options"
config FEATURE_VERBOSE
bool "Support verbose options (usually -v) for various applets"
default y
@@ -17,6 +13,19 @@ 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
@@ -37,4 +46,6 @@ config FEATURE_HUMAN_READABLE
help
Allow df, du, and ls to have human readable output.
INSERT
endmenu
+38 -24
View File
@@ -29,9 +29,11 @@
/* http://www.opengroup.org/onlinepubs/007904975/utilities/basename.html */
//usage:#define basename_trivial_usage
//usage: "FILE [SUFFIX]"
//usage: "FILE [SUFFIX] | -a FILE... | -s SUFFIX FILE..."
//usage:#define basename_full_usage "\n\n"
//usage: "Strip directory path and .SUFFIX from FILE"
//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:
//usage:#define basename_example_usage
//usage: "$ basename /usr/local/bin/foo\n"
@@ -48,31 +50,43 @@
int basename_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
int basename_main(int argc UNUSED_PARAM, char **argv)
{
size_t m, n;
char *s;
unsigned opts;
const char *suffix = NULL;
if (argv[1] && strcmp(argv[1], "--") == 0) {
argv++;
}
if (!argv[1])
bb_show_usage();
/* '+': stop at first non-option */
opts = getopt32(argv, "^+" "as:"
"\0" "-1" /* At least one argument */
, &suffix
);
argv += optind;
/* It should strip slash: /abc/def/ -> def */
s = bb_get_last_path_component_strip(*++argv);
do {
char *s;
size_t m;
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 */
/* 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();
}
}
}
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);
/* 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;
return EXIT_SUCCESS;
}
+4 -2
View File
@@ -88,10 +88,12 @@ static int FAST_FUNC fileAction(struct recursive_state *state,
if (chmod(fileName, newmode) == 0) {
if (OPT_VERBOSE
|| (OPT_CHANGED && statbuf->st_mode != newmode)
|| (OPT_CHANGED
&& (statbuf->st_mode & 07777) != (newmode & 07777))
) {
char modestr[12];
printf("mode of '%s' changed to %04o (%s)\n", fileName,
newmode & 07777, bb_mode_string(newmode)+1);
newmode & 07777, bb_mode_string(modestr, newmode)+1);
}
return TRUE;
}
+4 -3
View File
@@ -266,6 +266,7 @@ 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;
@@ -276,12 +277,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 {
parse_datestr(date_str, &tm_time);
check_dst = 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 time_t format) */
if (date_str[0] != '@')
/* Be sure to recheck dst (but not if date is UTC) */
if (check_dst)
tm_time.tm_isdst = -1;
ts.tv_sec = validate_tm_time(date_str, &tm_time);
ts.tv_nsec = 0;
+35 -11
View File
@@ -32,6 +32,26 @@
//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))
@@ -99,15 +119,16 @@ 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_MEGA = (1 << (5 + 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_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,
};
const char *disp_units_hdr = NULL;
char *chp, *opt_t;
@@ -124,7 +145,7 @@ int df_main(int argc UNUSED_PARAM, char **argv)
opt = getopt32(argv, "^"
"kPTt:"
IF_FEATURE_DF_FANCY("aiB:")
IF_FEATURE_HUMAN_READABLE("hm")
IF_FEATURE_HUMAN_READABLE("hHm")
"\0"
#if ENABLE_FEATURE_HUMAN_READABLE && ENABLE_FEATURE_DF_FANCY
"k-mB:m-Bk:B-km"
@@ -151,8 +172,11 @@ int df_main(int argc UNUSED_PARAM, char **argv)
got_it: ;
}
if (opt & OPT_HUMAN) {
if (opt & (OPT_HUMAN|OPT_HUMANDEC)) {
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)
+2 -1
View File
@@ -503,7 +503,8 @@ 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 */
column += printf("%-10s ", (char *) bb_mode_string(dn->dn_mode));
char modestr[12];
column += printf("%-10s ", bb_mode_string(modestr, dn->dn_mode));
/* long listing: show number of links */
column += printf("%4lu ", (long) dn->dn_nlink);
/* long listing: show user/group */
+15 -1
View File
@@ -72,13 +72,27 @@ 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) {
@@ -95,7 +109,7 @@ int mktemp_main(int argc UNUSED_PARAM, char **argv)
goto error;
}
#endif
if (opts & (OPT_t|OPT_p))
if (opts & (OPT_t|OPT_p|OPT_tmpdir))
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;
}
if (*f && strchr("-+ #", *f)) {
while (*f && strchr("-+ #0", *f)) {
++f;
++direc_length;
}
+58 -39
View File
@@ -17,14 +17,14 @@
//kbuild:lib-$(CONFIG_SHUF) += shuf.o
//usage:#define shuf_trivial_usage
//usage: "[-e|-i L-H] [-n NUM] [-o FILE] [-z] [FILE|ARG...]"
//usage: "[-n NUM] [-o FILE] [-z] [FILE | -e [ARG...] | -i L-H]"
//usage:#define shuf_full_usage "\n\n"
//usage: "Randomly permute lines\n"
//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"
//usage: "\n -z NUL terminated output"
//usage: "\n -e Treat ARGs as lines"
//usage: "\n -i L-H Treat numbers L-H as lines"
#include "libbb.h"
@@ -39,24 +39,30 @@
/*
* 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)
static void shuffle_lines(char **lines, unsigned numlines, unsigned outlines)
{
unsigned i;
unsigned r;
char *tmp;
srand(monotonic_us());
for (i = numlines-1; i > 0; i--) {
r = rand();
while (outlines != 0) {
char *tmp;
unsigned r = rand();
/* RAND_MAX can be as small as 32767 */
if (i > RAND_MAX)
if (numlines > RAND_MAX)
r ^= rand() << 15;
r %= i + 1;
tmp = lines[i];
lines[i] = lines[r];
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];
lines[r] = tmp;
outlines--;
}
}
@@ -65,9 +71,10 @@ int shuf_main(int argc, char **argv)
{
unsigned opts;
char *opt_i_str, *opt_n_str, *opt_o_str;
unsigned i;
char **lines;
unsigned numlines;
unsigned long long lo = lo;
unsigned numlines, outlines;
unsigned i;
char eol;
opts = getopt32(argv, "^"
@@ -87,35 +94,48 @@ int shuf_main(int argc, char **argv)
} else
if (opts & OPT_i) {
/* create a range of numbers */
unsigned long long hi;
char *dash;
unsigned lo, hi;
if (argv[0])
bb_show_usage();
dash = strchr(opt_i_str, '-');
if (!dash) {
bb_error_msg_and_die("bad range '%s'", opt_i_str);
}
*dash = '\0';
lo = xatou(opt_i_str);
hi = xatou(dash + 1);
lo = xatoull(opt_i_str);
hi = xatoull(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) - lo;
lines = xmalloc(numlines * sizeof(lines[0]));
numlines = hi + 1;
lines = xmalloc((size_t)numlines * sizeof(lines[0]));
for (i = 0; i < numlines; i++) {
lines[i] = (char*)(uintptr_t)lo;
lo++;
lines[i] = (char*)(uintptr_t)i;
}
} else {
/* default - read lines from stdin or the input file */
FILE *fp;
const char *fname = "-";
if (argc > 1)
bb_show_usage();
if (argv[0]) {
if (argv[1])
bb_show_usage();
fname = argv[0];
}
fp = xfopen_stdin(argv[0] ? argv[0] : "-");
fp = xfopen_stdin(fname);
lines = NULL;
numlines = 0;
for (;;) {
@@ -128,26 +148,25 @@ int shuf_main(int argc, char **argv)
fclose_if_not_stdin(fp);
}
if (numlines != 0)
shuffle_lines(lines, numlines);
outlines = numlines;
if (opts & OPT_n) {
outlines = xatou(opt_n_str);
if (outlines > numlines)
outlines = numlines;
}
shuffle_lines(lines, numlines, outlines);
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 = 0; i < numlines; i++) {
for (i = numlines - outlines; i < numlines; i++) {
if (opts & OPT_i)
printf("%u%c", (unsigned)(uintptr_t)lines[i], eol);
printf("%llu%c", lo + (uintptr_t)lines[i], eol);
else
printf("%s%c", lines[i], eol);
}
+4 -2
View File
@@ -339,7 +339,8 @@ 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') {
printfs(pformat, bb_mode_string(statbuf->st_mode));
char modestr[12];
printfs(pformat, bb_mode_string(modestr, statbuf->st_mode));
} else if (m == 'f') {
strcat(pformat, "lx");
printf(pformat, (unsigned long) statbuf->st_mode);
@@ -702,6 +703,7 @@ 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;
@@ -736,7 +738,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(statbuf.st_mode),
bb_mode_string(modestr, statbuf.st_mode),
(unsigned long) statbuf.st_uid,
(pw_ent != NULL) ? pw_ent->pw_name : "UNKNOWN",
(unsigned long) statbuf.st_gid,
+2 -3
View File
@@ -435,7 +435,7 @@ struct test_statics {
};
/* See test_ptr_hack.c */
extern struct test_statics *const test_ptr_to_statics;
extern struct test_statics *BB_GLOBAL_CONST test_ptr_to_statics;
#define S (*test_ptr_to_statics)
#define args (S.args )
@@ -446,8 +446,7 @@ extern struct test_statics *const test_ptr_to_statics;
#define leaving (S.leaving )
#define INIT_S() do { \
(*(struct test_statics**)not_const_pp(&test_ptr_to_statics)) = xzalloc(sizeof(S)); \
barrier(); \
XZALLOC_CONST_PTR(&test_ptr_to_statics, sizeof(S)); \
} while (0)
#define DEINIT_S() do { \
free(group_array); \
+33 -12
View File
@@ -39,13 +39,29 @@
//kbuild:lib-$(CONFIG_TIMEOUT) += timeout.o
//usage:#define timeout_trivial_usage
//usage: "[-s SIG] SECS PROG ARGS"
//usage: "[-s SIG] [-k KILL_SECS] 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)
{
@@ -53,23 +69,29 @@ 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:" USE_FOR_NOMMU("p:+"), &opt_s, &parent);
getopt32(argv, "+s:k:" USE_FOR_NOMMU("p:+"), &opt_s, &opt_k, &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++]);
@@ -103,17 +125,16 @@ int timeout_main(int argc UNUSED_PARAM, char **argv)
bb_daemonize_or_rexec(0, argv);
/* Here we are grandchild. Sleep, then kill grandparent */
grandchild:
/* 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;
}
}
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)
return EXIT_SUCCESS;
kill(parent, SIGKILL);
}
return EXIT_SUCCESS;
}
+4 -2
View File
@@ -140,15 +140,17 @@ 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);
parse_datestr(date_str, &tm_time);
check_dst = parse_datestr(date_str, &tm_time);
/* Correct any day of week and day of year etc. fields */
tm_time.tm_isdst = -1; /* Be sure to recheck dst */
if (check_dst)
tm_time.tm_isdst = -1; /* recheck dst unless date is UTC */
t = validate_tm_time(date_str, &tm_time);
timebuf[1].tv_sec = timebuf[0].tv_sec = t;
+10 -1
View File
@@ -155,7 +155,16 @@ int uudecode_main(int argc UNUSED_PARAM, char **argv)
break;
}
dst_stream = stdout;
if (NOT_LONE_DASH(outname)) {
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)
) {
dst_stream = xfopen_for_write(outname);
fchmod(fileno(dst_stream), mode & (S_IRWXU | S_IRWXG | S_IRWXO));
}
+3 -2
View File
@@ -17,9 +17,10 @@
//kbuild:lib-$(CONFIG_WHICH) += which.o
//usage:#define which_trivial_usage
//usage: "COMMAND..."
//usage: "[-a] COMMAND..."
//usage:#define which_full_usage "\n\n"
//usage: "Locate COMMAND"
//usage: "Locate COMMAND\n"
//usage: "\n -a Show all matches"
//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 | no | no |
-o outfile | yes | no |
uudecode Busybox specific options: None
uuencode POSIX options
+36 -16
View File
@@ -2338,36 +2338,55 @@ static char *awk_printf(node *n, size_t *len)
b = NULL;
i = 0;
while (*f) { /* "print one format spec" loop */
while (1) { /* "print one format spec" loop */
char *s;
char c;
char sv;
var *arg;
size_t slen;
/* Find end of the next format spec, or end of line */
s = f;
while (*f && (*f != '%' || *++f == '%'))
f++;
while (*f && !isalpha(*f)) {
if (*f == '*')
syntax_error("%*x formats are not supported");
while (1) {
c = *f;
if (!c) /* no percent chars found at all */
goto nul;
f++;
if (c == '%')
break;
}
/* we are past % in "....%..." */
c = *f;
if (!c) {
/* Tail of fmt with no percent chars,
* or "....%" (percent seen, but no format specifier char found)
*/
slen = strlen(s);
goto tail;
if (!c) /* "....%" */
goto nul;
if (c == '%') { /* "....%%...." */
slen = f - s;
s = xstrndup(s, slen);
f++;
goto append; /* print "....%" part verbatim */
}
sv = *++f;
*f = '\0';
while (1) {
if (isalpha(c))
break;
if (c == '*')
syntax_error("%*x formats are not supported");
c = *++f;
if (!c) { /* "....%...." and no letter found after % */
/* Example: awk 'BEGIN { printf "^^^%^^^\n"; }' */
nul:
slen = f - s;
goto tail; /* print remaining string, exit loop */
}
}
/* we are at A in "....%...A..." */
arg = evaluate(nextarg(&n), TMPVAR);
/* Result can be arbitrarily long. Example:
* printf "%99999s", "BOOM"
*/
sv = *++f;
*f = '\0';
if (c == 'c') {
char cc = is_numeric(arg) ? getvar_i(arg) : *getvar_s(arg);
char *r = xasprintf(s, cc ? cc : '^' /* else strlen will be wrong */);
@@ -2386,13 +2405,14 @@ static char *awk_printf(node *n, size_t *len)
} else if (strchr("eEfFgGaA", c)) {
s = xasprintf(s, d);
} else {
//TODO: GNU Awk 5.0.1: printf "%W" prints "%W", does not error out
syntax_error(EMSG_INV_FMT);
}
}
slen = strlen(s);
}
*f = sv;
append:
if (i == 0) {
b = s;
i = slen;
@@ -2402,7 +2422,7 @@ static char *awk_printf(node *n, size_t *len)
b = xrealloc(b, i + slen + 1);
strcpy(b + i, s);
i += slen;
if (!c) /* tail? */
if (!c) /* s is NOT allocated and this is the last part of string? */
break;
free(s);
}
+9 -3
View File
@@ -18,12 +18,13 @@
//kbuild:lib-$(CONFIG_CMP) += cmp.o
//usage:#define cmp_trivial_usage
//usage: "[-ls] FILE1 [FILE2" IF_DESKTOP(" [SKIP1 [SKIP2]]") "]"
//usage: "[-ls] [-n NUM] 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 */
@@ -35,9 +36,10 @@ 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 "sl"
#define OPT_STR "sln:+"
#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)
@@ -50,13 +52,15 @@ 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"
":l--s:s--l",
&max_count
);
argv += optind;
@@ -95,6 +99,8 @@ 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;
+28 -23
View File
@@ -18,7 +18,7 @@
//applet:IF_ED(APPLET(ed, BB_DIR_BIN, BB_SUID_DROP))
//usage:#define ed_trivial_usage "[FILE]"
//usage:#define ed_trivial_usage "[-p PROMPT] [FILE]"
//usage:#define ed_full_usage ""
#include "libbb.h"
@@ -48,6 +48,7 @@ struct globals {
char *bufBase;
char *bufPtr;
char *fileName;
const char *prompt;
LINE lines;
smallint dirty;
int marks[26];
@@ -57,6 +58,7 @@ 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 )
@@ -380,7 +382,8 @@ static void addLines(int num)
static int readLines(const char *file, int num)
{
int fd, cc;
int len, lineCount, charCount;
int len;
unsigned charCount;
char *cp;
if ((num < 1) || (num > lastNum + 1)) {
@@ -396,13 +399,9 @@ 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);
@@ -415,7 +414,6 @@ static int readLines(const char *file, int num)
bufPtr += len;
bufUsed -= len;
charCount += len;
lineCount++;
num++;
continue;
}
@@ -449,15 +447,18 @@ static int readLines(const char *file, int num)
close(fd);
return -1;
}
lineCount++;
charCount += bufUsed;
}
close(fd);
printf("%d lines%s, %d chars\n", lineCount,
(bufUsed ? " (incomplete)" : ""), charCount);
/* 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);
return TRUE;
}
@@ -468,12 +469,12 @@ static int readLines(const char *file, int num)
static int writeLines(const char *file, int num1, int num2)
{
LINE *lp;
int fd, lineCount, charCount;
int fd;
unsigned charCount;
if (bad_nums(num1, num2, "write"))
return FALSE;
lineCount = 0;
charCount = 0;
fd = creat(file, 0666);
@@ -482,9 +483,6 @@ 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);
@@ -498,7 +496,6 @@ static int writeLines(const char *file, int num1, int num2)
return FALSE;
}
charCount += lp->len;
lineCount++;
lp = lp->next;
}
@@ -507,7 +504,13 @@ static int writeLines(const char *file, int num1, int num2)
return FALSE;
}
printf("%d lines, %d chars\n", lineCount, charCount);
/* 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);
return TRUE;
}
@@ -789,7 +792,7 @@ static void doCommands(void)
* 0 on ctrl-C,
* >0 length of input string, including terminating '\n'
*/
len = read_line_input(NULL, ": ", buf, sizeof(buf));
len = read_line_input(NULL, prompt, buf, sizeof(buf));
if (len <= 0)
return;
while (len && isspace(buf[--len]))
@@ -1001,13 +1004,15 @@ int ed_main(int argc UNUSED_PARAM, char **argv)
lines.next = &lines;
lines.prev = &lines;
if (argv[1]) {
fileName = xstrdup(argv[1]);
prompt = ""; /* no prompt by default */
getopt32(argv, "p:", &prompt);
argv += optind;
if (argv[0]) {
fileName = xstrdup(argv[0]);
if (!readLines(fileName, 1)) {
return EXIT_SUCCESS;
}
if (lastNum)
setCurNum(1);
dirty = FALSE;
}
+1 -2
View File
@@ -435,8 +435,7 @@ static int parse_subst_cmd(sed_cmd_t *sed_cmd, const char *substr)
switch (substr[idx]) {
/* Replace all occurrences */
case 'g':
if (match[0] != '^')
sed_cmd->which_match = 0;
sed_cmd->which_match = 0;
break;
/* Print pattern space */
case 'p':
+189 -133
View File
@@ -7,7 +7,7 @@
*/
//
//Things To Do:
// $HOME/.exrc and ./.exrc
// ./.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 also available)"
//usage: "\n -c CMD Initial command to run ($EXINIT and ~/.exrc also available)"
//usage: )
//usage: IF_FEATURE_VI_READONLY(
//usage: "\n -R Read-only"
@@ -201,6 +201,7 @@
// 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
@@ -403,7 +404,7 @@ struct globals {
int cindex; // saved character index for up/down motion
smallint keep_index; // retain saved character index
#if ENABLE_FEATURE_VI_COLON
char *initial_cmds[3]; // currently 2 entries, NULL terminated
llist_t *initial_cmds;
#endif
// Should be just enough to hold a key sequence,
// but CRASHME mode uses it as generated command buffer too
@@ -1376,21 +1377,14 @@ 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;
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 & 0x80) && !Isprint(c))
c = '?';
if (c < ' ' || c == 0x7f) {
*d++ = '^';
c |= '@'; // 0x40
@@ -1399,14 +1393,6 @@ 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;
}
@@ -2472,26 +2458,38 @@ static char *char_search(char *p, const char *pat, int dir_and_range)
//----- The Colon commands -------------------------------------
#if ENABLE_FEATURE_VI_COLON
static char *get_one_address(char *p, int *result) // get colon addr, if present
// 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)
{
int st, num, sign, addr, new_addr;
int num, sign, addr, got_addr;
# if ENABLE_FEATURE_VI_YANKMARK || ENABLE_FEATURE_VI_SEARCH
char *q, c;
# endif
IF_FEATURE_VI_SEARCH(int dir;)
addr = -1; // assume no addr
got_addr = FALSE;
addr = count_lines(text, dot); // default to current line
sign = 0;
for (;;) {
new_addr = -1;
if (isblank(*p)) {
if (got_addr) {
addr += sign;
sign = 0;
}
p++;
} else if (*p == '.') { // the current line
} else if (!got_addr && *p == '.') { // the current line
p++;
new_addr = count_lines(text, dot);
//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;
}
# if ENABLE_FEATURE_VI_YANKMARK
else if (*p == '\'') { // is this a mark addr
else if (!got_addr && *p == '\'') { // is this a mark addr
p++;
c = tolower(*p);
p++;
@@ -2501,13 +2499,16 @@ static char *get_one_address(char *p, int *result) // get colon addr, if present
c = c - 'a';
q = mark[(unsigned char) c];
}
if (q == NULL) // is mark valid
if (q == NULL) { // is mark valid
status_line_bold("Mark not set");
return NULL;
new_addr = count_lines(text, q);
}
addr = count_lines(text, q);
got_addr = TRUE;
}
# endif
# if ENABLE_FEATURE_VI_SEARCH
else if (*p == '/' || *p == '?') { // a search pattern
else if (!got_addr && (*p == '/' || *p == '?')) { // a search pattern
c = *p;
q = strchrnul(p + 1, c);
if (p + 1 != q) {
@@ -2526,39 +2527,45 @@ static char *get_one_address(char *p, int *result) // get colon addr, if present
dir = ((unsigned)BACK << 1) | FULL;
}
q = char_search(q, last_search_pattern + 1, dir);
if (q == NULL)
return NULL;
new_addr = count_lines(text, q);
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;
}
# endif
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
else if (isdigit(*p)) {
num = 0;
while (isdigit(*p))
num = num * 10 + *p++ -'0';
if (!got_addr) { // specific line number
addr = num;
got_addr = TRUE;
} else { // offset from current addr
addr += sign >= 0 ? num : -num;
}
sign = 0;
} else if (*p == '-' || *p == '+') {
sign = *p++ == '-' ? -1 : 1;
if (addr < 0) { // default address is dot
addr = count_lines(text, dot);
if (!got_addr) { // default address is dot
//addr = count_lines(text, dot);
got_addr = TRUE;
} else {
addr += sign;
}
sign = *p++ == '-' ? -1 : 1;
} 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;
}
@@ -2567,34 +2574,40 @@ static char *get_one_address(char *p, int *result) // get colon addr, if present
// 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)
static char *get_address(char *p, int *b, int *e, unsigned int *got)
{
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 (*p == '%' && state == GET_ADDRESS) { // alias for 1,$
} else if (state == GET_ADDRESS && *p == '%') { // 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;
}
}
@@ -2808,9 +2821,14 @@ 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
@@ -2828,21 +2846,22 @@ static void colon(char *buf)
// :!<cmd> // run <cmd> then return
//
if (!buf[0])
goto ret;
if (*buf == ':')
buf++; // move past the ':'
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 '"'
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 :%
buf1 = buf;
buf = get_address(buf, &b, &e);
buf = get_address(buf, &b, &e, &got);
if (buf == NULL) {
status_line_bold("Bad address: %s", buf1);
goto ret;
}
@@ -2865,13 +2884,17 @@ static void colon(char *buf)
}
// assume the command will want a range, certain commands
// (read, substitute) need to adjust these assumptions
if (e < 0) {
if (!GOT_ADDRESS) {
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 (b < 0) {
if (!GOT_RANGE) {
// 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.
@@ -2880,6 +2903,10 @@ 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;
@@ -2910,12 +2937,12 @@ static void colon(char *buf)
}
# endif
else if (cmd[0] == '=' && !cmd[1]) { // where is the address
if (e < 0) { // no addr given- use defaults
if (!GOT_ADDRESS) { // no addr given- use defaults
e = count_lines(text, dot);
}
status_line("%d", e);
} else if (strncmp(cmd, "delete", i) == 0) { // delete lines
if (e < 0) { // no addr given- use defaults
if (!GOT_ADDRESS) { // no addr given- use defaults
q = begin_line(dot); // assume .,. for the range
r = end_line(dot);
}
@@ -2987,7 +3014,7 @@ static void colon(char *buf)
rawmode();
Hit_Return();
} else if (strncmp(cmd, "list", i) == 0) { // literal print line
if (e < 0) { // no addr given- use defaults
if (!GOT_ADDRESS) { // no addr given- use defaults
q = begin_line(dot); // assume .,. for the range
r = end_line(dot);
}
@@ -3070,7 +3097,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(e > 0 ? find_line(e) : dot);
q = next_line(GOT_ADDRESS ? find_line(e) : dot);
// read after last line
if (q == end-1)
++q;
@@ -3191,11 +3218,11 @@ static void colon(char *buf)
len_F = strlen(F);
}
if (e < 0) { // no addr given
if (!GOT_ADDRESS) { // 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 (b < 0) { // one addr given
} else if (!GOT_RANGE) { // one addr given
b = e;
}
@@ -3366,7 +3393,7 @@ static void colon(char *buf)
}
# if ENABLE_FEATURE_VI_YANKMARK
} else if (strncmp(cmd, "yank", i) == 0) { // yank lines
if (b < 0) { // no addr given- use defaults
if (!GOT_ADDRESS) { // no addr given- use defaults
q = begin_line(dot); // assume .,. for the range
r = end_line(dot);
}
@@ -4089,8 +4116,8 @@ static void do_cmd(int c)
#endif
}
}
} else /* if (c == '>') */ {
// shift right -- add tab or tabstop spaces
} else if (/* c == '>' && */ p != end_line(p)) {
// shift right -- add tab or tabstop spaces on non-empty lines
char_insert(p, '\t', allow_undo);
}
#if ENABLE_FEATURE_VI_UNDO
@@ -4708,6 +4735,21 @@ 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
@@ -4778,25 +4820,8 @@ static void edit_file(char *fn)
#endif
#if ENABLE_FEATURE_VI_COLON
{
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++;
}
}
while (initial_cmds)
run_cmds((char *)llist_pop(&initial_cmds));
#endif
redraw(FALSE); // dont force every col re-draw
//------This is the main Vi cmd handling loop -----------------------
@@ -4859,10 +4884,29 @@ 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 c;
int opts;
INIT_G();
@@ -4886,50 +4930,62 @@ int vi_main(int argc, char **argv)
// 0: all of our options are disabled by default in vim
//vi_setops = 0;
// 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
while ((c = getopt(argc, argv,
opts = getopt32(argv, VI_OPTSTR IF_FEATURE_VI_COLON(, &initial_cmds));
#if ENABLE_FEATURE_VI_CRASHME
"C"
if (opts & OPT_C)
crashme = 1;
#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;
}
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;
}
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
+12 -8
View File
@@ -179,7 +179,9 @@ ipt="iptables -t nat -A OUTPUT"
# OUTGOING TRAFFIC
ipt="iptables -t nat -A POSTROUTING"
# Masquerade boxes on my private net
doit $ipt -s 192.168.0.0/24 -o $extif -j MASQUERADE
for e in $extif; do
doit $ipt -s 192.168.0.0/24 -o $e -j MASQUERADE
done
# *** mangle ***
### DEBUG
@@ -204,7 +206,9 @@ 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"
doit $ipt -i $extif -j iext
for e in $extif; do
doit $ipt -i $e -j iext
done
echo; echo "* Enabling forwarding"
@@ -222,12 +226,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
+160 -22
View File
@@ -67,21 +67,53 @@
//config: interpreted by other programs.
//config:
//config:config FEATURE_FIND_MTIME
//config: bool "Enable -mtime: modified time matching"
//config: bool "Enable -mtime: modification 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: modified time matching by minutes"
//config: bool "Enable -mmin: modification 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
@@ -123,6 +155,13 @@
//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
@@ -296,16 +335,31 @@
//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: )
@@ -396,10 +450,11 @@ 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, char mtime_char; unsigned mtime_days;))
IF_FEATURE_FIND_MMIN( ACTS(mmin, char mmin_char; unsigned mmin_mins;))
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_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;))
@@ -618,30 +673,61 @@ 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)
{
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);
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);
}
#endif
#if ENABLE_FEATURE_FIND_MMIN
ACTF(mmin)
{
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);
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);
}
#endif
#if ENABLE_FEATURE_FIND_NEWER
@@ -656,6 +742,13 @@ 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)
{
@@ -1043,9 +1136,14 @@ 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 ,)
@@ -1087,9 +1185,14 @@ 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" )
@@ -1373,19 +1476,39 @@ static action*** parse_params(char **argv)
}
#endif
#if ENABLE_FEATURE_FIND_MTIME
else if (parm == PARM_mtime) {
else if (parm == PARM_mtime
# if ENABLE_FEATURE_FIND_ATIME
|| parm == PARM_atime
# endif
# if ENABLE_FEATURE_FIND_CTIME
|| parm == PARM_ctime
# endif
) {
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) {
else if (parm == PARM_mmin
# if ENABLE_FEATURE_FIND_AMIN
|| parm == PARM_amin
# endif
# if ENABLE_FEATURE_FIND_CMIN
|| parm == PARM_cmin
# endif
) {
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));
}
@@ -1408,6 +1531,21 @@ 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 Input is NUL terminated"
//usage: "\n -z NUL terminated input"
//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 Input is separated by NULs"
//usage: "\n -0 NUL terminated input"
//usage: )
//usage: IF_FEATURE_XARGS_SUPPORT_ARGS_FILE(
//usage: "\n -a FILE Read from FILE instead of stdin"
+1 -1
View File
@@ -167,6 +167,7 @@ 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[];
@@ -194,7 +195,6 @@ 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;
+54 -32
View File
@@ -305,9 +305,13 @@ typedef unsigned long long uoff_t;
# endif
#else
/* CONFIG_LFS is off */
# 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... */
/* 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
typedef unsigned long uoff_t;
# define XATOOFF(a) xatoi_positive(a)
# define BB_STRTOOFF bb_strtou
@@ -365,13 +369,27 @@ 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 *const bb_errno;
#undef errno
#define errno (*bb_errno)
#define bb_cached_errno_ptr 1
extern int *BB_GLOBAL_CONST bb_errno;
# undef errno
# define errno (*bb_errno)
# define bb_cached_errno_ptr 1
#endif
#if !(ULONG_MAX > 0xffffffff)
@@ -440,9 +458,8 @@ void *xmmap_anon(size_t size) FAST_FUNC;
# define cached_pagesize(var) (var)
#endif
//TODO: supply a pointer to char[11] buffer (avoid statics)?
extern const char *bb_mode_string(mode_t mode) FAST_FUNC;
/* Generate ls-style "mode string" like "-rwsr-xr-x" or "drwxrwxrwt" */
extern char *bb_mode_string(char buf[11], 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 */
@@ -561,7 +578,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(const char *path) FAST_FUNC RETURNS_MALLOC;
char *xmalloc_realpath_coreutils(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 */
@@ -690,7 +707,7 @@ struct BUG_too_small {
};
void parse_datestr(const char *date_str, struct tm *ptm) FAST_FUNC;
int 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;
@@ -1254,8 +1271,10 @@ 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
@@ -1483,16 +1502,8 @@ 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 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
;
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);
/* 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);
@@ -1607,7 +1618,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. current_mode is a base for e.g. "u+rw" */
/* Returns -1 if input is invalid. cur_mode is a base for e.g. "u+rw" */
int bb_parse_mode(const char* s, unsigned cur_mode) FAST_FUNC;
/*
@@ -2263,6 +2274,7 @@ 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;
@@ -2271,6 +2283,8 @@ 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.
@@ -2278,30 +2292,38 @@ 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;
}
#else
static ALWAYS_INLINE void* not_const_pp(const void *p) { return (void*)p; }
#endif
/* 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); \
# 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))
#endif
#define SET_PTR_TO_GLOBALS(x) ASSIGN_CONST_PTR(&ptr_to_globals, x)
#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,6 +239,7 @@ 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))
@@ -250,6 +251,7 @@ 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,6 +31,9 @@
# define ADJTIME_PATH "/etc/adjtime"
#endif
#define STR1(s) #s
#define STR(s) STR1(s)
INSERT
#define busybox_notes_usage \
+61 -113
View File
@@ -61,32 +61,73 @@ config SHA3_SMALL
64-bit x86: +270 bytes of code, 45% faster
32-bit x86: +450 bytes of code, 75% faster
config FEATURE_FAST_TOP
bool "Faster /proc scanning code (+100 bytes)"
default n # all "fast or small" options default to small
config FEATURE_NON_POSIX_CP
bool "Non-POSIX, but safer, copying to special nodes"
default y
help
This option makes top and ps ~20% faster (or 20% less CPU hungry),
but code size is slightly bigger.
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_ETC_NETWORKS
bool "Support /etc/networks"
config FEATURE_VERBOSE_CP_MESSAGE
bool "Give more precise messages when copy fails (cp, mv etc)"
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.
Error messages with this feature enabled:
config FEATURE_ETC_SERVICES
bool "Consult /etc/services even for well-known ports"
default n
$ 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
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.
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.
config FEATURE_EDITING
bool "Command line editing"
@@ -302,96 +343,3 @@ 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,6 +24,7 @@ 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
+14 -9
View File
@@ -247,8 +247,7 @@ void lbb_prepare(const char *applet
IF_FEATURE_INDIVIDUAL(, char **argv))
{
#ifdef bb_cached_errno_ptr
(*(int **)not_const_pp(&bb_errno)) = get_perrno();
barrier();
ASSIGN_CONST_PTR(&bb_errno, get_perrno());
#endif
applet_name = applet;
@@ -726,9 +725,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
exit(ash_main(-script - 1, argv));
return ash_main(-script - 1, argv);
# elif ENABLE_SHELL_HUSH
exit(hush_main(-script - 1, argv));
return hush_main(-script - 1, argv);
# else
return 1;
# endif
@@ -1005,10 +1004,10 @@ int scripted_main(int argc UNUSED_PARAM, char **argv)
{
# if ENABLE_SHELL_ASH
int script = 0;
exit(ash_main(-script - 1, argv));
return ash_main(-script - 1, argv);
# elif ENABLE_SHELL_HUSH
int script = 0;
exit(hush_main(-script - 1, argv));
return hush_main(-script - 1, argv);
# else
return 1;
# endif
@@ -1094,7 +1093,7 @@ int main(int argc UNUSED_PARAM, char **argv)
full_write2_str(bb_basename(argv[0]));
full_write2_str(": no applets enabled\n");
exit(127);
return 127;
#else
@@ -1113,8 +1112,14 @@ int main(int argc UNUSED_PARAM, char **argv)
|| ENABLE_FEATURE_PREFER_APPLETS
|| !BB_MMU
) {
if (NUM_APPLETS > 1)
set_task_comm(applet_name);
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);
}
}
parse_config_file(); /* ...maybe, if FEATURE_SUID_CONFIG */
+16
View File
@@ -0,0 +1,16 @@
/* 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 void display(priv_dumper_t* dumper)
static NOINLINE void display(priv_dumper_t* dumper)
{
unsigned char *bp;
unsigned char savech = '\0';
+66 -39
View File
@@ -135,10 +135,6 @@ 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;
@@ -161,12 +157,13 @@ struct lineedit_statics {
#if ENABLE_USERNAME_OR_HOMEDIR
char *user_buf;
char *home_pwd_buf; /* = (char*)null_str; */
char *home_pwd_buf;
smallint got_user_strings;
#endif
#if ENABLE_FEATURE_TAB_COMPLETION
char **matches;
unsigned num_matches;
char **matches;
#endif
#if ENABLE_FEATURE_EDITING_WINCH
@@ -192,7 +189,7 @@ struct lineedit_statics {
};
/* See lineedit_ptr_hack.c */
extern struct lineedit_statics *const lineedit_ptr_to_statics;
extern struct lineedit_statics *BB_GLOBAL_CONST lineedit_ptr_to_statics;
#define S (*lineedit_ptr_to_statics)
#define state (S.state )
@@ -207,15 +204,15 @@ extern struct lineedit_statics *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 matches (S.matches )
#define got_user_strings (S.got_user_strings)
#define num_matches (S.num_matches )
#define matches (S.matches )
#define delptr (S.delptr )
#define newdelflag (S.newdelflag )
#define delbuf (S.delbuf )
#define INIT_S() do { \
(*(struct lineedit_statics**)not_const_pp(&lineedit_ptr_to_statics)) = xzalloc(sizeof(S)); \
barrier(); \
XZALLOC_CONST_PTR(&lineedit_ptr_to_statics, sizeof(S)); \
} while (0)
static void deinit_S(void)
@@ -227,14 +224,47 @@ static void deinit_S(void)
#endif
#if ENABLE_USERNAME_OR_HOMEDIR
free(user_buf);
if (home_pwd_buf != null_str)
free(home_pwd_buf);
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)
{
@@ -692,11 +722,11 @@ static char *username_path_completion(char *ud)
{
struct passwd *entry;
char *tilde_name = ud;
char *home = NULL;
const char *home = NULL;
ud++; /* skip ~ */
if (*ud == '/') { /* "~/..." */
home = home_pwd_buf;
home = get_homedir_or_NULL();
} else {
/* "~user/..." */
ud = strchr(ud, '/');
@@ -1133,7 +1163,16 @@ static void showfiles(void)
static const char *is_special_char(char c)
{
return strchr(" `\"#$%^&*()=+{}[]:;'|\\<>", 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?
}
static char *quote_special_chars(char *found)
@@ -1753,7 +1792,7 @@ vi_back_motion(void)
input_backward(1);
}
}
#endif
#endif /* ENABLE_FEATURE_EDITING_VI */
/* Modelled after bash 4.0 behavior of Ctrl-<arrow> */
static void ctrl_left(void)
@@ -1854,7 +1893,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:
@@ -1963,7 +2002,7 @@ static void parse_and_put_prompt(const char *prmt_ptr)
switch (c) {
case 'u':
pbuf = user_buf ? user_buf : (char*)"";
pbuf = (char*)get_username_str();
break;
case 'H':
case 'h':
@@ -1985,14 +2024,15 @@ 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_pwd_buf[0]) {
else if ((home = get_homedir_or_NULL()) != NULL && home[0]) {
char *after_home_user;
/* /home/user[/something] -> ~[/something] */
after_home_user = is_prefixed_with(cwd_buf, home_pwd_buf);
after_home_user = is_prefixed_with(cwd_buf, home);
if (after_home_user
&& (*after_home_user == '/' || *after_home_user == '\0')
) {
@@ -2048,7 +2088,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 */
@@ -2059,9 +2099,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);
@@ -2288,7 +2328,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];
@@ -2299,7 +2339,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';
@@ -2351,7 +2391,7 @@ static int32_t reverse_i_search(int timeout)
return ic;
}
#endif
#endif /* ENABLE_FEATURE_REVERSE_SEARCH */
#if ENABLE_FEATURE_EDITING_WINCH
static void sigaction2(int sig, struct sigaction *act)
@@ -2391,7 +2431,6 @@ 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
@@ -2451,18 +2490,6 @@ 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]);
+12 -22
View File
@@ -16,16 +16,18 @@
#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,
@@ -33,19 +35,14 @@ 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";
const char* FAST_FUNC bb_mode_string(mode_t mode)
char* FAST_FUNC bb_mode_string(char buf[11], mode_t mode)
{
static char buf[12];
char *p = buf;
int i, j, k;
@@ -67,10 +64,7 @@ const char* FAST_FUNC bb_mode_string(mode_t mode)
i += 4;
} while (i < 12);
/* 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);
buf[10] = '\0';
return buf;
}
@@ -80,12 +74,11 @@ const char* FAST_FUNC bb_mode_string(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";
const char* FAST_FUNC bb_mode_string(mode_t mode)
char* FAST_FUNC bb_mode_string(char buf[11], mode_t mode)
{
static char buf[12];
char *p = buf;
int i, j, k, m;
@@ -109,10 +102,7 @@ const char* FAST_FUNC bb_mode_string(mode_t mode)
}
} while (i < 3);
/* 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);
buf[10] = '\0';
return buf;
}
+3 -2
View File
@@ -16,13 +16,14 @@
int FAST_FUNC bb_parse_mode(const char *s, unsigned current_mode)
{
static const mode_t who_mask[] = {
/* should be mode_t really, but in all Unixes these constants fit into uint16 */
static const uint16_t who_mask[] ALIGN2 = {
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 mode_t perm_mask[] = {
static const uint16_t perm_mask[] ALIGN2 = {
S_IRUSR | S_IRGRP | S_IROTH, /* r */
S_IWUSR | S_IWGRP | S_IWOTH, /* w */
S_IXUSR | S_IXGRP | S_IXOTH, /* x */
+14 -15
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;
//saltbits = 0; /* not needed: we call setup_salt() before do_des() */
bits28 = bits32 + 4;
bits24 = bits28 + 4;
@@ -481,12 +481,11 @@ 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 obit, saltbit;
int i;
uint32_t invbits;
#if USE_REPETITIVE_SPEEDUP
if (salt == old_salt)
@@ -494,15 +493,15 @@ setup_salt(struct des_ctx *ctx, uint32_t salt)
old_salt = salt;
#endif
saltbits = 0;
saltbit = 1;
obit = 0x800000;
for (i = 0; i < 24; i++) {
if (salt & saltbit)
saltbits |= obit;
saltbit <<= 1;
obit >>= 1;
}
invbits = 0;
salt |= (1 << 24);
do {
invbits = (invbits << 1) + (salt & 1);
salt >>= 1;
} while (salt != 1);
saltbits = invbits;
}
static void
@@ -736,14 +735,14 @@ des_crypt(struct des_ctx *ctx, char output[DES_OUT_BUFSIZE],
des_setkey(ctx, (char *)keybuf);
/*
* salt_str - 2 bytes of salt
* salt_str - 2 chars of salt (converted to 12 bits)
* 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);
setup_salt(ctx, salt); /* set ctx->saltbits for do_des() */
/* Do it. */
do_des(ctx, /*0, 0,*/ &r0, &r1, 25 /* count */);
+62 -15
View File
@@ -8,16 +8,68 @@
*/
#include "libbb.h"
void FAST_FUNC parse_datestr(const char *date_str, struct tm *ptm)
/* 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)
{
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",
@@ -50,14 +102,6 @@ void 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);
}
@@ -89,17 +133,19 @@ void 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 = localtime(&t);
struct tm *lt;
IF_FEATURE_TIMEZONE(localise:)
lt = localtime(&t);
if (lt) {
*ptm = *lt;
return;
return 0;
}
}
end = '1';
@@ -216,6 +262,7 @@ void 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,6 +28,22 @@
# 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) */
+7 -15
View File
@@ -115,27 +115,19 @@ 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 it isnt found return default_port
* If "port" is a name it is looked up in /etc/services.
* if NULL, return default_port
*/
unsigned FAST_FUNC bb_lookup_port(const char *port, const char *protocol, unsigned default_port)
unsigned FAST_FUNC bb_lookup_port(const char *port, const char *protocol, unsigned port_nr)
{
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);
port_nr = default_port;
if (tserv)
port_nr = ntohs(tserv->s_port);
//FIXME: else: port string was garbage, but we don't report that???
if (!tserv)
bb_error_msg_and_die("bad port '%s'", port);
port_nr = ntohs(tserv->s_port);
}
errno = old_errno;
}
return (uint16_t)port_nr;
}
@@ -239,7 +231,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 spec '%s'", org_host);
bb_error_msg("bad port '%s'", cp);
if (ai_flags & DIE_ON_ERROR)
xfunc_die();
return NULL;
+45 -30
View File
@@ -123,7 +123,7 @@ char* FAST_FUNC xmalloc_realpath(const char *path)
#endif
}
char* FAST_FUNC xmalloc_realpath_coreutils(const char *path)
char* FAST_FUNC xmalloc_realpath_coreutils(char *path)
{
char *buf;
@@ -137,32 +137,19 @@ char* FAST_FUNC xmalloc_realpath_coreutils(const char *path)
* (the directory must exist).
*/
if (!buf && errno == ENOENT) {
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;
}
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] != '/') {
/*
* $ ln -s target_does_not_exist symlink
* $ readlink -f symlink
@@ -170,13 +157,41 @@ char* FAST_FUNC xmalloc_realpath_coreutils(const char *path)
* $ realpath symlink
* /CURDIR/target_does_not_exist
*/
cwd = xrealloc_getcwd_or_warn(NULL);
buf = concat_path_file(cwd, target);
char *cwd = xrealloc_getcwd_or_warn(NULL);
char *tmp = concat_path_file(cwd, target);
free(cwd);
free(target);
return buf;
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);
}
}
path[i + 1] = c;
}
return buf;
+2 -2
View File
@@ -1,7 +1,5 @@
menu "Mail Utilities"
INSERT
config FEATURE_MIME_CHARSET
string "Default charset"
default "us-ascii"
@@ -9,4 +7,6 @@ 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 BC_STATUS zbc_num_sqrt(BcNum *a, BcNum *restrict b, size_t scale)
static NOINLINE BC_STATUS zbc_num_sqrt(BcNum *a, BcNum *restrict b, size_t scale)
{
BcStatus s;
BcNum num1, num2, half, f, fprime, *x0, *x1, *temp;
+34 -30
View File
@@ -201,6 +201,9 @@ int chat_main(int argc UNUSED_PARAM, char **argv)
DIR_RECORD,
};
#define inbuf bb_common_bufsiz1
setup_common_bufsiz();
// make x* functions fail with correct exitcode
xfunc_error_retval = ERR_IO;
@@ -361,35 +364,36 @@ int chat_main(int argc UNUSED_PARAM, char **argv)
// get reply
pfd.fd = STDIN_FILENO;
pfd.events = POLLIN;
while (!exitcode
while (exitcode == ERR_OK
&& poll(&pfd, 1, timeout) > 0
&& (pfd.revents & POLLIN)
/* && (pfd.revents & POLLIN) - may be untrue (e.g. only POLLERR set) */
) {
llist_t *l;
ssize_t delta;
#define buf bb_common_bufsiz1
setup_common_bufsiz();
// read next char from device
if (safe_read(STDIN_FILENO, buf+buf_len, 1) > 0) {
// dump device input if RECORD fname
if (record_fd > 0) {
full_write(record_fd, buf+buf_len, 1);
}
// dump device input if ECHO ON
if (echo) {
// if (buf[buf_len] < ' ') {
// full_write2_str("^");
// buf[buf_len] += '@';
// }
full_write(STDERR_FILENO, buf+buf_len, 1);
}
buf_len++;
// move input frame if we've reached higher bound
if (buf_len > COMMON_BUFSIZE) {
memmove(buf, buf+buf_len-max_len, max_len);
buf_len = max_len;
}
if (safe_read(STDIN_FILENO, inbuf + buf_len, 1) <= 0) {
exitcode = ERR_IO;
goto expect_done;
}
// dump device input if RECORD fname
if (record_fd > 0) {
full_write(record_fd, inbuf + buf_len, 1);
}
// dump device input if ECHO ON
if (echo) {
// if (inbuf[buf_len] < ' ') {
// full_write2_str("^");
// inbuf[buf_len] += '@';
// }
full_write(STDERR_FILENO, inbuf + buf_len, 1);
}
buf_len++;
// move input frame if we've reached higher bound
if (buf_len > COMMON_BUFSIZE) {
memmove(inbuf, inbuf + buf_len - max_len, max_len);
buf_len = max_len;
}
// N.B. rule of thumb: values being looked for can
// be found only at the end of input buffer
@@ -399,20 +403,20 @@ int chat_main(int argc UNUSED_PARAM, char **argv)
// abort condition is met? -> bail out
for (l = aborts, exitcode = ERR_ABORT; l; l = l->link, ++exitcode) {
size_t len = strlen(l->data);
delta = buf_len-len;
if (delta >= 0 && !memcmp(buf+delta, l->data, len))
delta = buf_len - len;
if (delta >= 0 && !memcmp(inbuf + delta, l->data, len))
goto expect_done;
}
exitcode = ERR_OK;
// expected reply received? -> goto next command
delta = buf_len - expect_len;
if (delta >= 0 && !memcmp(buf+delta, expect, expect_len))
if (delta >= 0 && memcmp(inbuf + delta, expect, expect_len) == 0)
goto expect_done;
#undef buf
} /* while (have data) */
// device timed out or unexpected reply received
// device timed out, or unexpected reply received,
// or we got a signal (poll() returned -1 with EINTR).
exitcode = ERR_TIMEOUT;
expect_done:
#if ENABLE_FEATURE_CHAT_NOFAIL
@@ -434,7 +438,7 @@ int chat_main(int argc UNUSED_PARAM, char **argv)
}
#endif
// bail out unless we expected successfully
if (exitcode)
if (exitcode != ERR_OK)
break;
//-----------------------
@@ -478,7 +482,7 @@ int chat_main(int argc UNUSED_PARAM, char **argv)
continue;
}
if ('p' == c) {
usleep(10000);
msleep(10);
len--;
continue;
}
+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:*/"s"
/*ignored:*/"sX"
);
argv += optind;
num_files = argc - optind;
+26
View File
@@ -46,6 +46,32 @@ 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 void show_bridge_port(const char *name)
static NOINLINE void show_bridge_port(const char *name)
{
char pathbuf[IFNAMSIZ + sizeof("/brport/forward_delay_timer") + 8];
char *sfx;
+1 -2
View File
@@ -290,8 +290,7 @@ 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 = "ftp";
/* socket to ftp server */
const char *port = NULL;
#if ENABLE_FTPPUT && !ENABLE_FTPGET
# define ftp_action ftp_send
+23 -6
View File
@@ -102,6 +102,12 @@
//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
@@ -268,9 +274,9 @@
//usage:#define httpd_full_usage "\n\n"
//usage: "Listen for incoming HTTP requests\n"
//usage: "\n -i Inetd mode"
//usage: "\n -f Don't daemonize"
//usage: "\n -f Run in foreground"
//usage: "\n -v[v] Verbose"
//usage: "\n -p [IP:]PORT Bind to IP:PORT (default *:80)"
//usage: "\n -p [IP:]PORT Bind to IP:PORT (default *:"STR(CONFIG_FEATURE_HTTPD_PORT_DEFAULT)")"
//usage: IF_FEATURE_HTTPD_SETUID(
//usage: "\n -u USER[:GRP] Set uid/gid after binding to port")
//usage: IF_FEATURE_HTTPD_BASIC_AUTH(
@@ -316,6 +322,9 @@
#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";
@@ -542,7 +551,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 = "80"; \
bind_addr_or_port = STR(CONFIG_FEATURE_HTTPD_PORT_DEFAULT); \
index_page = index_html; \
file_size = -1; \
} while (0)
@@ -1116,7 +1125,7 @@ static void send_headers(unsigned responseNum)
"Connection: close\r\n",
responseNum, responseString
#if ENABLE_FEATURE_HTTPD_DATE
,date_str
, date_str
#endif
);
}
@@ -1281,6 +1290,7 @@ 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();
}
@@ -1869,14 +1879,21 @@ static NOINLINE void send_file_and_exit(const char *url, int what)
send_headers(HTTP_OK);
#if ENABLE_FEATURE_USE_SENDFILE
{
off_t offset = (range_start < 0) ? 0 : range_start;
off_t offset;
# if ENABLE_FEATURE_HTTPD_RANGES
if (range_start < 0)
range_start = 0;
offset = range_start;
# else
offset = 0;
# endif
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)
if (offset == range_start) /* was it the very 1st sendfile? */
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 Don't daemonize"
//usage: "\n -n Run in foreground"
//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]"
//usage: " [master IFACE | nomaster] [netns PID]"
// * short help shows only "set" command, long help continues (with just one "\n")
// * and shows all other commands:
//usage:#define iplink_full_usage "\n"
+33 -2
View File
@@ -152,6 +152,30 @@ 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)
{
@@ -226,6 +250,7 @@ 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;
@@ -234,11 +259,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"
"arp\0""promisc\0""address\0""netns\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_arp, ARG_promisc, ARG_addr, ARG_netns,
ARG_master, ARG_nomaster,
ARG_dev };
enum { PARM_on = 0, PARM_off };
@@ -276,6 +301,9 @@ 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) {
@@ -463,6 +491,9 @@ 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],
argv[1] ? bb_lookup_port(argv[1], "tcp", 0) : 0);
bb_lookup_port(argv[1], "tcp", 0));
}
}
+2 -5
View File
@@ -813,8 +813,6 @@ 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 */
@@ -827,9 +825,8 @@ int nc_main(int argc UNUSED_PARAM, char **argv)
if (argv[0]) {
themaddr = xhost2sockaddr(argv[0],
argv[1]
? bb_lookup_port(argv[1], o_udpmode ? "udp" : "tcp", 0)
: 0);
bb_lookup_port(argv[1], o_udpmode ? "udp" : "tcp", 0)
);
}
/* create & bind network socket */
+1 -1
View File
@@ -335,7 +335,7 @@ enum {
OPT_debug = (1 << 0),
};
static int parse_reply(const unsigned char *msg, size_t len)
static NOINLINE 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 Do not daemonize"
//usage: "\n -n Run in foreground"
//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 peer_t*
static NOINLINE peer_t*
select_and_cluster(void)
{
peer_t *p;
+8 -2
View File
@@ -68,6 +68,12 @@
//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
@@ -103,7 +109,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"
//usage: "\n -p PORT Port to listen on. Default "STR(CONFIG_FEATURE_TELNETD_PORT_DEFAULT)
//usage: "\n -b ADDR[:PORT] Address to bind to"
//usage: "\n -F Run in foreground"
//usage: "\n -i Inetd mode"
@@ -708,7 +714,7 @@ int telnetd_main(int argc UNUSED_PARAM, char **argv)
} else {
master_fd = 0;
if (!(opt & OPT_WAIT)) {
unsigned portnbr = 23;
unsigned portnbr = CONFIG_FEATURE_TELNETD_PORT_DEFAULT;
if (opt & OPT_PORT)
portnbr = xatou16(opt_portnbr);
master_fd = create_and_bind_stream_or_die(opt_bindaddr, portnbr);
+95 -57
View File
@@ -22,47 +22,23 @@
#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 // 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 ALLOW_RSA_NULL_SHA256 0
#define TLS_DEBUG 0
#define TLS_DEBUG_HASH 0
@@ -1488,9 +1464,20 @@ 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 (7 + 6 * ENABLE_FEATURE_TLS_SHA1 + ALLOW_RSA_NULL_SHA256)
#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 \
)
static const uint8_t ciphers[] = {
0x00,2 + NUM_CIPHERS*2, //len16_be
0x00,2 * (1 + NUM_CIPHERS), //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
@@ -1501,14 +1488,22 @@ 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
@@ -1521,9 +1516,15 @@ 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
@@ -1532,12 +1533,16 @@ 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,0x06, //ext len
0x00,0x04, //list len
0x00,0x17, //curve_secp256r1 (aka P256)
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,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[] = {
@@ -1555,7 +1560,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 + NUM_CIPHERS*2]; /* actually variable */
uint8_t cipherid[2 * (1 + NUM_CIPHERS)]; /* actually variable */
uint8_t comprtypes_len;
uint8_t comprtypes[1]; /* actually variable */
/* Extensions (SNI shown):
@@ -1603,7 +1608,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 + 2 + NUM_CIPHERS*2 + 2);
BUILD_BUG_ON(sizeof(ciphers) != 2 * (1 + 1 + NUM_CIPHERS + 1));
memcpy(&record->cipherid_len16_hi, ciphers, sizeof(ciphers));
ptr = (void*)(record + 1);
@@ -1700,41 +1705,32 @@ 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;
@@ -1887,10 +1883,12 @@ 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).
*/
@@ -1903,7 +1901,6 @@ 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)
@@ -1944,7 +1941,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("server cert is not RSA");
bb_simple_error_msg_and_die("server cert is not RSA");
tls_get_random(premaster, RSA_PREMASTER_SIZE);
if (TLS_DEBUG_FIXED_SECRETS)
@@ -2330,6 +2327,47 @@ 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;
+4 -1
View File
@@ -101,7 +101,6 @@ 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"
@@ -117,3 +116,7 @@ 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;
+63 -65
View File
@@ -63,16 +63,22 @@ 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 *zero, const byte *one,
const byte *src,
byte condition)
{
const byte mask = -condition;
int i;
for (i = 0; i < F25519_SIZE; i++)
dst[i] = zero[i] ^ (mask & (one[i] ^ zero[i]));
dst[i] = dst[i] ^ (mask & (src[i] ^ dst[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)
@@ -181,7 +187,7 @@ static void fprime_mul(byte *r, const byte *a, const byte *b,
#if 0 //UNUSED
static void fe_load(byte *x, word32 c)
{
word32 i;
int i;
for (i = 0; i < sizeof(c); i++) {
x[i] = c;
@@ -193,6 +199,21 @@ 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];
@@ -200,14 +221,7 @@ static void fe_normalize(byte *x)
int i;
/* Reduce using 2^255 = 19 mod p */
c = (x[31] >> 7) * 19;
x[31] &= 127;
for (i = 0; i < F25519_SIZE; i++) {
c += x[i];
x[i] = (byte)c;
c >>= 8;
}
fe_reduce(x, x[31]);
/* The number is now less than 2^255 + 18, and therefore less than
* 2p. Try subtracting p, and conditionally load the subtracted
@@ -225,7 +239,7 @@ static void fe_normalize(byte *x)
minusp[31] = (byte)c;
/* Load x-p if no underflow */
fe_select(x, minusp, x, (c >> 15) & 1);
fe_select(x, minusp, !(c & (1<<15)));
}
static void lm_add(byte* r, const byte* a, const byte* b)
@@ -241,14 +255,7 @@ static void lm_add(byte* r, const byte* a, const byte* b)
}
/* Reduce with 2^255 = 19 mod p */
r[31] &= 127;
c = (c >> 7) * 19;
for (i = 0; i < F25519_SIZE; i++) {
c += r[i];
r[i] = (byte)c;
c >>= 8;
}
fe_reduce(r, c);
}
static void lm_sub(byte* r, const byte* a, const byte* b)
@@ -258,21 +265,15 @@ 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 + 1 < F25519_SIZE; i++) {
for (i = 0; i < F25519_SIZE - 1; 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;
for (i = 0; i < F25519_SIZE; i++) {
c += r[i];
r[i] = c;
c >>= 8;
}
fe_reduce(r, c);
}
#if 0 //UNUSED
@@ -283,21 +284,15 @@ static void lm_neg(byte* r, const byte* a)
/* Calculate 2p - a, to avoid underflow */
c = 218;
for (i = 0; i + 1 < F25519_SIZE; i++) {
for (i = 0; i < F25519_SIZE - 1; i++) {
c += 65280 - ((word32)a[i]);
r[i] = c;
c >>= 8;
}
c -= ((word32)a[31]);
r[31] = c & 127;
c = (c >> 7) * 19;
for (i = 0; i < F25519_SIZE; i++) {
c += r[i];
r[i] = c;
c >>= 8;
}
fe_reduce(r, c);
}
#endif
@@ -320,14 +315,7 @@ static void fe_mul__distinct(byte *r, const byte *a, const byte *b)
r[i] = c;
}
r[31] &= 127;
c = (c >> 7) * 19;
for (i = 0; i < F25519_SIZE; i++) {
c += r[i];
r[i] = c;
c >>= 8;
}
fe_reduce(r, c);
}
#if 0 //UNUSED
@@ -351,15 +339,7 @@ static void fe_mul_c(byte *r, const byte *a, word32 b)
r[i] = c;
}
r[31] &= 127;
c >>= 7;
c *= 19;
for (i = 0; i < F25519_SIZE; i++) {
c += r[i];
r[i] = c;
c >>= 8;
}
fe_reduce(r, c);
}
static void fe_inv__distinct(byte *r, const byte *x)
@@ -548,26 +528,32 @@ static void curve25519(byte *result, const byte *e, const byte *q)
{
int i;
struct {
struct Z {
/* 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};
/* Current point: P_m */
byte xm[F25519_SIZE];
byte zm[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];
} 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 xm z.xm
#define zm z.zm
#define xm1 z.xm1
#define zm1 z.zm1
#define xm z.xm
#define zm z.zm
#define xms z.xms
#define zms z.zms
memset(&z, 0, sizeof(z));
f25519_one[0] = 1;
zm[0] = 1;
@@ -583,8 +569,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);
@@ -597,10 +583,22 @@ 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))
*/
fe_select(xm1, xm1, xm, bit);
fe_select(zm1, zm1, zm, bit);
fe_select(xm, xm, xms, bit);
fe_select(zm, zm, zms, bit);
#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
}
/* Freeze out of projective coordinates */
-1
View File
@@ -283,4 +283,3 @@ extern int32 pstm_invmod(psPool_t *pool, pstm_int * a, pstm_int * b,
typedef int32 pstm_int;
#endif /* !DISABLE_PSTM */
#endif /* _h_PSTMATH */
+1145 -549
View File
File diff suppressed because it is too large. Load diff
-511
View File
@@ -1,511 +0,0 @@
/*
* 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 */
/******************************************************************************/
+22 -7
View File
@@ -404,14 +404,29 @@ 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)
struct option_set* FAST_FUNC udhcp_find_option(struct option_set *opt_list, uint8_t code, bool dhcpv6)
{
while (opt_list && opt_list->data[OPT_CODE] < code)
opt_list = opt_list->next;
IF_NOT_UDHCPC6(bool dhcpv6 = 0;)
uint8_t cur_code;
if (opt_list && opt_list->data[OPT_CODE] == code)
return opt_list;
return NULL;
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;
}
opt_list = opt_list->next;
}
}
/* Parse string to IP in network order */
@@ -499,7 +514,7 @@ static NOINLINE void attach_option(
}
#endif
existing = udhcp_find_option(*opt_list, optflag->code);
existing = udhcp_find_option(*opt_list, optflag->code, dhcpv6);
if (!existing) {
/* make a new option */
uint8_t *p = udhcp_insert_new_option(opt_list, optflag->code, length, dhcpv6);
+29 -20
View File
@@ -38,13 +38,27 @@ 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 to use in bootstrap, returned in DHCPOFFER, DHCPACK by server */
/* IP address of "next server" (usually meant to be an TFTP server)
* to use in bootstrap, returned in DHCPOFFER, DHCPACK by server: */
uint32_t siaddr_nip;
uint32_t gateway_nip; /* aka 'giaddr': relay agent IP address */
/* 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 */
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) */
uint32_t cookie; /* fixed first four option bytes (99,130,83,99 dec) */
/* 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 */
uint8_t options[DHCP_OPTIONS_BUFSIZE + CONFIG_UDHCPC_SLACK_FOR_BUGGY_SERVERS];
};
#define DHCP_PKT_SNAME_LEN 64
@@ -142,18 +156,21 @@ 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: */
#define DHCP_OPTION_OVERLOAD 0x34 /* 52: */
#define DHCP_MESSAGE_TYPE 0x35 /* 53: */
#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_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: */
#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_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 */
@@ -228,7 +245,11 @@ 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
struct option_set *udhcp_find_option(struct option_set *opt_list, uint8_t code) FAST_FUNC;
#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;
// RFC 2131 Table 5: Fields and options used by DHCP clients
//
@@ -304,18 +325,6 @@ void udhcp_dump_packet(struct dhcp_packet *packet) FAST_FUNC;
# define log3s(msg) ((void)0)
#endif
#if defined(__mips__)
/*
* The 'simple' message functions have a negative impact on the size of the
* DHCP code when compiled for MIPS, so don't use them in this case.
*/
#define bb_simple_info_msg bb_info_msg
#define bb_simple_error_msg bb_error_msg
#define bb_simple_perror_msg_and_die bb_perror_msg_and_die
#undef log1s
#define log1s log1
#endif
/*** Other shared functions ***/
/* 2nd param is "uint32_t*" */
+3 -2
View File
@@ -888,7 +888,8 @@ 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 */
ci = udhcp_find_option(client_data.options, D6_OPT_CLIENTID);
///vda
ci = udhcp_find_option(client_data.options, D6_OPT_CLIENTID, /*dhcpv6:*/ 1);
if (ci)
opt_ptr = mempcpy(opt_ptr, ci->data, D6_OPT_DATA + 2+2 + 6);
@@ -1272,7 +1273,7 @@ int udhcpc6_main(int argc UNUSED_PARAM, char **argv)
}
clientid_mac_ptr = NULL;
if (!udhcp_find_option(client_data.options, D6_OPT_CLIENTID)) {
if (!udhcp_find_option(client_data.options, D6_OPT_CLIENTID, /*dhcpv6:*/ 1)) {
/* 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))
//if (!udhcp_find_option(packet.options, DHCP_VENDOR, /*dhcpv6:*/ 0))
// /* 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);
ci = udhcp_find_option(client_data.options, DHCP_CLIENT_ID, /*dhcpv6:*/ 0);
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)) {
if (!(opt & OPT_C) && !udhcp_find_option(client_data.options, DHCP_CLIENT_ID, /*dhcpv6:*/ 0)) {
/* not suppressed and not set, create default client ID */
clientid_mac_ptr = udhcp_insert_new_option(
&client_data.options, DHCP_CLIENT_ID,
+26 -11
View File
@@ -27,7 +27,7 @@
//kbuild:lib-$(CONFIG_FEATURE_UDHCP_RFC3397) += domain_codec.o
//usage:#define udhcpd_trivial_usage
//usage: "[-fS] [-I ADDR]" IF_FEATURE_UDHCP_PORT(" [-P PORT]") " [CONFFILE]"
//usage: "[-fS] [-I ADDR] [-a MSEC]" 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,6 +451,8 @@ 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)
@@ -612,6 +614,10 @@ 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);
}
@@ -858,7 +864,6 @@ 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;
@@ -877,6 +882,12 @@ 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"
@@ -887,24 +898,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 & 1)) { /* no -f */
);
if (!(opt & OPT_f)) { /* no -f */
bb_daemonize_or_rexec(0, argv);
logmode = LOGMODE_NONE;
}
/* update argv after the possible vfork+exec in daemonize */
argv += optind;
if (opt & 2) { /* -S */
if (opt & OPT_S) {
openlog(applet_name, LOG_PID, LOG_DAEMON);
logmode |= LOGMODE_SYSLOG;
}
if (opt & 4) { /* -I */
if (opt & OPT_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 & 32) { /* -P */
if (opt & OPT_P) {
SERVER_PORT = xatou16(str_P);
CLIENT_PORT = SERVER_PORT + 1;
}
@@ -924,7 +935,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);
option = udhcp_find_option(server_data.options, DHCP_LEASE_TIME, /*dhcpv6:*/ 0);
server_data.max_lease_sec = DEFAULT_LEASE_TIME;
if (option) {
move_from_unaligned32(server_data.max_lease_sec, option->data + OPT_DATA);
@@ -960,6 +971,7 @@ 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;
@@ -1017,6 +1029,9 @@ 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) {
@@ -1034,8 +1049,8 @@ int udhcpd_main(int argc UNUSED_PARAM, char **argv)
bb_info_msg("not a REQUEST%s", ", ignoring packet");
continue;
}
state = udhcp_get_option(&packet, DHCP_MESSAGE_TYPE);
if (state == NULL || state[0] < DHCP_MINTYPE || state[0] > DHCP_MAXTYPE) {
msg_type = udhcp_get_option(&packet, DHCP_MESSAGE_TYPE);
if (!msg_type || msg_type[0] < DHCP_MINTYPE || msg_type[0] > DHCP_MAXTYPE) {
bb_info_msg("no or bad message type option%s", ", ignoring packet");
continue;
}
@@ -1071,7 +1086,7 @@ int udhcpd_main(int argc UNUSED_PARAM, char **argv)
move_from_unaligned32(requested_nip, requested_ip_opt);
}
switch (state[0]) {
switch (msg_type[0]) {
case DHCPDISCOVER:
log1("received %s", "DISCOVER");
+40 -23
View File
@@ -17,7 +17,8 @@
//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"
//usage: "Relay DHCP requests between clients and server.\n"
//usage: "Without SERVER_IP, requests are broadcast on SERVER_IFACE."
#include "common.h"
@@ -31,7 +32,7 @@
/* This list holds information about clients. The xid_* functions manipulate this list. */
struct xid_item {
unsigned timestamp;
int client;
unsigned iface_no;
uint32_t xid;
struct sockaddr_in ip;
struct xid_item *next;
@@ -40,7 +41,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, int client)
static struct xid_item *xid_add(uint32_t xid, struct sockaddr_in *ip, unsigned iface_no)
{
struct xid_item *item;
@@ -50,7 +51,7 @@ static struct xid_item *xid_add(uint32_t xid, struct sockaddr_in *ip, int client
/* add xid entry */
item->ip = *ip;
item->xid = xid;
item->client = client;
item->iface_no = iface_no;
item->timestamp = monotonic_sec();
item->next = dhcprelay_xid_list.next;
dhcprelay_xid_list.next = item;
@@ -127,10 +128,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, int *client_number)
static char **make_iface_list(char **client_and_server_ifaces, unsigned *client_number)
{
char *s, **iface_list;
int i, cn;
unsigned i, cn;
/* get number of items */
cn = 2; /* 1 server iface + at least 1 client one */
@@ -165,9 +166,9 @@ static char **make_iface_list(char **client_and_server_ifaces, int *client_numbe
/* Creates listen sockets (in fds) bound to client and server ifaces,
* and returns numerically max fd.
*/
static int init_sockets(char **iface_list, int num_clients, int *fds)
static unsigned init_sockets(char **iface_list, unsigned num_clients, int *fds)
{
int i, n;
unsigned i, n;
n = 0;
for (i = 0; i < num_clients; i++) {
@@ -195,13 +196,14 @@ 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, int client, int *fds,
static void pass_to_server(struct dhcp_packet *p, int packet_len, unsigned from_iface_no, 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
@@ -210,7 +212,10 @@ static void pass_to_server(struct dhcp_packet *p, int packet_len, int client, in
}
/* create new xid entry */
xid_add(p->xid, client_addr, client);
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?
/* forward request to server */
/* note that we send from fds[0] which is bound to SERVER_PORT (67).
@@ -229,25 +234,30 @@ 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;
}
/* check packet type */
type = get_dhcp_packet_type(p);
if (type != DHCPOFFER && type != DHCPACK && type != DHCPNAK) {
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.
//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);
if (sendto_ip4(fds[item->client], p, packet_len, &item->ip) != 0) {
return; /* send error occurred */
}
sendto_ip4(fds[item->iface_no], p, packet_len, &item->ip);
/* ^^^ if send error occurred, we can't do much, hence no check */
/* remove xid entry */
xid_del(p->xid);
@@ -259,7 +269,7 @@ int dhcprelay_main(int argc UNUSED_PARAM, char **argv)
struct sockaddr_in server_addr;
char **iface_list;
int *fds;
int num_sockets, max_socket;
unsigned num_sockets, max_socket;
uint32_t our_nip;
INIT_G();
@@ -293,7 +303,7 @@ int dhcprelay_main(int argc UNUSED_PARAM, char **argv)
// every N minutes?
fd_set rfds;
struct timeval tv;
int i;
unsigned i;
FD_ZERO(&rfds);
for (i = 0; i < num_sockets; i++)
@@ -304,15 +314,17 @@ int dhcprelay_main(int argc UNUSED_PARAM, char **argv)
int packlen;
struct dhcp_packet dhcp_msg;
/* server */
/* from 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);
}
}
/* clients */
/* from clients */
for (i = 1; i < num_sockets; i++) {
struct sockaddr_in client_addr;
socklen_t addr_size;
@@ -325,6 +337,11 @@ 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
+45 -16
View File
@@ -135,7 +135,8 @@
//usage:#define wget_trivial_usage
//usage: IF_FEATURE_WGET_LONG_OPTIONS(
//usage: "[-cqS] [--spider] [-O FILE] [-o LOGFILE] [--header 'HEADER: VALUE'] [-Y on/off]\n"
//usage: "[-cqS] [--spider] [-O FILE] [-o LOGFILE] [--header STR]\n"
//usage: " [--post-data STR | --post-file FILE] [-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]" */
@@ -148,6 +149,9 @@
//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: )
@@ -207,29 +211,33 @@ enum {
HDR_HOST = (1<<0),
HDR_USER_AGENT = (1<<1),
HDR_RANGE = (1<<2),
HDR_AUTH = (1<<3) * ENABLE_FEATURE_WGET_AUTHENTICATION,
HDR_PROXY_AUTH = (1<<4) * ENABLE_FEATURE_WGET_AUTHENTICATION,
HDR_CONTENT_TYPE = (1<<3),
HDR_AUTH = (1<<4) * ENABLE_FEATURE_WGET_AUTHENTICATION,
HDR_PROXY_AUTH = (1<<5) * 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_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_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)
#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_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_CONTENT_TYPE 0
# define USR_HEADER_AUTH 0
# define USR_HEADER_PROXY_AUTH 0
#endif
/* Globals */
@@ -244,6 +252,7 @@ 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
@@ -292,10 +301,13 @@ 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,
@@ -1213,7 +1225,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_DATA) ? "POST" : "GET",
(option_mask32 & WGET_OPT_POST) ? "POST" : "GET",
target.path);
}
if (!USR_HEADER_HOST)
@@ -1246,9 +1258,20 @@ static void download_one_url(const char *url)
fputs(G.extra_headers, sfp);
}
if (option_mask32 & WGET_OPT_POST_DATA) {
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"
);
}
SENDFMT(sfp,
"Content-Type: application/x-www-form-urlencoded\r\n"
"Content-Length: %u\r\n"
"\r\n"
"%s",
@@ -1489,6 +1512,7 @@ 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) */
@@ -1532,6 +1556,9 @@ 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,
@@ -1541,6 +1568,7 @@ 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");
@@ -1549,6 +1577,7 @@ 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;
+8 -1
View File
@@ -5,7 +5,12 @@
menu "Process Utilities"
INSERT
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.
config FEATURE_SHOW_THREADS
bool "Support thread display in ps/pstree/top"
@@ -15,4 +20,6 @@ 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 */
+18 -14
View File
@@ -443,17 +443,19 @@ static void parse_o(char* opt)
opt = comma + 1;
continue;
}
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;
// 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';
// 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=,
@@ -461,10 +463,12 @@ static void parse_o(char* opt)
// default header text
if (new->header[0]) {
new->width = strlen(new->header);
print_header = 1;
}
} else
print_header = 1;
if (!comma)
break;
//*comma = ','; /* no, new->header should stay NUL-terminated */
opt = comma + 1;
}
}
static void alloc_line_buffer(void)
+1 -15
View File
@@ -29,7 +29,6 @@ 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);
@@ -40,20 +39,7 @@ 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;
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);
chksum_and_xwrite_tar_header(STDOUT_FILENO, &header);
}
static void archivefile(const char *path)
+297 -264
View File
File diff suppressed because it is too large. Load diff
@@ -0,0 +1 @@
Ok
+16
View File
@@ -0,0 +1,16 @@
# 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
@@ -0,0 +1 @@
Ok
+8
View File
@@ -0,0 +1,8 @@
# 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,4 +2,7 @@
1 1
1 1
1 1
6 6
7 7
7 7
Ok:0
@@ -2,4 +2,8 @@ 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:$?
+54 -24
View File
@@ -43,40 +43,60 @@ 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
./arith.tests: line 117: arithmetic syntax error
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
6 6
6,5,3 6,5,3
octal, hex
263 263
255 255
40 40
./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
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
abc
def
ghi
./arith.tests: line 191: arithmetic syntax error
./arith.tests: line 190: arithmetic syntax error
16 16
./arith.tests: line 196: arithmetic syntax error
./arith.tests: line 197: malformed ?: operator
./arith.tests: line 198: arithmetic syntax error
./arith.tests: line 195: arithmetic syntax error
./arith.tests: line 196: malformed ?: operator
./arith.tests: line 197: arithmetic syntax error
9 9
./arith.tests: line 205: arithmetic syntax error
./arith.tests: line 208: arithmetic syntax error
./arith.tests: line 204: arithmetic syntax error
./arith.tests: line 207: arithmetic syntax error
9 9
9 9
9 9
@@ -97,14 +117,17 @@ ghi
3 3
4 4
4 4
./arith.tests: line 257: arithmetic syntax error
7 7
./arith.tests: line 256: arithmetic syntax error
./arith.tests: line 258: arithmetic syntax error
./arith.tests: line 259: arithmetic syntax error
./arith.tests: line 260: arithmetic syntax error
./arith.tests: line 261: 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
@@ -119,11 +142,12 @@ ghi
2 2
-2 -2
1 1
./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
7
7
7
7
7
7
5 5
1 1
6 6
@@ -132,11 +156,17 @@ ghi
1 1
4 4
0 0
./arith2.sub: line 42: arithmetic syntax error
./arith2.sub: line 47: arithmetic syntax error
-7
-7
7
7
-7 -7
-7 -7
7 7
7 7
8 12
./arith.tests: line 290: arithmetic syntax error
./arith.tests: line 289: arithmetic syntax error
42
42
42
./arith.tests: line 302: a[b[c]d]=e: not found
./arith.tests: line 301: a[b[c]d]=e: not found
+27 -28
View File
@@ -75,11 +75,11 @@ echo 4 $(( iv &= 4 ))
echo 29 $(( iv += (jv + 9)))
echo 5 $(( (iv + 4) % 7 ))
# unary plus, minus
echo unary plus, minus
echo -4 $(( +4 - 8 ))
echo 4 $(( -4 + 8 ))
# conditional expressions
echo conditional expressions
echo 1 $(( 4<5 ? 1 : 32))
echo 32 $(( 4>5 ? 1 : 32))
echo 32 $(( 4>(2+3) ? 1 : 32))
@@ -87,8 +87,7 @@ echo 1 $(( 4<(2+3) ? 1 : 32))
echo 1 $(( (2+2)<(2+3) ? 1 : 32))
echo 32 $(( (2+2)>(2+3) ? 1 : 32))
# check that the unevaluated part of the ternary operator does not do
# evaluation or assignment
echo 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
@@ -109,20 +108,20 @@ echo 20 $((1 ? 20 : (x+=2)))
echo 30 $((0 ? (y+=2) : 30))
#ash# echo $i,$y # ash mishandles this
# check precedence of assignment vs. conditional operator
echo 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)) )
# check precedence of assignment vs. conditional operator
echo 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))
# associativity of assignment-operator operator
echo associativity of assignment-operator operator
#ash# declare -i i=1 j=2 k=3
i=1
j=2
@@ -130,7 +129,7 @@ k=3
echo 6 $((i += j += k))
echo 6,5,3 $i,$j,$k
# octal, hex
echo octal, hex
echo 263 $(( 0x100 | 007 ))
echo 255 $(( 0xff ))
#ash# echo 255 $(( 16#ff ))
@@ -139,25 +138,25 @@ echo 255 $(( 0xff ))
echo 40 $(( 8 ^ 32 ))
#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#_ ))
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# # weird bases (error)
#ash# echo $(( 3425#56 ))
#ash# # missing number after base
#ash# echo 0 $(( 2# ))
echo missing number after base
echo 0 $(( 2# ))
# these should generate errors
( echo $(( 7 = 43 )) )
@@ -252,8 +251,8 @@ echo 3 $x
echo 4 $(( ++x ))
echo 4 $x
# bash 3.2 apparently thinks that ++7 is 7
#ash# echo 7 $(( ++7 ))
# ++ is not a inc operator on non-variable, it is the + + sequence
echo 7 $(( ++7 ))
( echo $(( 7-- )) )
( echo $(( --x=7 )) )
@@ -267,9 +266,9 @@ echo 4 $x
echo 7 $(( +7 ))
echo -7 $(( -7 ))
# bash 3.2 apparently thinks that ++7 is 7
#ash# echo $(( ++7 ))
#ash# echo $(( --7 ))
# ++ is not a inc operator on non-variable, it is the + + sequence
echo $(( ++7 ))
echo $(( --7 ))
${THIS_SH} ./arith1.sub
${THIS_SH} ./arith2.sub
+2 -2
View File
@@ -35,6 +35,6 @@ echo 1 $a
#ash# (( ++ ))
( echo $(( +++7 )) )
# bash 3.2 apparently thinks that ++ +7 is 7
#ash# echo $(( ++ + 7 ))
# ++ is not a inc operator on non-variable, it is the + + sequence
echo $(( ++ + 7 ))
#ash# (( -- ))
Loaded 100 of 160 files, more files were not shown because too many files have changed in this diff. Show more