Compare commits

..
205 Commits
Author SHA1 Message Date
Denys Vlasenko 6412da255d libbb: fix ioloop's limitation of fd < 1024
function                                             old     new   delta
grow_fdsets                                            -      90     +90
ioloop_run                                           438     485     +47
------------------------------------------------------------------------------
(add/remove: 1/0 grow/shrink: 1/0 up/down: 137/0)             Total: 137 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-11-17 18:23:08 +01:00
Denys Vlasenko 25a61f0feb shell: in math evaluation, use malloc, not alloca
function                                             old     new   delta
evaluate_string                                     1315    1322      +7

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-11-17 14:44:30 +01:00
Denys Vlasenko d724d7d292 mkfs.vfat: fix creation of 2.5 kbyte FAT12 image
function                                             old     new   delta
mkfs_vfat_main                                      2463    2454      -9
.rodata                                           105036  105007     -29
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 0/2 up/down: 0/-38)             Total: -38 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-11-16 13:56:51 +01:00
Denys Vlasenko 8d79a6335c mkfs.vfat: fix write buffer allocation for tiny images
function                                             old     new   delta
mkfs_vfat_main                                      2460    2463      +3

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-11-15 23:06:39 +01:00
Denys Vlasenko 3441a0e4bc mkfs.vfat: add ignored option -a ("disable alignment")
function                                             old     new   delta
.rodata                                           105038  105036      -2

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-11-15 22:44:24 +01:00
Denys Vlasenko f8f567fb54 mkfs.vfat: implement creation of FAT12/16 filesystems
function                                             old     new   delta
mkfs_vfat_main                                      1858    2460    +602
.rodata                                           105028  105038     +10
packed_usage                                       36569   36575      +6
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 3/0 up/down: 618/0)             Total: 618 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-11-15 19:18:08 +01:00
Denys Vlasenko 7b38885adf mkfs.vfat: code shrink
function                                             old     new   delta
mkfs_vfat_main                                      1874    1858     -16

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-11-14 20:04:56 +01:00
Denys Vlasenko 174ee36441 mkfs.vfat: code chrink, prepare for FAT16/12 support
function                                             old     new   delta
mkfs_vfat_main                                      1880    1874      -6

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-11-14 16:14:12 +01:00
Denys Vlasenko cb53a88831 testsuite: modify 130GB mkfs.vfat test to actually have the very max cluster#
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-11-14 00:23:59 +01:00
Denys Vlasenko fb32719cb2 testsuite: add 130GB mkfs.vfat test
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-11-13 17:30:02 +01:00
Denys Vlasenko d3303c327e mkfs.vfat: add -s SECTORS_PER_CLUSTER
function                                             old     new   delta
mkfs_vfat_main                                      1800    1880     +80
.rodata                                           105000  105028     +28
packed_usage                                       36552   36549      -3
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 2/1 up/down: 108/-3)            Total: 105 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-11-13 16:55:59 +01:00
Denys Vlasenko 9f435d8347 mkfs.vfat: if -C, avoid unnecessary zero-filling of newly-created image file
This can save hundreds of megabytes for a QEMU-operated virtual FAT32 disk.

function                                             old     new   delta
mkfs_vfat_main                                      1766    1800     +34
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 1/0 up/down: 34/0)               Total: 34 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-11-13 15:09:33 +01:00
Denys Vlasenko 484da7a2b3 mkfs.vfat: add support for -S SECTOR_SIZE
mkfs.vfat -v -F32 -S4096 -C IMAGE_16TB $((1024*1024*1024*16 - 0x10000))
tested to work.

function                                             old     new   delta
mkfs_vfat_main                                      1613    1686     +73
packed_usage                                       36498   36552     +54
.rodata                                           104988  105000     +12
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 3/0 up/down: 139/0)             Total: 139 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-11-13 14:49:44 +01:00
Denys Vlasenko d99c769ce3 mkfs.vfat: make -n "NO NAME " create the volume label as requested.
"NO NAME    " has special meaning _only_ in boot sector, not in rootdir's label.

function                                             old     new   delta
mkfs_vfat_main                                      1621    1613      -8

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-11-13 13:53:13 +01:00
Denys Vlasenko c743bd3a9d libbb: if get_volume_size_in_bytes() detects too-small block device, warn about it
The "mkfs.vfar BLOCKDEV 1000000" case where BLOCKDEV is smaller.

function                                             old     new   delta
.rodata                                           104938  104988     +50
get_volume_size_in_bytes                             262     293     +31
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 2/0 up/down: 81/0)               Total: 81 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-11-13 13:44:25 +01:00
Denys Vlasenko 8eea53bb7a libbb: introduce and use xfstat_mode() and xfstat_size()
function                                             old     new   delta
xfstat_size                                            -      28     +28
add_remove_shell_main                                312     302     -10
mkfs_ext2_main                                      2299    2285     -14
mesg_main                                            157     136     -21
ar_main                                              565     527     -38
ubi_tools_main                                      1164    1125     -39
------------------------------------------------------------------------------
(add/remove: 1/0 grow/shrink: 0/5 up/down: 28/-122)           Total: -94 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-11-12 16:40:57 +01:00
Denys Vlasenko 10c9c7faec mkfs.vfat: code shrink
function                                             old     new   delta
xfstat_mode                                            -      26     +26
mkfs_vfat_main                                      2106    1621    -485
------------------------------------------------------------------------------
(add/remove: 1/0 grow/shrink: 0/1 up/down: 26/-485)          Total: -459 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-11-12 16:05:41 +01:00
Denys Vlasenko e18ddc4ad3 mkfs.vfat: print how many sectors we ignore on large volumes
It's quite useful to know whether you lose 123 sectors, or 123 gigabytes.

function                                             old     new   delta
mkfs_vfat_main                                      2096    2106     +10
.rodata                                           104951  104938     -13
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 1/1 up/down: 10/-13)             Total: -3 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-11-12 16:04:41 +01:00
Denys Vlasenko 67a351f7c0 mkfs.vfat: code shrink, tweak comments
function                                             old     new   delta
mkfs_vfat_main                                      2102    2096      -6

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-11-12 12:33:16 +01:00
Denys Vlasenko 7de358fa8e mkfs.vfat: explain big filesystem sizes with 32 sectors/cluster, no code changes
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-11-12 11:11:29 +01:00
Denys Vlasenko 3e4beef20c mkfs.vfat: support -b N -R N - allows creation of tiny 3KB FAT32 image
function                                             old     new   delta
mkfs_vfat_main                                      1586    2102    +516
.rodata                                           104913  104951     +38
packed_usage                                       36467   36498     +31
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 3/0 up/down: 585/0)             Total: 585 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-11-12 10:48:49 +01:00
Denys Vlasenko 4f986c0f9d mkfs.vfat: make it possible to create tiny 5KB images
function                                             old     new   delta
mkfs_vfat_main                                      1539    1586     +47
mkswap_main                                          253     256      +3
mkfs_minix_main                                     2575    2578      +3
mkfs_ext2_main                                      2297    2299      +2
.rodata                                           104946  104913     -33
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 4/1 up/down: 55/-33)             Total: 22 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-11-10 18:19:26 +01:00
Denys Vlasenko d03387ebf3 mkfs.vfat: correctly handle huge images with total sectors above 2^32
function                                             old     new   delta
.rodata                                           104897  104946     +49
mkfs_vfat_main                                      1526    1539     +13
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 2/0 up/down: 62/0)               Total: 62 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-11-10 16:21:24 +01:00
Denys Vlasenko 292ec317a3 mkfs.ext2: fix "can't open '(null)': Bad address"
function                                             old     new   delta
.rodata                                           104893  104897      +4

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-11-10 14:32:38 +01:00
Denys Vlasenko f227dc2eb7 mkfs.vfat: implement -C
function                                             old     new   delta
packed_usage                                       36438   36467     +29
mkfs_vfat_main                                      1518    1526      +8
.rodata                                           104894  104893      -1
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 2/1 up/down: 37/-1)              Total: 36 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-11-10 14:29:07 +01:00
Denys Vlasenko a096845640 testsuite: add mkfs.vfat and blkid tests
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-11-10 11:46:15 +01:00
Denys Vlasenko 6a839afdee volume_id/fat: follow kernel example in deciding what is FAT32
This will allow detection of small FAT32 volumes which
are mountable by kernel - before this change we misdetected them,
and likely failed to fetch volume label.

While at it, avoid running off FAT if FAT is smaller than necessary
to cover entire data area, and rootdir has clusters beyond this
"shorter FAT". (This matches kernel behavior too)

function                                             old     new   delta
volume_id_probe_vfat                                 856     886     +30

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-11-10 03:25:03 +01:00
Denys Vlasenko bd8c4f7ce9 volume_id/fat: decrease maximum valid FAT table size to 0x02000000 sectors
It's still enormous (16GByte FAT tables). Real-world maximum
is 16 times smaller since cluster numbers are 28-bit.

function                                             old     new   delta
volume_id_probe_vfat                                 867     856     -11

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-11-10 00:43:35 +01:00
Denys Vlasenko 8015168a75 Share "NO NAME " string
function                                             old     new   delta
bb_NO_NAME_11                                          -      12     +12
static.NO_NAME_11                                     12       -     -12
.rodata                                           104906  104894     -12
------------------------------------------------------------------------------
(add/remove: 1/1 grow/shrink: 0/1 up/down: 12/-24)            Total: -12 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-11-09 23:43:17 +01:00
Denys Vlasenko d04e804bee volume_id/fat: in root dir scan, stop at first cluster# larger than FAT size
Otherwise, we can read non-FAT area and try to interpret it as FAT.

function                                             old     new   delta
volume_id_probe_vfat                                 851     867     +16

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-11-09 12:50:07 +01:00
Denys Vlasenko 0c1060dee1 volume_id/fat: add validity checks for FAT12/16 (rootdir can't have 0 sectors)
function                                             old     new   delta
volume_id_probe_vfat                                 815     852     +37
mkfs_vfat_main                                      1523    1518      -5
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 1/1 up/down: 37/-5)              Total: 32 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-11-09 12:37:21 +01:00
Denys Vlasenko 484e887ce6 volume_id/fat: avoid rereading of 1st sector - use it when we have it initially
function                                             old     new   delta
volume_id_probe_vfat                                 856     815     -41

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-11-08 21:13:58 +01:00
Denys Vlasenko 0338bee40e volume_id/fat: allow FAT partitions with one FAT, tighten some validity checks
function                                             old     new   delta
volume_id_probe_vfat                                 829     856     +27

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-11-08 20:54:48 +01:00
Denys Vlasenko 7584233f64 volume_id/fat: remove test for non-zero head count in FAT superblock probe.
From util-linux:

    This change enables the auto-detection of the internal storage on a VTech
    Kidizoom camera, which has a zero head count value in the superblock.

    Microsoft documentation, "FAT: General Overview of On-Disk Format", states
    that the sectors and heads fields are only relevant for media that have
    a geometry.

    The Linux kernel also does not require a non-zero head count, and can
    manually mount the filesystem.

function                                             old     new   delta
volume_id_probe_vfat                                 841     829     -12

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-11-08 19:20:57 +01:00
Denys Vlasenko b7c89c493a volume_id/fat: prevent possible division by zero and crash
function                                             old     new   delta
volume_id_probe_vfat                                 830     841     +11

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-11-08 18:25:22 +01:00
Dominique Martinet d68f55fc29 tunctl: fix segfault on ioctl failure
libbb now takes "" instead of NULL as format string for nomsg functions,
but this caller had not been updated making busybox segfault on tunctl
commands when ioctl fails.
This can be reproduced by running `tunctl -t tun0` in gdb and blocking
with the tun open after being created, and running `tunctl -d tun0` in
another shell: the later will fail with EBUSY after fixing:
> tunctl: Device or resource busy

function                                             old     new   delta
tunctl_main                                          393     409     +16

Fixes: 4bd70463c7 ("libbb: pass "" rather than NULL as format string in _nomsg functions")
Signed-off-by: Dominique Martinet <dominique.martinet@atmark-techno.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-11-08 17:24:12 +01:00
Denys Vlasenko 17080dd399 shell/math: speed up handling of short arithmetic expansions
function                                             old     new   delta
evaluate_string                                     1291    1315     +24

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-11-08 16:31:12 +01:00
Denys Vlasenko d03670c64e mount: remove support for "swap" and "sw" mount options, they were added by mistake
Review of git log shows that they were mistakenly added during a rewrite
(confused with *FS type string* "swap" used in fstab to specify swap partitions).
util-linux's mount does not support this.
There is no reason to keep this incompatible extension.

function                                             old     new   delta
mount_main                                          1250    1249      -1
mount_options                                        188     180      -8
mount_option_str                                     385     377      -8
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 0/3 up/down: 0/-17)             Total: -17 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-11-08 13:17:40 +01:00
Denys Vlasenko 604470bec4 mount: disallow -o OPTS, -T ALT_FSTAB, -a,r,w,n,f,i for non-root mount invocations
function                                             old     new   delta
mount_main                                          1259    1250      -9
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 0/1 up/down: 0/-9)               Total: -9 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-11-08 03:05:09 +01:00
Denys Vlasenko c64ffa2e2b nsloopup: tighten up length checks to avoid out-of-bounds reads
function                                             old     new   delta
parse_reply                                          979    1030     +51

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-11-07 20:30:35 +01:00
Denys Vlasenko 5450a8ed71 rpm: bail out if headers have abnormally large entry counts
function                                             old     new   delta
.rodata                                           104880  104906     +26
rpm_gettags                                          419     443     +24
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 2/0 up/down: 50/0)               Total: 50 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-11-07 20:02:28 +01:00
Denys Vlasenko f3ca54f688 tftp: add commented-out code with non-ISREG check
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-11-07 16:14:03 +01:00
Denys Vlasenko 56e9d36bb6 udhcpc[6]: check minimum packet size after reducing it to ip.tot_len
For DHCPv6, also require that all fields up until option array exist in the packet.
I did not find a definitive info that DHCPv6 requires at least one option
to be present, and the code appears to handle empty option array correctly.

function                                             old     new   delta
d6_recv_raw_packet                                   228     230      +2
d4_recv_raw_packet                                   500     501      +1
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 2/0 up/down: 3/0)                 Total: 3 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-11-07 14:05:35 +01:00
Denys Vlasenko b67f7b7d14 tftpd: make DIR argiment work for non-root too, strip leading /
function                                             old     new   delta
tftpd_main                                           573     589     +16

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-11-06 20:33:51 +01:00
Denys Vlasenko 7022247743 tftp(d): code shrink by not having two copies of option value
function                                             old     new   delta
tftp_protocol                                       1985    1938     -47

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-11-06 19:01:51 +01:00
Denys Vlasenko 1d363c609f tftpd: code shrink
function                                             old     new   delta
tftp_get_option                                      102      93      -9

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-11-06 18:09:10 +01:00
Denys Vlasenko 11edcd9eb0 tftpd: comment tweak
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-11-06 16:56:02 +01:00
Denys Vlasenko 1a80c25d30 tftpd: increase minimum supported block size to approx. 64
function                                             old     new   delta
tftp_protocol                                       2001    1985     -16

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-11-06 16:43:33 +01:00
Denys Vlasenko 8650079721 tftpd: improve sanitization of remote strings in error messages
function                                             old     new   delta
tftp_blksize_check                                    57      64      +7
tftp_protocol                                       2009    2001      -8
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 1/1 up/down: 7/-8)               Total: -1 bytes
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-11-06 16:18:47 +01:00
Michael Pfeifroth 2d6925708e awk: fix mktime() for dates beyond 2038
do_mktime() returned the result of mktime() as int. Since int is
32 bits wide even on LP64 systems, any time at or after
2038-01-19 03:14:08 UTC was truncated, even with a 64-bit time_t:

  $ TZ=UTC busybox awk 'BEGIN { printf "%.0f\n", mktime("2038 01 19 03 14 08") }'
  -2147483648

Return time_t instead and add a testcase.

function                                             old     new   delta
exec_builtin                                        1130    1136      +6
do_mktime                                            119     121      +2
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 2/0 up/down: 8/0)                 Total: 8 bytes

Signed-off-by: Michael Pfeifroth <micpf@westermo.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-11-06 15:33:22 +01:00
Denys Vlasenko 3a381903ce lzop: comment out unused variables
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-11-05 11:02:54 +01:00
Denys Vlasenko 7e4137b6bd init: set RC_REBOOT=YES if shutdown actions are running for reboot (not shutdown)
function                                             old     new   delta
.rodata                                           104866  104880     +14
check_delayed_sigs                                   341     354     +13
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 2/0 up/down: 27/0)               Total: 27 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-11-05 10:57:54 +01:00
Denys Vlasenko 5eee8017a8 ash: do not read past the text of an unset MAIL
Patch by Florian Schmaus <florian.schmaus@codasip.com>:

ash stores each variable as a single "NAME=value" string in var_text,
and accessor macros like mailval() simply skip over the "NAME=" prefix
(var_text + 5). Per the comment above them, they return the null
string for unset variables. That only works if an unset variable's
text still has a NUL where the value would start.

MAIL and MAILPATH are unset by default, and their initial texts are
"MAIL" and "MAILPATH". For "MAIL" (5 bytes including the NUL)
mailval() therefore points one byte past the end of the string. When
MAILPATH is not set, chkmail() falls back to mailval() and hands that
pointer to padvance_magic(), which parses the memory following "MAIL"
as a colon-separated list of mail files. This happens before every
interactive prompt, unless the user sets MAIL or MAILPATH.

What gets read there depends on the binary layout. In an x86_64
defconfig build "MAIL" is directly followed by "MAILPATH", so ash
stat()s ./MAILPATH before every prompt and prints "you have mail"
when a file of that name in the current directory changes. This
stat() of ./MAILPATH was already noticed in 2016 [1], and the
overread itself was recently reported after fuzzing ash with
AddressSanitizer [2].

The texts used to be "MAIL\0" and "MAILPATH\0", as they still are in
dash. Commit 8837c5dec4 ("ash: remove one redundant function,
improve string sharing, better field names") dropped the extra NUL
from all unset-by-default variables, so the literals become plain
strings the compiler can put in mergeable string sections. That is
fine for RANDOM, LC_ALL, LC_CTYPE and HISTFILE, whose values are only
read through lookupvar(), which checks VUNSET. But mailval() is
used without such a check.

Fix the out-of-bounds read by restoring the trailing NULs for MAIL
and MAILPATH, so that mailval() and mpathval() again yield "" for an
unset variable. This matches setvar(), which already allocates a
zeroed buffer of name length + 2 when unsetting a variable at
runtime. MAILPATH is not strictly affected, since mpathval() is only
used after mpathset(), but this keeps both accessors consistent.
Neither literal is shared with any other string, so the cost is two
bytes of .rodata:

function                                             old     new   delta
.rodata                                           102098  102100      +2

We ran into this on a CHERI [3, 4] system. CHERI's architectural
capabilities bound each memory region precisely, so it catches
out-of-bounds accesses that MMU-based protection misses. Here the
one-byte overread of the "MAIL" string literal is a capability length
violation, and every interactive ash dies with SIGSEGV on start-up.

1: https://github.com/gliderlabs/docker-alpine/issues/163
2: https://github.com/vda-linux/busybox_mirror/issues/47
3: https://www.cl.cam.ac.uk/research/security/ctsrd/cheri/
4: https://codasip.com/solutions/riscv-processor-safety-security/cheri/

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-10-22 07:31:22 +02:00
Denys Vlasenko 87e54246b6 swapon/off: revert the non-portable change made in 2014: use setmntent, not fopen
function                                             old     new   delta
swap_on_off_main                                     449     474     +25

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-10-22 06:36:05 +02:00
Denys Vlasenko daf8ec40e0 mount: allow longer /proc/mounts lines
Based on patch by Natanael Copa <ncopa@alpinelinux.org>:

Use a bigger buffer for getmntent_r so we can handle entries
with lines longer that 504 chars.

This solves issue when running `mount -o remount,rw ...` in a docker
container on Fedora 43.

ref: https://github.com/k0sproject/k0s/issues/6774
ref: https://lists.busybox.net/pipermail/busybox/2025-December/091859.html

function                                             old     new   delta
mount_main                                          1219    1259     +40
singlemount                                         1315    1323      +8
verbose_mount                                         94      96      +2
mount_it_now                                         358     359      +1
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 4/0 up/down: 51/0)               Total: 51 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-10-18 18:44:01 +02:00
Denys Vlasenko 38e2124b32 examples/var_service/dhcp_if/: improve selection of implied router
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-10-18 18:17:22 +02:00
Denys Vlasenko e58cb22366 volume_id: code shrink
function                                             old     new   delta
resolve_mount_spec                                    87     158     +71
mount_main                                          1211    1219      +8
fsck_device                                          453     451      -2
findfs_main                                           76      74      -2
blkid_main                                            41      39      -2
display_uuid_cache                                   109     105      -4
get_devname_from_uuid                                 56       -     -56
get_devname_from_label                                62       -     -62
------------------------------------------------------------------------------
(add/remove: 0/2 grow/shrink: 2/4 up/down: 79/-128)           Total: -49 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-10-18 16:55:01 +02:00
Denys Vlasenko bad78f5e96 fsck: code shrink, improve code comments on resolve_mount_spec() alloc
function                                             old     new   delta
create_fs_device                                     155     140     -15

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-10-18 16:31:49 +02:00
Natanael Copa 6fb8efcd6c fsck: resolve LABEL=.../UUID=... spec to device
function                                             old     new   delta
fsck_device                                          433     453     +20

Signed-off-by: Natanael Copa <ncopa@alpinelinux.org>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-10-18 15:34:07 +02:00
Sören Tempel 9d961aff6f Install lsblk to /bin instead of /usr/bin
On Alpine, the util-linux lsblk utility is installed in /bin and
since BusyBox only gained support for that applet recently, we
should make sure to install it to the same location.

Otherwise, the BusyBox symlink is not overwritten by the lsblk pkg.

Signed-off-by: Sören Tempel <soeren+git@soeren-tempel.net>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-10-12 12:35:36 +02:00
Natanael Copa 531d9db7b4 app location for cpio, vi and lspci
Adjust location to where alpine linux installs them

Signed-off-by: Natanael Copa <ncopa@alpinelinux.org>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-10-12 12:34:42 +02:00
Sören Tempel ec9036610f nologin: Install applet to /sbin instead of /usr/sbin
This is required to retain compatibility with our old custom nologin
applet written in C which was also installed to /sbin.

Compatibility with the old path is required because login shell paths
are hardcoded in /etc/passwd.

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-10-12 12:34:42 +02:00
Sören Tempel 2e57f66cba adduser: default to /sbin/nologin as shell for system accounts
Signed-off-by: Sören Tempel <soeren+git@soeren-tempel.net>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-10-12 12:34:42 +02:00
Lauri Tirkkonen 30a8277fa0 blkdiscard: ship link to /sbin instead of /usr/bin
util-linux ships blkdiscard in /sbin, so follow what it does.

Link: https://git.kernel.org/pub/scm/utils/util-linux/util-linux.git/tree/sys-utils/Makemodule.am?id=5a75fb2b9e384c61a4b2afd13fe9bba219d5bd93#n194
Signed-off-by: Lauri Tirkkonen <lauri@hacktheplanet.fi>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-10-12 12:34:42 +02:00
Denys Vlasenko 45ad4ce552 tests: fix tarball creation
Without this patch, the chmod 644 invocation takes away the executable
bit from the input_dir directory, thus preventing the chmod of the files
within the input_dir directory (due to lack of x-bit).

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-10-12 00:00:55 +02:00
Sören Tempel de40fe3350 tests: musl doesn't seem to recognize UTC0 as a timezone
UTC works though.

TODO: Figure out if musl /should/ regonize UTC0.

Signed-off-by: Sören Tempel <soeren+git@soeren-tempel.net>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-10-11 23:51:14 +02:00
Natanael Copa b58d7e51b0 Add flag for not following symlinks when recursing
function                                             old     new   delta
.rodata                                             7934    7967     +33
diff_longopts                                        253     270     +17
packed_usage                                        1704    1720     +16
diff_main                                           1665    1662      -3
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 3/1 up/down: 66/-3)              Total: 63 bytes

Signed-off-by: Natanael Copa <ncopa@alpinelinux.org>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-10-11 23:46:42 +02:00
Sören Tempel 97e373643d hexdump: skip additional hexdump test on big-endian systems
This one fails on s390x.

Signed-off-by: Sören Tempel <soeren+git@soeren-tempel.net>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-10-11 23:39:01 +02:00
Natanael Copa 7476cd280d hexdump: fix regression with -n4 -e '"%u"'
Fix bug introduced in busybox 1.37.0 that broke kernel builds.

Fixes commit e2287f99fe (od: for !DESKTOP, match output more closely
to GNU coreutils 9.1, implement -s)

Signed-off-by: Natanael Copa <ncopa@alpinelinux.org>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-10-11 23:36:27 +02:00
Natanael Copa b9f5de0352 wget: add header Accept: */*
Some servers (like https://netfilter.org) returns failure if the Accept
header is missing. Both GNU wget and curl adds this header, so make
busybox do the same.

fixes: https://bugs.busybox.net/show_bug.cgi?id=15982

function                                             old     new   delta
wget_main                                           3120    3144     +24
.rodata                                            79296   79310     +14
wget_user_headers                                     76      84      +8
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 3/0 up/down: 46/0)               Total: 46 bytes
   text	   data	    bss	    dec	    hex	filename
 825278	  14260	   2008	 841546	  cd74a	busybox_old
 825324	  14260	   2008	 841592	  cd778	busybox_unstripped

Signed-off-by: Natanael Copa <ncopa@alpinelinux.org>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-10-11 23:36:27 +02:00
Denys Vlasenko f0e5be9fbc awk: fix handling of literal backslashes in replacement
Follow actual gawk behavior.
    https://www.gnu.org/software/gawk/manual/html_node/Gory-Details.html
Erm... wait. Follow *actual* gawk behavior - as seen in testing,
because even Gory-Details.html do not tell the whole awful truth.

function                                             old     new   delta
awk_sub                                              550     658    +108

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-10-11 23:15:35 +02:00
Denys Vlasenko 538499b65a ash,hush: fix read builtin versus already-handled signal
function                                             old     new   delta
builtin_read                                         178     205     +27
shell_builtin_read                                  1340    1350     +10
pgetc                                                623     633     +10
dotrap                                               157     164      +7
check_and_run_traps                                  278     285      +7
readcmd                                              227     222      -5
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 5/1 up/down: 61/-5)              Total: 56 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-10-11 18:17:43 +02:00
Denys Vlasenko fcdc004c5c ash: docunebt that "timed out waiting for input" goes to stdout
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-10-11 16:05:24 +02:00
Denys Vlasenko 049ae38950 ash,hush: print sugnal-related "beautification" (^C etc) to stderr, not stdout
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-10-11 15:54:21 +02:00
Denys Vlasenko 1c7e871e0a less: accept/ignore -T TAGFILE
Patch by Sören Tempel <soeren@soeren-tempel.net>

This option is passed by mandoc(1), while we don't implement the
actual functionality here, this patch allows using tagfile support
with mandoc(1) when a more feature-full less(1) implementation is
installed.

Otherwise, we would have to detect support for -T option in the
pager at run-time in mandoc(1), which would occur run-time costs.
Note that other option (-s and -X) are already ignored by BusyBox
less(1), so this seems like a good solution for mandoc(1) compat.

function                                             old     new   delta
less_main                                           2062    2064      +2
.rodata                                           104845  104847      +2

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-10-11 15:52:33 +02:00
Denys Vlasenko 8d4ac0d17b udhcpc: code shrink by reusing "deconfig" code path
function                                             old     new   delta
udhcpc_main                                         2544    2501     -43

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-10-11 15:52:33 +02:00
Denys Vlasenko 15e0ea385d udhcpc6: code shrink by reusing "deconfig" code path
function                                             old     new   delta
udhcpc6_main                                        2772    2651    -121

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-10-11 15:52:33 +02:00
Jake Buchholz Göktürk a65bea40f4 udhcpc6: restart acquisition after a zero valid lifetime
A Reply with a zero valid lifetime revokes an address or delegated
prefix. The current client instead applies its minimum lease time and
keeps renewing the revoked lease. When both IA_NA and IA_PD are requested,
the zero can also be replaced by the other IA's nonzero lifetime.

Check the lifetimes of requested IAs before combining or clamping them.
On zero, run deconfig and return to INIT_SELECTING. Clear the requested
address hint, remaining lease, elapsed time and packet counter. Use the
same three-second delay as the existing DHCPv6 NAK recovery path to avoid
repeatedly soliciting an unusable lease. Deconfiguration happens
immediately; the delay applies only to restarting acquisition. This is
an existing implementation convention, not an RFC requirement. Do not
report bound or renew, or honor quit-after-lease, for an unusable lease.

Use option_mask32, which includes the default address request and the
-r no/-l overrides. A zero preferred lifetime with a positive valid
lifetime remains accepted. Stateful address and prefix acquisition
still share one client state: revoking either restarts both.

This addresses the existing zero-lease TODO. It does not implement
independent IA renewal or processing of multiple leases per IA.
Existing partial-Reply handling is unchanged: if a requested companion
IA is missing, the Reply is ignored before this revocation check.

Tested on aarch64: address and prefix revocation, combined leases with
one or both lifetimes zero, replacement acquisition and renewal,
zero first Reply, persistent zero Replies, quit-after-lease, deprecated
addresses, and stateless Information-request. The unpatched baseline
continues renewing revoked state.

Native aarch64, GCC 15.2.0, Alpine configuration; relative to
the preceding patch in this series. Data and BSS are unchanged.

bloat-o-meter:
function                                             old     new   delta
udhcpc6_main                                        3024    3120     +96
.rodata                                            69449   69484     +35
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 2/0 up/down: 131/0)             Total: 131 bytes

Signed-off-by: Jake Buchholz Göktürk <tomalok@gmail.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-10-11 03:08:34 +02:00
Jake Buchholz Göktürk 57c5bba044 udhcpc6: send proper Rebind messages
The REBINDING state uses the Renew packet builder, so its multicast
fallback sends another Renew containing the original server ID. It
cannot ask a different server to extend the lease.

Reuse the existing builder for both message types. Send D6_MSG_REBIND
without a server ID in REBINDING, preserving the client options and
IA_NA/IA_PD contents. Start a new transaction and reset elapsed time
when entering that state; retransmissions retain the transaction ID.
This follows RFC 9915 section 18.2.5 and resolves the TODO in the
REBINDING state asking whether send_d6_renew() should use D6_MSG_REBIND
instead of D6_MSG_RENEW.

Keep the renewal schedule, retry limits, and multicast option behavior
unchanged.

Tested on aarch64 with Alpine's configuration: initial acquisition and
Renew, server failover with IA_NA, IA_PD, and both, Rebind retransmissions,
and stateless Information-request. The unpatched tree loses its lease
in the same failover test. Packet captures verify the message type,
options, transaction ID, and elapsed time.

Native aarch64, GCC 15.2.0, Alpine configuration; relative to
the preceding patch in this series. Data and BSS are unchanged.

bloat-o-meter:
function                                             old     new   delta
static.send_d6_renew                                 208     256     +48
udhcpc6_main                                        3000    3024     +24
.rodata                                            69447   69449      +2
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 3/0 up/down: 74/0)               Total: 74 bytes

Signed-off-by: Jake Buchholz Göktürk <tomalok@gmail.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-10-11 02:41:42 +02:00
Jake Buchholz Göktürk 89032255bb udhcp: export IPv6 preferred_lifetime to the script
Export the DHCPv6 preferred address lifetime alongside the existing
valid lifetime in lease.

function                                             old     new   delta
option_to_env                                        711     739     +28
.rodata                                           104781  104808     +27
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 2/0 up/down: 55/0)               Total: 55 bytes

Signed-off-by: Jake Buchholz Göktürk <tomalok@gmail.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-10-11 02:36:32 +02:00
Ron Yorston 5e57539acb test: fix POSIX -nt and -ot when "older" is missing
These should evaluate true if the newer file exists and the older is
missing or older, but it was never true if older is missing.

Note: 'test X -nt Y' is identical to 'test Y -ot X'

  https://pubs.opengroup.org/onlinepubs/9799919799/utilities/test.html

function                                             old     new   delta
binop                                                593     634     +41
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 1/0 up/down: 41/0)               Total: 41 bytes

Signed-off-by: Avi Halachmi (:avih) <avihpit@yahoo.com>
Signed-off-by: Ron Yorston <rmy@pobox.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-10-10 18:29:56 +02:00
Ron Yorston aeaa7f547c ash: PSSYNTAX: preserve \\ in addition to \$
'\\t' in PS1 was incorrectly displayed as a timestamp instead of
the intended '\t' because '\\' was not preserved.

function                                             old     new   delta
readtoken1                                          3072    3079      +7
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 1/0 up/down: 7/0)                 Total: 7 bytes

Signed-off-by: Avi Halachmi (:avih) <avihpit@yahoo.com>
Signed-off-by: Ron Yorston <rmy@pobox.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-10-10 18:28:51 +02:00
Denys Vlasenko 32653c392c libarchive: comment tweak
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-10-09 16:56:50 +02:00
Denys Vlasenko 382008b3f0 tar: protect against Symlink+Hardlink attack
function                                             old     new   delta
create_links_from_list                                93     190     +97

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-10-09 16:45:23 +02:00
Denys Vlasenko 5da20102b5 tar: ".." is also an unsafe filename, treat as such
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-10-09 15:09:26 +02:00
Denys Vlasenko a040aa2826 ash: follow bash in allowing multiple !s: "! ! CMD" is the same as "CMD"
function                                             old     new   delta
pipeline                                             167     165      -2

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-10-09 13:36:11 +02:00
Denys Vlasenko 4a9fe5a0c2 ash: fix !BASH_COMPAT build, tweak variable names, add comments
The work to improve "wait -n" is based on patches by
    Luiz Angelo Daros de Luca <luizluca@gmail.com>
and
    Dominique Martinet <dominique.martinet@atmark-techno.com>

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-10-09 12:26:51 +02:00
Denys Vlasenko e3e1ad1587 ash: fix "wait -n PID %JOBSPEC" behavior
function                                             old     new   delta
dowait_n                                               -     565    +565
waitcmd                                              346     569    +223
getjob_match_last_pid                                  -      29     +29
waitforjob                                           100     103      +3
showjobs                                              56      59      +3
dowait                                               557       -    -557
------------------------------------------------------------------------------
(add/remove: 2/1 grow/shrink: 3/0 up/down: 823/-557)          Total: 266 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-10-07 23:45:35 +02:00
Denys Vlasenko 30f2f883bd ash: fix "wait -n" behavior wrt already-exited jobs
function                                             old     new   delta
waitcmd                                              318     346     +28
kill_main                                            907     919     +12
dowait                                               553     557      +4
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 3/0 up/down: 44/0)               Total: 44 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-10-07 11:15:37 +02:00
Denys Vlasenko 730f515626 ash: fix !ASH_BASH_COMPAT build
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-10-07 00:13:59 +02:00
Denys Vlasenko b829bba950 httpd: do not try to use obviously bogus password from /etc/passwd
If password is 'x' or '*' and yet, /etc/shadow has no entry,
do not run the crypt machinery - go to the next entry.

function                                             old     new   delta
check_user_passwd                                    444     462     +18

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-10-06 00:00:32 +02:00
Ron Yorston f15a204bb2 xxd: '-p -c 0' outputs a single line
vim's xxd allows the combination of options '-p -c 0' to output
a single line of text [1].  A use case is handling cryptographic
material [2].

Add this feature to BusyBox xxd.

[1] https://github.com/vim/vim/pull/9524
[2] https://stackoverflow.com/questions/42192490/aes-cbc-incorrect-usage

function                                             old     new   delta
xxd_main                                            1496    1526     +30
packed_usage                                       35515   35511      -4
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 1/1 up/down: 30/-4)              Total: 26 bytes

Signed-off-by: Ron Yorston <rmy@pobox.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-10-05 21:18:44 +02:00
Denys Vlasenko db7dfff800 ash: make "wait -n" pick up last job, if there is no running processes
This is bash compat

function                                             old     new   delta
waitcmd                                              281     318     +37
dowait                                               546     553      +7
waitforjob                                            98     100      +2
showjobs                                              54      56      +2
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 4/0 up/down: 48/0)               Total: 48 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-10-05 20:43:43 +02:00
Denys Vlasenko ef673ec65a ash: propagate exitstatus to wait -n for correct $? value
function                                             old     new   delta
dowait                                               533     532      -1

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-10-05 17:40:47 +02:00
Denys Vlasenko f4406b2d09 ash: rename "int err" in waitproc() to "pid"
function                                             old     new   delta
dowait                                               530     533      +3

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-10-05 17:40:47 +02:00
Denys Vlasenko 3920b0a994 ash: dowait: remove incorrect looping
Prev code:

         rpid = 1;
         do {
                 pid = waitone(block, jp);
                 rpid &= !!pid; <<<<<<<<<<<<<<<<<< HERE
                 if (!pid || (jp && jp->state != JOBRUNNING))
                         block = DOWAIT_NONBLOCK;
         } while (pid >= 0);
         return rpid;

If we got pid == 0, it happens in exactly one case:
we did waitpid(WNOHANG), got 0 ("children exist but none yet
changed its state"), then waited for a signal and got one,
which wasn't SIGCHLD.

The above behavior is requested by only one caller: waitcmd()
- the "wait" builtin.

"wait" builtin is required to be interruptible by signals and
to set exitcode to (128 + sig).

Therefore, if we got pid == 0, we don't need to wait
for any more processes. We need to return to waitcmd()
and let it set $? accordingly.

Instead, we do yet another loop.

I'm not saying that we know
that there are no more processes that finished.

I'm saying we don't care at this point: we know
that we are "wait" builtin and we got interrupted by a signal.

Fix this by not looping if "pid == 0" indicates we got a signal.
ONLY loop if we got a pid > 0 and we either do not wait for a specific job,
or this scpecific job is still RUNNING.

function                                             old     new   delta
dowait                                               546     530     -16

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-10-05 17:40:47 +02:00
Denys Vlasenko e054f9fb4b ash: waiting machinery: add comments explaining the code
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-10-05 17:40:47 +02:00
Denys Vlasenko cdd442ebd2 ash: waitproc: unobfuscate and explain what the code does
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-10-05 17:40:47 +02:00
Wojtek Kaniewski 85efaab179 id: Fix output in case of groups error
On a severely constrained system (m68k-nommu) I got confusing output from
`id` command:

    ~ # id
    uid=0 gid=0id: can't get groups

After this change it's a bit more readable:

    ~ # id
    uid=0 gid=0
    id: can't get groups

function                                             old     new   delta
id_main                                              474     484     +10

Signed-off-by: Wojtek Kaniewski <wojtekka@toxygen.net>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-10-05 00:52:46 +02:00
Denys Vlasenko 6644e8376e ash simplify PS1 initialization
function                                             old     new   delta
.rodata                                           104788  104781      -7
init                                                 432     422     -10
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 0/2 up/down: 0/-17)             Total: -17 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-10-05 00:36:08 +02:00
Denys Vlasenko 93bacaa199 ash: remove stray semicolon to fix prompt in !EDITING_FANCY_PROMPT case
Patch by Robert Sandholzer.

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-10-05 00:35:36 +02:00
Michele Dionisio via busybox e65b560038 chrt: add -R to set SCHED_RESET_ON_FORK
Add the -R option, as in util-linux's chrt, which ORs the
SCHED_RESET_ON_FORK flag into the policy passed to sched_setscheduler().
Children created by fork() then do not inherit privileged scheduling
policies and priorities.

Provide a fallback definition of SCHED_RESET_ON_FORK for libcs whose
headers lack it, so the #ifdef around the flag masking in the -p query
path is no longer needed.

function                                             old     new   delta
chrt_main                                            474     501     +27
packed_usage                                       36406   36428     +22
.rodata                                           104787  104788      +1
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 3/0 up/down: 50/0)               Total: 50 bytes

Signed-off-by: Michele Dionisio <michele.dionisio@gmail.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-10-04 19:41:03 +02:00
Karthik D K c6c7ab979e libbb: enable fixed 4k pagesize on RISC-V
function             old     new   delta
dd_main             2728    2760     +32
time_main           1300    1288     -12
procps_scan          884     868     -16
devmem_main          648     632     -16
hexedit_main        1416    1392     -24
mkswap_main          408     372     -36
alloc_buf             64       -     -64
------------------------------------------------------------------------------
(add/remove: 0/1 grow/shrink: 1/5 up/down: 32/-168)  Total: -136 bytes

Signed-off-by: Karthik D K <karthikdk1998@gmail.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-10-04 18:40:20 +02:00
Harald van Dijk f96d33d28a printf: fix handling of omitted arguments
For numeric formats, this is meant to behave as a "0" literal zero
argument, not an "" empty string argument.

Add a test to ensure that an explicit "" empty string argument still is
treated as an error.

function                                             old     new   delta
printf_main                                          837    1209    +372
print_direc                                          432       -    -432
------------------------------------------------------------------------------
(add/remove: 0/1 grow/shrink: 1/0 up/down: 372/-432)          Total: -60 bytes

Signed-off-by: Harald van Dijk <harald@gigawatt.nl>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-10-04 17:48:06 +02:00
Denys Vlasenko b68024b2b8 fatlabel: do not require the 55,AA "bootable" signature
function                                             old     new   delta
fatlabel_main                                        396     384     -12

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-10-04 17:27:43 +02:00
Denys Vlasenko 4da3f6df05 fatlabel: require dir_entries = 0 in FAT32 check; fix typos
function                                             old     new   delta
fatlabel_main                                        392     396      +4

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-10-04 17:00:56 +02:00
Denys Vlasenko 4366618a25 tls_aes: use bytes for AES state
This is not a code size win on i686. It is "accidentally" a win on x86_64:
my gcc stops trying to use SSE operations for xoring, which is smaller code.

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-10-04 03:03:37 +02:00
Denys Vlasenko ca70514d85 tftp: fix maximum allowed block size from 65564 to 65464 (location #2)
Patch by Valentin. He did send the patch. Which I didn't notice
in the email, decided "bug clear enough, can do it myself",
missed the second location with a buggy constant,
forgot to attribute the fix, and made *two* typos in the commit message.
:(

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-10-04 01:28:33 +02:00
Denys Vlasenko 0625fac9fe tftp: fix maximum allowed blcok size form 65564 to 65464
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-10-03 15:26:15 +02:00
Denys Vlasenko 14f6b6b580 bunzip2: reject blocks whose run-length count overflows
Based ob the patch by Matt Turner <mattst88@gmail.com>:
> get_next_block() accumulates a run length in the unsigned 32-bit runCnt:
>
>         runCnt += (runPos << nextSym);
>
> A crafted stream with a long enough RUNA/RUNB sequence can drive runCnt
> up to ~2^32. Once it is that large, the existing guard
>
>         if (dbufCount + runCnt > bd->dbufSize)
>
> is bypassed: dbufCount + runCnt overflows the unsigned addition and
> wraps to a small value, so the check passes. The following
> byteCount[tmp_byte] += runCnt then overflows byteCount[] (an int) to a
> negative value. The inverse Burrows-Wheeler sort loop computes negative
> cumulative offsets from it and writes before the start of dbuf[], an
> out-of-bounds heap write (confirmed with AddressSanitizer as a write 48
> bytes before the dbuf allocation).

function                                             old     new   delta
get_next_block                                      1452    1458      +6

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-10-02 20:35:04 +02:00
Denys Vlasenko 904511662e nmeter: make it able to sleep for hours: -d %((60*60*1000))
function                                             old     new   delta
nmeter_main                                          786    1031    +245
packed_usage                                       36379   36406     +27
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 2/0 up/down: 272/0)             Total: 272 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-10-01 17:28:51 +02:00
Denys Vlasenko c824119226 nmeter: document why %[nIF] format prepends a space
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-10-01 15:48:05 +02:00
Denys Vlasenko e6302b2711 swapon: with no arguments, show /proc/swaps (mimic util-linux 2.41.1)
function                                             old     new   delta
swap_on_off_main                                     419     449     +30

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-09-29 00:00:42 +02:00
Denys Vlasenko e8cb0a1d14 fdisk: util-linux compat wrt meaning of -u
function                                             old     new   delta
menu                                                 261     282     +21
.rodata                                           104779  104787      +8
packed_usage                                       36390   36379     -11
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 2/1 up/down: 29/-11)             Total: 18 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-09-28 18:07:32 +02:00
Denys Vlasenko c1289d58d5 fdisk: add a test of adding a 1-sector primary partition
function                                             old     new   delta
packed_usage                                       36323   36390     +67
read_int                                             450     457      +7
read_line_input                                     2664    2669      +5
get_boot                                            1426    1423      -3
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 3/1 up/down: 79/-3)              Total: 76 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-09-28 17:24:03 +02:00
Denys Vlasenko 928b0384cf fdisk: more readable code in read_extended_chain()
function                                             old     new   delta
get_boot                                            1426    1423      -3

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-09-28 12:22:10 +02:00
Denys Vlasenko ccf1e30fa2 fdisk: consider partition empty only when it's all-zeros, not merely type 0
Our own message in the source says that Linux does not consider type 0
as "empty". (Linux thinks that size of 0 sectors means "empty").

function                                             old     new   delta
verify                                               726     767     +41
wrong_p_order                                         86     119     +33
get_geometry                                         437     460     +23
get_boot                                            1412    1426     +14
fill_bounds                                          115     124      +9
x_dos_print_disklabel                                227     232      +5
delete_partition                                     334     337      +3
add_logical                                          106     109      +3
fdisk_main                                          2590    2576     -14
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 8/1 up/down: 131/-14)           Total: 117 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-09-28 11:44:00 +02:00
Denys Vlasenko bfdf3560d6 fdisk: DOS compat flag off by default - mimic util-linux 2.41.1
function                                             old     new   delta
fdisk_main                                          2610    2590     -20

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-09-28 11:16:02 +02:00
Denys Vlasenko 4c9b0e45da fdisk: in add_partition(), only fully zeroed partition entry is free
function                                             old     new   delta
add_partition                                       1038    1041      +3

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-09-28 04:04:56 +02:00
Denys Vlasenko 152c6227d0 fdisk: simplify new_partition()
function                                             old     new   delta
input_partition_number                                 -      73     +73
fdisk_main                                          2547    2610     +63
get_partition                                         73       -     -73
get_nonexisting_partition                            100       -    -100
.rodata                                           104879  104779    -100
------------------------------------------------------------------------------
(add/remove: 1/2 grow/shrink: 1/1 up/down: 136/-273)         Total: -137 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-09-28 03:23:26 +02:00
Denys Vlasenko 659644d8d6 fdisk: explain how extended partitions work on-disk
Improve messages about "DOS compatibility flag"

function                                             old     new   delta
menu                                                 231     261     +30
valid_55AA_signature                                   -      26     +26
fdisk_main                                          2534    2547     +13
get_boot                                            1406    1412      +6
valid_part_table_flag                                 26       -     -26
.rodata                                           104913  104879     -34
------------------------------------------------------------------------------
(add/remove: 1/1 grow/shrink: 3/1 up/down: 75/-60)             Total: 15 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-09-28 02:49:08 +02:00
Denys Vlasenko 25c50c4805 fdisk: remove "devfs kludge"
function                                             old     new   delta
partname                                             184     136     -48

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-09-27 23:21:23 +02:00
Denys Vlasenko 03293bc06c fdisk: remove dead code in open_list_and_close()
delete_partition() which deals with extended partition is unnecessary
since we are inside "fdisk -l".
"if (LABEL_IS_AIX) ..." is false since only after successful get_boot()
we can have a detected AIX label.

function                                             old     new   delta
open_list_and_close                                  424     392     -32

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-09-27 22:57:52 +02:00
Denys Vlasenko 3fc725d413 fdsik: reduce local char mesg[256] to [64]
function                                             old     new   delta
add_partition                                       1246    1038    -208

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-09-27 22:50:02 +02:00
Denys Vlasenko dcb8ae589b fdisk: group menu functions together
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-09-27 22:31:46 +02:00
Denys Vlasenko ef63f4dec2 fdisk: standardize on XYZ_print_disklabel() as the function for 'p'
list_disk_name_and_sizes() shouldn't be used by gpt's print_disklabel(),
just use it unconditionally for all partition types.

function                                             old     new   delta
static.print_disklabel                                 -     775    +775
x_dos_print_disklabel                                  -     227    +227
print_disk_name_and_sizes                              -      80     +80
print_disk_geometry                                    -      66     +66
open_list_and_close                                  419     424      +5
.rodata                                           104928  104913     -15
list_disk_geometry                                    71       -     -71
list_disk_name_and_sizes                              80       -     -80
x_list_table                                         227       -    -227
static.list_table                                    775       -    -775
------------------------------------------------------------------------------
(add/remove: 4/4 grow/shrink: 1/1 up/down: 1153/-1168)        Total: -15 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-09-27 20:32:07 +02:00
Denys Vlasenko 6853c796be fdisk: rename bsd_select() -> if_osf_label_loop_in_menu_until_r()
Much clearer to read the call site.
While at it, shiffle fdisk_osf.c to reduce forward references.
Shorten sprintf() in xbsd_get_part_index().

function                                             old     new   delta
if_osf_label_loop_in_menu_until_r                      -    1546   +1546
xbsd_get_part_index                                   69      67      -2
bsd_select                                          1546       -   -1546
------------------------------------------------------------------------------
(add/remove: 1/1 grow/shrink: 0/1 up/down: 1546/-1548)         Total: -2 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-09-27 19:44:34 +02:00
Denys Vlasenko 4839711dce fdisk: consistently use uint8_t (not char) for binary data
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-09-27 19:00:36 +02:00
Denys Vlasenko e5588888c8 fdisk: rename struct partition to dos_partition
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-09-27 18:34:08 +02:00
Denys Vlasenko 8ce86eb361 fdisk: show "Changes will remain in memory only" more prominently
function                                             old     new   delta
.rodata                                           104735  104928    +193
fdisk_main                                          2522    2534     +12
create_doslabel                                       99      93      -6
msg_part_already_defined                              61       -     -61
msg_building_new_label                               142       -    -142
------------------------------------------------------------------------------
(add/remove: 0/2 grow/shrink: 2/1 up/down: 205/-209)           Total: -4 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-09-27 18:29:42 +02:00
Denys Vlasenko 8c43e2409e fdisk: make write_table_and_exit() NORETURN
function                                             old     new   delta
write_table_and_exit                                   -     153    +153
fdisk_main                                          2537    2522     -15
write_table                                          159       -    -159
------------------------------------------------------------------------------
(add/remove: 1/1 grow/shrink: 0/1 up/down: 153/-174)          Total: -21 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-09-27 18:10:34 +02:00
Denys Vlasenko fbfc949b26 fdisk: remove get_boot() -> create_doslabel() -> get_boot() recursion
It works, but
get_boot() [table is bad] -> create_doslabel() -> get_boot(CREATE_EMPTY_DOS)
is a mind bender

function                                             old     new   delta
dos_reset_primary_partition_info                       -      73     +73
get_existing_partition                               113     110      -3
fdisk_main                                          2543    2537      -6
create_doslabel                                      108      99      -9
get_boot                                            1477    1406     -71
------------------------------------------------------------------------------
(add/remove: 1/0 grow/shrink: 0/4 up/down: 73/-89)            Total: -16 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-09-27 18:02:02 +02:00
Denys Vlasenko 946aba349c fdisk: remove vestiges of SUN and SGI labels support
function                                             old     new   delta
menu                                                 262     231     -31
.rodata                                           104770  104735     -35
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 0/2 up/down: 0/-66)             Total: -66 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-09-27 16:46:13 +02:00
Denys Vlasenko e1aeba03f4 fdisk: remove SUN and SGI labels support - obsolete (20+ years)
function                                             old     new   delta
static.list_table                                      -     775    +775
packed_usage                                       36304   36323     +19
read_int                                             434     450     +16
fdisk_swap32                                           3       -      -3
open_list_and_close                                  431     419     -12
verify                                               742     726     -16
partition_type                                        49      28     -21
get_partition                                        100      73     -27
menu                                                 293     262     -31
read_maybe_empty                                      38       -     -38
verify_sun_cmp                                        39       -     -39
get_boot                                            1532    1477     -55
sun_sys_types                                         56       -     -56
write_table                                          251     159     -92
delete_partition                                     432     334     -98
set_sun_partition                                    100       -    -100
get_geometry                                         538     437    -101
print_buffer                                         102       -    -102
fetch_sun                                            207       -    -207
check_sun_label                                      208       -    -208
sun_autoconfigure_scsi                               395       -    -395
verify_sun                                           447       -    -447
sun_drives                                           456       -    -456
new_partition                                       1066       -   -1066
list_table                                          1370       -   -1370
fdisk_main                                          4622    2543   -2079
.rodata                                           107469  104770   -2699
------------------------------------------------------------------------------
(add/remove: 1/13 grow/shrink: 2/11 up/down: 810/-9718)     Total: -8908 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-09-27 16:38:02 +02:00
Denys Vlasenko 274a087cdc *: users of get_volume_size_in_bytes() should open their file O_RDWR
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-09-26 19:52:10 +02:00
Denys Vlasenko 69dd61ccbf nc: show connect() errors always, not only with -v or -vv
function                                             old     new   delta
display                                             1485    1481      -4
nc_main                                             1018     992     -26
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 0/2 up/down: 0/-30)             Total: -30 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-09-26 19:45:56 +02:00
Denys Vlasenko 13562b9351 volume_id: add FAST_FUNCs
function                                             old     new   delta
volume_id_set_unicode16                              167     181     +14
volume_id_probe_btrfs                                131     139      +8
volume_id_probe_vfat                                 824     830      +6
volume_id_probe_sysv                                 188     193      +5
volume_id_probe_romfs                                 97     100      +3
volume_id_probe_iso9660                              315     316      +1
volume_id_probe_nilfs                                 97      96      -1
volume_id_probe_lfs                                   59      58      -1
volume_id_probe_ext                                  122     121      -1
volume_id_probe_erofs                                 86      85      -1
volume_id_probe_reiserfs                             243     241      -2
volume_id_probe_linux_raid                           128     126      -2
volume_id_free_buffer                                 67      65      -2
volume_id_probe_xfs                                   98      95      -3
volume_id_probe_ocfs2                                107     104      -3
volume_id_probe_linux_swap                           248     245      -3
volume_id_probe_jfs                                  107     104      -3
volume_id_probe_bcache                               104     101      -3
volume_id_set_label_string                            81      77      -4
volume_id_probe_ubifs                                 64      60      -4
volume_id_probe_squashfs                              83      79      -4
volume_id_probe_minix                                 82      78      -4
volume_id_probe_f2fs                                 104     100      -4
volume_id_probe_cramfs                                64      60      -4
volume_id_get_buffer                                 372     368      -4
volume_id_probe_luks                                  89      83      -6
volume_id_probe_udf                                  538     531      -7
volume_id_probe_exfat                                282     275      -7
volume_id_set_label_unicode16                         31      23      -8
volume_id_probe_ntfs                                 285     277      -8
volume_id_probe_all                                  123     113     -10
volume_id_set_uuid                                   178     166     -12
volume_id_probe_hfs_hfsplus                          494     470     -24
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 6/27 up/down: 37/-135)          Total: -98 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-09-24 16:20:36 +02:00
Denys Vlasenko 30d2839a7c fatlabel: new applet
function                                             old     new   delta
fatlabel_main                                          -     392    +392
.rodata                                           107413  107469     +56
applet_names                                        2885    2894      +9
applet_main                                         1660    1664      +4
packed_usage                                       36307   36304      -3
swaplabel_main                                       274     270      -4
------------------------------------------------------------------------------
(add/remove: 2/0 grow/shrink: 3/2 up/down: 461/-7)            Total: 454 bytes
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-09-24 11:52:58 +02:00
Denys Vlasenko f5c0543fd1 swaplabel: new applet
While at it, make get_volume_size_in_bytes() messages more informative;
do not write to file unless _have to_ extend it.

function                                             old     new   delta
swaplabel_main                                         -     274    +274
.rodata                                           107344  107413     +69
get_volume_size_in_bytes                             221     262     +41
bb_SWAPSPACE2                                          -      10     +10
applet_names                                        2875    2885     +10
packed_usage                                       36298   36307      +9
applet_main                                         1656    1660      +4
applet_install_loc                                   207     208      +1
SWAPSPACE2                                            10       -     -10
------------------------------------------------------------------------------
(add/remove: 3/1 grow/shrink: 6/0 up/down: 418/-10)           Total: 408 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-09-24 02:21:18 +02:00
Denys Vlasenko d3c8cfa674 tr: special-case "\-" before trying to parse it as escape
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-09-23 06:41:53 +02:00
Ron Yorston 0e09d2f857 tr: an escaped dash doesn't indicate a range
Commit d683c5c2f1 (tr: support octal ranges) broke the previous
behaviour that an escaped dash doesn't indicate a range:
'[p\-r]' should match 'p', '-' or 'r', not 'p', 'q' or 'r'.

Add a special case to handle this.

function                                             old     new   delta
expand                                               641     657     +16
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 1/0 up/down: 16/0)               Total: 16 bytes

Signed-off-by: Ron Yorston <rmy@pobox.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-09-23 06:41:53 +02:00
Denys Vlasenko a21eaf440d *: fix Unicode damage
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-09-23 02:53:30 +02:00
Denys Vlasenko c9e11ef570 telnet: make put_iac_subopt_XYZ() more readable
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-09-23 02:23:46 +02:00
Denys Vlasenko 5cea24cf6c telnet: remove superfluous bit clearing
function                                             old     new   delta
write_to_net                                         625     621      -4

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-09-23 02:07:23 +02:00
Denys Vlasenko bf9ebfe168 wget: fix progress bar and message placement on unexpected EOF (and retry)
Correct behavior: "wget: connection closed..." on new line:

$ wget http://127.0.0.1/50g -O/dev/null
Connecting to 127.0.0.1 (127.0.0.1:80)
saving to '/dev/null'
null                   8% |**                       | 4531M  0:00:30 ETA
wget: connection closed at byte 4751158460
Connecting to 127.0.0.1 (127.0.0.1:80)
saving to '/dev/null'
null                  10% |***_

function                                             old     new   delta
progress_meter                                       182     195     +13
retrieve_file_data                                   705     697      -8
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 1/1 up/down: 13/-8)               Total: 5 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-09-23 01:25:45 +02:00
Denys Vlasenko 218f328625 wget: support multiple restarts, -t NUM controls how many
function                                             old     new   delta
retrieve_file_data                                   621     705     +84
wget_main                                           2581    2657     +76
ftpcmd                                               133     151     +18
packed_usage                                       36282   36298     +16
get_sanitized_hdr                                    150     156      +6
fgets_trim_sanitize                                  134     137      +3
reset_beg_range_to_zero                               44      46      +2
.rodata                                           107342  107344      +2
progress_meter                                       189     182      -7
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 8/1 up/down: 207/-7)            Total: 200 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-09-23 00:36:36 +02:00
Denys Vlasenko 61e244e5ee dpkk: stop allowing spaces in NAME: parts. Debian does not do this, it seems
Add mode docs in comments. We probably do not follow them correctly yet.

function                                             old     new   delta
read_package_field                                   211     170     -41

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-09-22 16:12:33 +02:00
Denys Vlasenko 39c2dc8c49 httpd: document that P: proxying is not checking passwords
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-09-22 13:26:19 +02:00
Denys Vlasenko e97224f8fb tls: fix off-by-one access past the end of the received packet.
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-09-22 02:38:38 +02:00
Denys Vlasenko c2dec52d37 libpwdgrp: tokenizer fix for trailing whitespace removeal.
The tokenize() function trims trailing whitespace via
overlapping_strcpy() but continues to reference the stale *end
pointer. Fixing this.

function                                             old     new   delta
tokenize                                             120     119      -1

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-09-22 02:19:06 +02:00
Denys Vlasenko 556567f403 mount: document a possible bug in comment, no code changes.
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-09-22 01:55:03 +02:00
Denys Vlasenko 9f5cbdcaa5 httpd: allow yescrypt passwords ("$y$....")
function                                             old     new   delta
check_user_passwd                                    439     444      +5

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-09-22 01:14:47 +02:00
Denys Vlasenko d5cc94063b dpkg: fix field handling in write_status_file()
function                                             old     new   delta
dpkg_main                                           3943    3934      -9

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-09-22 01:05:07 +02:00
Denys Vlasenko 7a055991de dpkg: improve --help
function                                             old     new   delta
packed_usage                                       36247   36282     +35

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-09-22 00:48:46 +02:00
Denys Vlasenko e8a55de7ec dpkg-deb: add a rudimentary test
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-09-21 23:34:12 +02:00
Denys Vlasenko 6b366627e1 dpkg: remove const from non-pointer variables
This does not improve anything, only makes code more verbose.

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-09-21 23:32:37 +02:00
Denys Vlasenko 89a2512144 dpkg: code shrink by improving make_hash() API
function                                             old     new   delta
search_status_hashtable                              109     113      +4
search_name_hashtable                                104     103      -1
make_hash                                            116     113      -3
search_package_hashtable                             120      99     -21
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 1/3 up/down: 4/-25)             Total: -21 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-09-21 22:33:15 +02:00
Denys Vlasenko bef7bcf4ce dpkg: improve --help
function                                             old     new   delta
packed_usage                                       36243   36247      +4

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-09-21 22:30:23 +02:00
Denys Vlasenko 21f9c36676 dpkg: avoid strlen in fill_package_struct()
function                                             old     new   delta
fill_package_struct                                  306     291     -15

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-09-21 17:16:17 +02:00
Denys Vlasenko 7c611860df dpkg: deindent read_package_field(), rename variables. No logic changes
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-09-21 17:13:27 +02:00
Denys Vlasenko f5a4a02a15 dpkg: fix cases where read_package_field() returns offset past NUL
function                                             old     new   delta
read_package_field                                   169     211     +42

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-09-21 16:59:56 +02:00
Denys Vlasenko 43a9d7d315 dpkg: reformat code in read_package_field(), exposing why it's buggy
function                                             old     new   delta
read_package_field                                   184     169     -15

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-09-21 16:32:43 +02:00
Denys Vlasenko e2c5cc0420 dpkg: free results of read_package_field(), preliminary cleanups in read_package_field()
function                                             old     new   delta
dpkg_main                                           3910    3943     +33
write_buffer_no_status                                92     114     +22
read_package_field                                   204     184     -20
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 2/1 up/down: 55/-20)             Total: 35 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-09-21 16:16:47 +02:00
Denys Vlasenko fd1972099f udhcpc: ensure packet.data.cookie exists before we access it
function                                             old     new   delta
d4_recv_raw_packet                                   497     500      +3

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-09-21 12:15:19 +02:00
Denys Vlasenko 9073c1d15c volume_id/romfs: limit the maximum size of label to VOLUME_ID_LABEL_SIZE
function                                             old     new   delta
volume_id_set_label_string                            71      81     +10
volume_id_probe_romfs                                 94      97      +3
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 2/0 up/down: 13/0)               Total: 13 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-09-21 05:34:19 +02:00
Denys Vlasenko d0143f8da1 httpd: remove one unnecessary check
function                                             old     new   delta
scan_ip                                              170     165      -5

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-09-21 05:20:06 +02:00
Denys Vlasenko 339e3c62f5 httpd: fix handling of "D:1.2.3/999"
An error in allow/deny rule should be interpreted as D:0/0
("deny all") but was interpreted as D:IP/0. Fix this.

function                                             old     new   delta
parse_conf                                          1323    1330      +7

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-09-21 04:40:37 +02:00
Denys Vlasenko 89ac82774f tls: fix undersized buffer calculation
All callers of pstm_montgomery_reduce() are currently in pstm_exptmod()
and they all pass a preallocated temporary buffer, so the incorrect code
is unreachable. But fix it anyway.

function                                             old     new   delta
pstm_montgomery_reduce                               431     430      -1

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-09-21 03:20:39 +02:00
Denys Vlasenko 1b4f8e2a87 awk: allow OFMT='prefix:%SPEC suffix with %%'
function                                             old     new   delta
fmt_num                                              380     394     +14

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-09-14 01:46:32 +02:00
Ali Ahmet Memis 74ac096e89 sort: compute -k END.ENDCHAR from the end field, not the line start
get_key() locates a key in two passes: j=0 walks to the start of the
START field, j=1 walks to the end of the END field. When END carries
an ENDCHAR (-kSTART,N.ENDCHAR), that char position is supposed to be
counted from the start of field N. Instead the code overwrote 'end'
with the raw parsed value, an offset from the very start of the line:

	if (key->range[3]) {
		end = key->range[3];

For END field 1 this happens to be the same thing, but for any later
field it is not. The result usually lands before 'start', which then
gets clamped to 'start', producing an empty key. Sort has an ASCII
whole-line fallback when keys tie, so it silently sorts by the whole
line instead of the requested key:

	$ printf '%s\n' 'b:aa' 'a:ba' 'a:aa' | busybox sort -t : -k 2.1,2.1
	a:aa
	a:ba
	b:aa
	$ printf '%s\n' 'b:aa' 'a:ba' 'a:aa' | sort -t : -k 2.1,2.1
	a:aa
	b:aa
	a:ba

Make the j=1 pass stop at the start of field N instead of its end when
ENDCHAR is given, one field-skip short of the usual pass, and add the
ENDCHAR offset from there. This mirrors how STARTCHAR is already
applied relative to the start of the START field. Verified against
several -k combinations (endchar past the field's own length, multiple
fields skipped, startchar and endchar together) matching GNU sort.

Add a regression test; the existing ENDCHAR test only exercises field
1, where the old absolute offset and the correct field-relative one
happen to coincide.

function                                             old     new   delta
get_key                                              490     516     +26

Signed-off-by: Ali Ahmet Memis <ali@iusegentoo.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-08-31 22:54:31 +02:00
Denys Vlasenko 8f4dc3b405 platform.h: UNINITIALIZED_VAR() macro for suppressing gcc warnings
With gcc-15.0.1:

function                                             old     new   delta
tftpd_main                                           603     617     +14
expand_one_var                                      1923    1929      +6
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 2/0 up/down: 20/0)               Total: 20 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-08-31 20:03:33 +02:00
Denys Vlasenko c8047030dc vi: explain what vim 9.2 is doing with ":e FILE" escaping
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-08-31 16:50:46 +02:00
Denys Vlasenko 6ab4e2a0de vi: code shrink
function                                             old     new   delta
expand_args                                          186     181      -5

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-08-31 10:21:20 +02:00
Denys Vlasenko 7406d7a74f inetd: build fix if RPC is selected in .config
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-08-31 02:00:36 +02:00
Denys Vlasenko fe215e35d6 devfsd: heed warnings
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-08-31 01:55:03 +02:00
Denys Vlasenko 452a4f1ad5 hush: heed warnings about strchr() returning const char*
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-08-31 01:14:51 +02:00
Denys Vlasenko 6885d4c310 *: selinux: replace deprecated security_context_t with char*
Suppresses a lot of selinux warnings.
This does not change the code.

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-08-31 01:02:03 +02:00
Romain Guyard 4a2a446472 hdparm: fix ATA identification string output
print_ascii() is intended to skip leading spaces before printing ATA
IDENTIFY strings, but the condition is inverted and skips non-space
characters instead.

As a result, left-justified strings such as serial numbers and firmware
revisions can be printed as empty, while strings containing embedded
spaces, such as model names, are truncated up to the first space.

Fix the condition so only leading spaces are skipped, and add a regression
test covering left-justified strings, embedded spaces, and leading-space
padding.

function                                             old     new   delta
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 0/0 up/down: 0/0)                 Total: 0 bytes

Signed-off-by: Romain Guyard <foss@romainguyard.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-08-30 20:06:15 +02:00
Denys Vlasenko 9958bbd70a awk: disallow OFMT/CONVFMT to have more than one %SPEC, implement %s
function                                             old     new   delta
fmt_num                                              257     380    +123
.rodata                                           107332  107342     +10
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 2/0 up/down: 133/0)             Total: 133 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-08-30 18:55:07 +02:00
Anton Skorup 436223e2b7 tar: Sanitize verbose file names
function                                             old     new   delta
writeTarHeader                                       859     869     +10

Signed-off-by: Anton Skorup <anton.skorup@axis.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-08-30 13:27:23 +02:00
Ediz 15666f3e9a awk: fix 1-byte heap-buffer-overflow in next_token() string parse
When the awk program ends with \<newline> right after the last string
token, nextchar() eats the newline and then reads the terminating NUL
that xmalloc_read_with_initial_buf() appends, advancing past the end
of the buffer. The string-scan loop in next_token() then dereferences
one byte past the buffer (heap-buffer-overflow, READ of size 1).

Fix: test every nextchar() return for NULs.

Reproducer (ASan build):
awk 'BEGIN { print "string\
'

function                                             old     new   delta
next_token                                           934     933      -1

Signed-off-by: Ediz <ediz.research@gmail.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-08-24 10:56:25 +02:00
Denys Vlasenko 92ad65c3a2 stat: code shrink
function                                             old     new   delta
printf_llu                                             -      35     +35
printf_lx                                              -      30     +30
printf_lu                                              -      30     +30
printf_s                                               -      28     +28
printfs                                               28       -     -28
print_statfs                                         338     260     -78
print_stat                                           858     761     -97
------------------------------------------------------------------------------
(add/remove: 4/1 grow/shrink: 0/2 up/down: 123/-203)          Total: -80 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-08-24 09:49:01 +02:00
Benjamin Robin a61d158d54 stat: fix negative %X/%Y/%Z timestamps after Y2038 on 32-bit builds
Introduce a utility function to always print `time_t` values using either
`long long` or `unsigned long long`, depending on whether `time_t` is
signed. This fixes the bug reported in [1].

Previously, `time_t` values were cast to `long`, which is a 32-bit value
on 32-bit builds.

[1]: https://lists.busybox.net/pipermail/busybox/2026-August/092413.html

function                                             old     new   delta
print_stat                                           869     858     -11

Signed-off-by: Benjamin Robin <benjamin.robin@bootlin.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-08-24 09:27:10 +02:00
Thorsten B 7473045ad3 tar: fix verbose output with extract-to-stdout
Combining the verbose (-v) and extract-to-stdout (-O) options caused
verbose output and extracted file data to be interleaved unpredictably on
stdout. Verbose listing uses buffered stdio (printf()/puts()), while file
contents are written directly to the stdout file descriptor.

GNU tar also combines buffered verbose output with unbuffered writes for
"-vO", however, GNU tar writes verbose output to stderr, so the two streams
remain separate and consistent.

Fix this by making "tar xvO" send output to stderr.

function                                             old     new   delta
header_verbose_list                                  244     279     +35
header_list                                           15      49     +34
get_header_tar                                      1764    1769      +5
header_verbose_list_ar                                77      78      +1
get_header_ar                                        542     540      -2
get_header_cpio                                      959     948     -11
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 4/2 up/down: 75/-13)             Total: 62 bytes

Signed-off-by: Thorsten B <brehmt@gmail.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-08-10 06:30:18 +02:00
Ron Yorston d057384504 rpm2cpio: print name of unknown compression method
Commit f13f68288 (rpm2cpio: extract cpio even if compression is
not known) added an error message if the compression method was
unknown.  When support for lzma was disabled this resulted in a
null pointer being passed to bb_error_msg().

The call to rpm_getstr0() to fetch the name of the compression
method shouldn't depend on lzma being supported.

This doesn't affect the size of a default build.  In a build with
lzma disabled:

function                                             old     new   delta
rpm2cpio_main                                        110     121     +11
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 1/0 up/down: 11/0)               Total: 11 bytes

Signed-off-by: Ron Yorston <rmy@pobox.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-08-10 05:36:59 +02:00
Ron Yorston fce9d7f35e shell: correctly count backslashes in read built-in
When the read built-in's '-n' option is used to limit the number
of characters read, backslashes should only be counted if the '-r'
option is also suppiled.  This matches how bash behaves.

function                                             old     new   delta
shell_builtin_read                                  1360    1358      -2
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 0/1 up/down: 0/-2)               Total: -2 bytes

Signed-off-by: Ron Yorston <rmy@pobox.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-08-09 06:51:46 +02:00
Denys Vlasenko 9ad78b4180 shell: read: if poll() fails, attempt to process any data collected so far
This was already done on read() failure, why not on poll()?
Making it consistent.

function                                             old     new   delta
shell_builtin_read                                  1318    1308     -10

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-08-09 06:49:14 +02:00
Ron Yorston 9b21bb0f89 patch: handle files with no final newline
GNU and BSD patch both handle patches which include the annotation
'\ No newline at end of file'.  BusyBox patch doesn't, even though
its diff emits it.

Implement this feature and add some tests.

function                                             old     new   delta
patch_main                                          1912    2002     +90
do_line                                               88     116     +28
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 2/0 up/down: 118/0)             Total: 118 bytes

Signed-off-by: Ron Yorston <rmy@pobox.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-08-09 06:39:10 +02:00
Denys Vlasenko 3db20fa07b grep: support --quiet
function                                             old     new   delta
static.grep_longopts                                   -      17     +17
packed_usage                                       36237   36243      +6
.rodata                                           107341  107332      -9
------------------------------------------------------------------------------
(add/remove: 1/0 grow/shrink: 1/1 up/down: 23/-9)              Total: 14 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-07-24 18:38:38 +02:00
Denys Vlasenko ec0c5cc142 cp: fix --sparse to have mandatory argument, fix --remove-destination bit position
cp --remove-destination was broken by commit 56bbbfae "cp: implement -n"

function                                             old     new   delta
cp_main                                              527     533      +6

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-07-14 23:14:24 +02:00
Denys Vlasenko 17908bf760 cp: accept --sparse=ANYTHING
function                                             old     new   delta
cp_main                                              514     527     +13
.rodata                                           107332  107341      +9
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 2/0 up/down: 22/0)               Total: 22 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-07-14 19:00:02 +02:00
Denys Vlasenko 8f0533c576 join: code shrink by making some variables "global"
function                                             old     new   delta
readfields                                           442     437      -5
printfields                                          462     457      -5
join_main                                            843     760     -83
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 0/3 up/down: 0/-93)             Total: -93 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-07-08 14:38:07 +02:00
Ron Yorston a058289401 join: new applet
function                                             old     new   delta
join_main                                              -     843    +843
printfields                                            -     462    +462
readfields                                             -     442    +442
.rodata                                           107120  107332    +212
packed_usage                                       36078   36237    +159
applet_names                                        2870    2875      +5
applet_main                                         1652    1656      +4
------------------------------------------------------------------------------
(add/remove: 4/0 grow/shrink: 4/0 up/down: 2127/0)           Total: 2127 bytes
   text	   data	    bss	    dec	    hex	filename
1080964	    555	   4992	1086511	 10942f	busybox_old
1083091	    555	   4992	1088638	 109c7e	busybox_unstripped

v2: Add a missing return statement which broke the '-t' option.
    Thanks to Roberto A. Foglietta for pointing this out.

Signed-off-by: Morgan Bartlett <mjmouse9999@gmail.com>
Signed-off-by: Ron Yorston <rmy@pobox.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-07-08 07:01:03 +02:00
Sanghyun Park a448b6d5b2 ash: fix out-of-bounds read in ifsbreakup()
ifsfree() does not only release allocated ifsregion nodes; it also clears
the global IFS region state used by ifsbreakup(). If argstr() raises an
error while expanding an argument, ash longjmps out of expandarg() before
that cleanup runs, leaving stale IFS split offsets behind.

A later expansion can reuse the stack for a shorter string. ifsbreakup()
then sees the stale IFS state, trusts the old offsets, and can walk past
the current stack block before dereferencing p.

Follow dash's root-cause fix: when an expansion-related handler catches
EXERROR and continues, restore the handler and call ifsfree(). Apply
the cleanup to redirectsafe(), expandstr(), and evaltree().

Upstream commit:

    Date:   Mon Dec 5 23:02:01 2022 +0800
    expand: Add ifsfree to expand to fix a logic error that causes a buffer over-read

    On Mon, Jun 20, 2022 at 02:27:10PM -0400, Alex Gorinson wrote:
    > Due to a logic error in the ifsbreakup function in expand.c if a
    > heredoc and normal command is run one after the other by means of a
    > semi-colon, when the second command drops into ifsbreakup the command
    > will be evaluated with the ifslastp/ifsfirst struct that was set when
    > the here doc was evaluated. This results in a buffer over-read that
    > can leak the program's heap, stack, and arena addresses which can be
    > used to beat ASLR.
    >
    > Steps to Reproduce:
    > First bug:
    > cmd args: ~/exampleDir/example> dash
    > $ M='AAAAAAAAAAAAAAAAA'    <note: 17 A's>
    > $ q00(){
    > $ <<000;echo
    > $ ${D?$M$M$M$M$M$M}        <note: 6 $M's>
    > $ 000
    > $ }
    > $ q00                      <note: After the q00 is typed in, the leak
    > should be echo'd out; this works with ash, busybox ash, and dash and
    > with all option args.>
    >
    > Patch:
    > Adding the following to expand.c will fix both bugs in one go.
    > (Thank you to Harald van Dijk and Michael Greenberg for doing the
    > heavy lifting for this patch!)
    > ==========================
    > --- a/src/expand.c
    > +++ b/src/expand.c
    > @@ -859,6 +859,7 @@
    > if (discard)
    > return -1;
    >
    > +ifsfree();
    > sh_error("Bad substitution");
    > }
    >
    > @@ -1739,6 +1740,7 @@
    > } else
    > msg = umsg;
    > }
    > +ifsfree();
    > sh_error("%.*s: %s%s", end - var - 1, var, msg, tail);
    >  }
    > ==========================

    Thanks for the report!

    I think it's better to add the ifsfree() call to the exception
    handling path as other sh_error calls may trigger this too.

function                                             old     new   delta
restore_handler_expandarg                              -      33     +33
evaltree                                             725     711     -14
static.redirectsafe                                  141     124     -17
expandstr                                            262     242     -20
------------------------------------------------------------------------------
(add/remove: 1/0 grow/shrink: 0/3 up/down: 36/-45)            Total: -18 bytes

Signed-off-by: Sanghyun Park <sanghyun.park.cnu@gmail.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-07-06 10:30:30 +02:00
Denys Vlasenko 5de0780eaf awk: fix printf "%o\n", -1
function                                             old     new   delta
awk_printf                                          1381    1387      +6

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-07-06 04:37:44 +02:00
Denys Vlasenko cd8427b8ec svlogd: fix buffer overrun
Patch by mjmouse9999@gmail.com

When running svlogd -tt with a long line of input, the code assumes a buffer
of at least linemax+26 length, but that is two bytes longer than the
actual buffer with the default of linemax = 1000.

fixing that.

No code size change.

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-07-03 08:17:51 +02:00
Anubhav Kokane 71f9960b33 cmp: add KMG suffix for cmp -n MAXCOUNT
Change input to getopt32 from int to char * so that
max_count is parsed as string. Use xatol_sfx to convert
string to long.

function                                             old     new   delta
cmp_main                                             595     631     +36
.rodata                                           107121  107120      -1
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 1/1 up/down: 36/-1)              Total: 35 bytes

Signed-off-by: Anubhav Kokane <dev.anubhavk@gmail.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-07-03 08:14:23 +02:00
Denys Vlasenko 1332023051 awk: optimize 'print "no format specs here\n"' case
function                                             old     new   delta
awk_printf                                          1349    1381     +32

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-07-02 05:57:28 +02:00
Denys Vlasenko a0667b2def awk: fix printing of very large numbers with printf("%d")
function                                             old     new   delta
awk_printf                                          1086    1349    +263
.rodata                                           107108  107121     +13
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 2/0 up/down: 276/0)             Total: 276 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-07-02 04:58:08 +02:00
Denys Vlasenko 4e981fe00f awk: rename variables in awk_printf(), no code changes
awk_printf() got bigger, and now variables need better names,
even if this makes them longer.

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-07-02 00:05:11 +02:00
Denys Vlasenko 6ba81ddb0d awk: add '*' as a valid specifier for width and precision in printf
Based on a patch by Anubhav Kokane <dev.anubhavk@gmail.com>

function                                             old     new   delta
awk_printf                                           640    1086    +446
.rodata                                           107131  107108     -23
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 1/1 up/down: 446/-23)           Total: 423 bytes
   text	   data	    bss	    dec	    hex	filename
1080210	    555	   4992	1085757	 10913d	busybox_old
1080633	    555	   4992	1086180	 1092e4	busybox_unstripped

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-07-01 23:38:27 +02:00
Denys Vlasenko 244c0a01ee testing stripts: allow to skip "awk gsub erroneous word start match" test
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-05-14 16:26:10 +02:00
Denys Vlasenko 0309c02980 hush: placate warning: 'print_pfx_escaped_nl' defined but not used
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-05-14 16:22:40 +02:00
Denys Vlasenko 8fc70b52e6 tls: use bb_simple_error_msg where appropriate
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-05-14 16:08:13 +02:00
Denys Vlasenko c83394922e Start 1.39.0 development cycle
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-05-13 05:24:28 +02:00
182 changed files with 6358 additions and 4813 deletions

No files matched your search

+2 -2
View File
@@ -1,7 +1,7 @@
VERSION = 1
PATCHLEVEL = 38
PATCHLEVEL = 39
SUBLEVEL = 0
EXTRAVERSION =
EXTRAVERSION = .git
NAME = Unnamed
# *DOCUMENTATION*
+2
View File
@@ -27,6 +27,8 @@ CFLAGS += $(call cc-option,-Wunused -Wunused-parameter,)
CFLAGS += $(call cc-option,-Wunused-function -Wunused-value,)
CFLAGS += $(call cc-option,-Wmissing-prototypes -Wmissing-declarations,)
CFLAGS += $(call cc-option,-Wno-format-security,)
# we use "" format in ioctl_or_perror_and_die(a, b, c, "")
CFLAGS += $(call cc-option,-Wno-format-zero-length,)
# warn about C99 declaration after statement
CFLAGS += $(call cc-option,-Wdeclaration-after-statement,)
# If you want to add more -Wsomething above, make sure that it is
+6 -5
View File
@@ -151,15 +151,15 @@ static int write_ar_header(archive_handle_t *handle)
static int write_ar_archive(archive_handle_t *handle)
{
struct stat st;
off_t st_size;
archive_handle_t *out_handle;
xfstat(handle->src_fd, &st, handle->ar__name);
st_size = xfstat_size(handle->src_fd, handle->ar__name);
/* if archive exists, create a new handle for output.
* we create it in place of the old one.
*/
if (st.st_size != 0) {
if (st_size != 0) {
out_handle = init_handle();
xunlink(handle->ar__name);
out_handle->src_fd = xopen(handle->ar__name, O_WRONLY | O_CREAT | O_TRUNC);
@@ -174,7 +174,7 @@ static int write_ar_archive(archive_handle_t *handle)
out_handle->offset += AR_MAGIC_LEN + 1;
/* skip to the end of the archive if we have to append stuff */
if (st.st_size != 0) {
if (st_size != 0) {
handle->filter = filter_replaceable;
handle->action_data = copy_data;
unpack_ar_archive(handle);
@@ -194,8 +194,9 @@ static int write_ar_archive(archive_handle_t *handle)
}
#endif /* FEATURE_AR_CREATE */
static void FAST_FUNC header_verbose_list_ar(const file_header_t *file_header)
static void FAST_FUNC header_verbose_list_ar(archive_handle_t *archive_handle)
{
const file_header_t *file_header = archive_handle->file_header;
char mode[12];
char *mtime;
+1 -1
View File
@@ -53,7 +53,7 @@
//config: help
//config: Optionally renumber inodes when creating archives.
//applet:IF_CPIO(APPLET(cpio, BB_DIR_BIN, BB_SUID_DROP))
//applet:IF_CPIO(APPLET(cpio, BB_DIR_USR_BIN, BB_SUID_DROP))
//kbuild:lib-$(CONFIG_CPIO) += cpio.o
+176 -138
View File
@@ -41,30 +41,30 @@
//kbuild:lib-$(CONFIG_DPKG) += dpkg.o
//usage:#define dpkg_trivial_usage
//usage: "[-ilCPru] [-F OPT] PACKAGE"
//usage: IF_LONG_OPTS("-i|P|r|--unpack|--configure [--force-OPT]")IF_NOT_LONG_OPTS("-i|P|r|u|C [-F OPT]")" PACKAGE | -l [PATTERN]"
//usage:#define dpkg_full_usage "\n\n"
//usage: "Install, remove and manage Debian packages\n"
//usage: "Manage Debian packages\n"
//usage: IF_LONG_OPTS(
//usage: "\n -i,--install Install the package"
//usage: "\n -l,--list List of installed packages"
//usage: "\n --configure Configure an unpackaged package"
//usage: "\n -P,--purge Purge all files of a package"
//usage: "\n -r,--remove Remove all but the configuration files for a package"
//usage: "\n --unpack Unpack a package, but don't configure it"
//usage: "\n -i,--install Install PACKAGE.deb"
//usage: "\n -P,--purge Purge all files of PACKAGE"
//usage: "\n -r,--remove Remove all but configuration files of PACKAGE"
//usage: "\n --unpack Unpack PACKAGE.deb relative to /, don't configure"
//usage: "\n --configure Configure unpacked PACKAGE"
//usage: "\n --force-depends Ignore dependency problems"
//usage: "\n --force-confnew Overwrite existing config files when installing"
//usage: "\n --force-confold Keep old config files when installing"
//usage: "\n -l,--list List installed packages"
//usage: )
//usage: IF_NOT_LONG_OPTS(
//usage: "\n -i Install the package"
//usage: "\n -l List of installed packages"
//usage: "\n -C Configure an unpackaged package"
//usage: "\n -P Purge all files of a package"
//usage: "\n -r Remove all but the configuration files for a package"
//usage: "\n -u Unpack a package, but don't configure it"
//usage: "\n -i Install PACKAGE.deb"
//usage: "\n -P Purge all files of PACKAGE"
//usage: "\n -r Remove all but configuration files of PACKAGE"
//usage: "\n -u Unpack PACKAGE.deb relative to /, don't configure"
//usage: "\n -C Configure unpacked PACKAGE"
//usage: "\n -F depends Ignore dependency problems"
//usage: "\n -F confnew Overwrite existing config files when installing"
//usage: "\n -F confold Keep old config files when installing"
//usage: "\n -l List installed packages"
//usage: )
#include "libbb.h"
@@ -166,8 +166,9 @@ typedef struct deb_file_s {
} deb_file_t;
static void make_hash(const char *key, unsigned *start, unsigned *decrement, const int hash_prime)
static unsigned make_hash(const char *key, unsigned *decrement, int hash_prime)
{
unsigned start;
unsigned long hash_num = key[0];
int len = strlen(key);
int i;
@@ -181,8 +182,9 @@ static void make_hash(const char *key, unsigned *start, unsigned *decrement, con
* no effect */
hash_num += (key[i] + key[i-1]) << ((key[i] * i) % 24);
}
*start = (unsigned) hash_num % hash_prime;
start = (unsigned) hash_num % hash_prime;
*decrement = (unsigned) 1 + (hash_num % (hash_prime - 1));
return start;
}
/* this adds the key to the hash table */
@@ -191,7 +193,7 @@ static int search_name_hashtable(const char *key)
unsigned probe_address;
unsigned probe_decrement;
make_hash(key, &probe_address, &probe_decrement, NAME_HASH_PRIME);
probe_address = make_hash(key, &probe_decrement, NAME_HASH_PRIME);
while (name_hashtable[probe_address] != NULL) {
if (strcmp(name_hashtable[probe_address], key) == 0) {
return probe_address;
@@ -213,7 +215,7 @@ static unsigned search_status_hashtable(const char *key)
unsigned probe_address;
unsigned probe_decrement;
make_hash(key, &probe_address, &probe_decrement, STATUS_HASH_PRIME);
probe_address = make_hash(key, &probe_decrement, STATUS_HASH_PRIME);
while (status_hashtable[probe_address] != NULL) {
if (strcmp(key, name_hashtable[package_hashtable[status_hashtable[probe_address]->package]->name]) == 0) {
break;
@@ -280,7 +282,7 @@ static int version_compare_part(const char *val, const char *ref)
* if ver1 = ver2 return 0,
* if ver1 > ver2 return 1,
*/
static int version_compare(const unsigned ver1, const unsigned ver2)
static int version_compare(unsigned ver1, unsigned ver2)
{
char *ch_ver1 = name_hashtable[ver1];
char *ch_ver2 = name_hashtable[ver2];
@@ -333,9 +335,9 @@ static int version_compare(const unsigned ver1, const unsigned ver2)
return result;
}
static int test_version(const unsigned version1, const unsigned version2, const unsigned operator)
static int test_version(unsigned version1, unsigned version2, unsigned operator)
{
const int version_result = version_compare(version1, version2);
int version_result = version_compare(version1, version2);
switch (operator) {
case VER_ANY:
return TRUE;
@@ -353,12 +355,12 @@ static int test_version(const unsigned version1, const unsigned version2, const
return FALSE;
}
static int search_package_hashtable(const unsigned name, const unsigned version, const unsigned operator)
static int search_package_hashtable(unsigned name, unsigned version, unsigned operator)
{
unsigned probe_address;
unsigned probe_decrement;
make_hash(name_hashtable[name], &probe_address, &probe_decrement, PACKAGE_HASH_PRIME);
probe_address = make_hash(name_hashtable[name], &probe_decrement, PACKAGE_HASH_PRIME);
while (package_hashtable[probe_address] != NULL) {
if (package_hashtable[probe_address]->name == name) {
if (operator == VER_ANY) {
@@ -531,90 +533,98 @@ static void free_package(common_node_t *node)
}
/*
* Gets the next package field from package_buffer, separated into the field name
* and field value, it returns the int offset to the first character of the next field
* Gets the next package field from pkg_buf:
* "NAME:<spaces|tabs>VALUE{\n|NUL}"
* "NAME:<spaces|tabs>VALUE\n
* " VALUE_LINE2{\n|NUL}"
* separated into "NAME" and "VALUE", both strdup()ed.
* (Debian does not allow whitespace before/after NAME).
* Returns offset to the first character of the next field (or to NUL).
* The pkg_buf parameter is NUL-terminated.
*
* https://manpages.debian.org/testing/dpkg-dev/deb-control.5.en.html
* """
* This file contains a number of fields. Each field begins with a tag,
* such as Package or Version (case insensitive), followed by a colon,
* and the body of the field (case sensitive unless stated otherwise).
* Fields are delimited only by field tags. In other words, field text
* may be multiple lines in length, but the installation tools will
* generally join lines when processing the body of the field (except
* in the case of the Description field, see below).
* ...
* Description: short-description (recommended)
* long-description
* The format for the package description is a short brief summary
* on the first line (after the Description field). The following lines
* should be used as a longer, more detailed description. Each line
* of the long description must be preceded by a space, and blank
* lines in the long description must contain a single '.' following
* the preceding space."""
*
* Seen in libgtk-3-0t64_3.24.52: source package's control:
* Recommends: ibus-gtk3,
* libgtk-3-bin,
* librsvg2-common
* gets translated to this in binary package's control:
* Recommends: ibus-gtk3, libgtk-3-bin, librsvg2-common
*/
static int read_package_field(const char *package_buffer, char **field_name, char **field_value)
static int read_package_field(const char *pkg_buf, char **pname, char **pvalue)
{
int offset_name_start = 0;
int offset_name_end = 0;
int offset_value_start = 0;
int offset_value_end = 0;
int offset = 0;
int next_offset;
int name_length;
int value_length;
int exit_flag = FALSE;
int name_start;
int name_end;
int value_start = value_start;
int offset;
if (package_buffer == NULL) {
*field_name = NULL;
*field_value = NULL;
return -1;
}
*pname = NULL;
*pvalue = NULL;
offset = 0;
name_start = 0;
name_end = 0; /* "we did not see ':' yet" */
while (1) {
next_offset = offset + 1;
switch (package_buffer[offset]) {
case '\0':
exit_flag = TRUE;
break;
case ':':
if (offset_name_end == 0) {
offset_name_end = offset;
offset_value_start = next_offset;
}
/* TODO: Name might still have trailing spaces if ':' isn't
* immediately after name */
break;
case '\n':
/* TODO: The char next_offset may be out of bounds */
if (package_buffer[next_offset] != ' ') {
exit_flag = TRUE;
break;
}
case '\t':
case ' ':
/* increment the value start point if its a just filler */
if (offset_name_start == offset) {
offset_name_start++;
}
if (offset_value_start == offset) {
offset_value_start++;
}
break;
}
if (exit_flag) {
/* Check that the names are valid */
offset_value_end = offset;
name_length = offset_name_end - offset_name_start;
value_length = offset_value_end - offset_value_start;
if (name_length == 0) {
break;
char ch = pkg_buf[offset];
switch (ch) {
case ':':
if (name_end == 0) {
offset++;
name_end = offset; /* points AFTER ':' - think of empty NAME case */
while (isblank(pkg_buf[offset])) /* skip spaces/tabs (not newlines!) */
offset++;
value_start = offset;
continue; /* check next char */
}
if ((name_length > 0) && (value_length > 0)) {
break;
case '\n':
if (pkg_buf[offset + 1] == ' ')
break;
/* end of VALUE - fall through */
case '\0':
/* Did we see the ':'? */
if (name_end != 0) {
/* Yes. Check that NAME is not empty */
int nlen = (name_end - 1) - name_start;
if (nlen > 0) {
//TODO: why do we disallow empty NAME? Imagine a ": VALUE\n" line
*pname = xstrndup(&pkg_buf[name_start], nlen);
*pvalue = xstrndup(&pkg_buf[value_start], offset - value_start); /* could be "" */
if (ch)
offset++; /* skip '\n' */
return offset;
}
}
if (!ch)
return offset; /* stop at NUL */
/* If not valid, start fresh with next field */
exit_flag = FALSE;
offset_name_start = offset + 1;
offset_name_end = 0;
offset_value_start = offset + 1;
offset_value_end = offset + 1;
offset++;
/* Not valid: skip '\n', start fresh with next field */
name_start = offset + 1;
name_end = 0; /* "we did not see ':' yet" */
break;
}
offset++;
}
*field_name = NULL;
if (name_length) {
*field_name = xstrndup(&package_buffer[offset_name_start], name_length);
}
*field_value = NULL;
if (value_length > 0) {
*field_value = xstrndup(&package_buffer[offset_value_start], value_length);
}
return next_offset;
} /* while (1) */
}
/* The parameter is NUL-terminated */
static unsigned fill_package_struct(char *control_buffer)
{
static const char field_names[] ALIGN1 =
@@ -623,14 +633,13 @@ static unsigned fill_package_struct(char *control_buffer)
"Conflicts\0""Suggests\0""Recommends\0""Enhances\0";
common_node_t *new_node = xzalloc(sizeof(common_node_t));
char *field_name;
char *field_value;
int field_start = 0;
int num = -1;
int buffer_length = strlen(control_buffer);
int num;
new_node->version = search_name_hashtable("unknown");
while (field_start < buffer_length) {
while (control_buffer[field_start]) {
char *field_name;
char *field_value;
unsigned field_num;
field_start += read_package_field(&control_buffer[field_start],
@@ -689,7 +698,7 @@ static unsigned fill_package_struct(char *control_buffer)
}
/* if num = 1, it returns the want status, 2 returns flag, 3 returns status */
static unsigned get_status(const unsigned status_node, const int num)
static unsigned get_status(unsigned status_node, int num)
{
char *status_string = name_hashtable[status_hashtable[status_node]->status];
char *state_sub_string;
@@ -711,9 +720,9 @@ static unsigned get_status(const unsigned status_node, const int num)
return state_sub_num;
}
static void set_status(const unsigned status_node_num, const char *new_value, const int position)
static void set_status(unsigned status_node_num, const char *new_value, int position)
{
const unsigned new_value_num = search_name_hashtable(new_value);
unsigned new_value_num = search_name_hashtable(new_value);
unsigned want = get_status(status_node_num, 1);
unsigned flag = get_status(status_node_num, 2);
unsigned status = get_status(status_node_num, 3);
@@ -771,9 +780,10 @@ static void index_status_file(const char *filename)
status_node_t *status_node = NULL;
unsigned status_num;
//FIXME: dpkg 1.22.22 recreates empty /var/lib/dpkg/status if it's missing - does not fail
status_file = xfopen_for_read(filename);
while ((control_buffer = xmalloc_fgetline_str(status_file, "\n\n")) != NULL) {
const unsigned package_num = fill_package_struct(control_buffer);
unsigned package_num = fill_package_struct(control_buffer);
if (package_num != -1) {
status_node = xmalloc(sizeof(status_node_t));
/* fill_package_struct doesn't handle the status field */
@@ -799,7 +809,7 @@ static void write_buffer_no_status(FILE *new_status_file, const char *control_bu
char *name;
char *value;
int start = 0;
while (1) {
while (control_buffer[start]) {
start += read_package_field(&control_buffer[start], &name, &value);
if (name == NULL) {
break;
@@ -807,42 +817,42 @@ static void write_buffer_no_status(FILE *new_status_file, const char *control_bu
if (strcmp(name, "Status") != 0) {
fprintf(new_status_file, "%s: %s\n", name, value);
}
free(name);
free(value);
}
}
/* This could do with a cleanup */
static void write_status_file(deb_file_t **deb_file)
{
//FIXME: dpkg 1.22.22 recreates empty /var/lib/dpkg/status if it's missing - does not fail
FILE *old_status_file = xfopen_for_read("/var/lib/dpkg/status");
FILE *new_status_file = xfopen_for_write("/var/lib/dpkg/status.udeb");
char *package_name;
char *status_from_file;
char *control_buffer = NULL;
char *tmp_string;
char *control_buffer;
int status_num;
int field_start = 0;
int write_flag;
int i = 0;
int i;
/* Update previously known packages */
while ((control_buffer = xmalloc_fgetline_str(old_status_file, "\n\n")) != NULL) {
char *package_name;
char *status_from_file;
char *tmp_string;
int write_flag;
tmp_string = strstr(control_buffer, "Package:");
if (tmp_string == NULL) {
free(control_buffer);
continue;
}
tmp_string += 8;
tmp_string += strspn(tmp_string, " \n\t");
tmp_string = skip_whitespace(tmp_string + 8);
package_name = xstrndup(tmp_string, strcspn(tmp_string, "\n"));
write_flag = FALSE;
status_from_file = NULL;
tmp_string = strstr(control_buffer, "Status:");
if (tmp_string != NULL) {
/* Separate the status value from the control buffer */
tmp_string += 7;
tmp_string += strspn(tmp_string, " \n\t");
tmp_string = skip_whitespace(tmp_string + 7);
status_from_file = xstrndup(tmp_string, strcspn(tmp_string, "\n"));
} else {
status_from_file = NULL;
}
/* Find this package in the status hashtable */
@@ -851,7 +861,7 @@ static void write_status_file(deb_file_t **deb_file)
const char *status_from_hashtable = name_hashtable[status_hashtable[status_num]->status];
if (strcmp(status_from_file, status_from_hashtable) != 0) {
/* New status isn't exactly the same as old status */
const int state_status = get_status(status_num, 3);
int state_status = get_status(status_num, 3);
if ((strcmp("installed", name_hashtable[state_status]) == 0)
|| (strcmp("unpacked", name_hashtable[state_status]) == 0)
) {
@@ -870,7 +880,7 @@ static void write_status_file(deb_file_t **deb_file)
}
i++;
}
/* This is temperary, debugging only */
/* This is temporary, debugging only */
if (deb_file[i] == NULL) {
bb_error_msg_and_die("ALERT: cannot find a control file, "
"your status file may be broken, status may be "
@@ -878,14 +888,18 @@ static void write_status_file(deb_file_t **deb_file)
}
}
else if (strcmp("not-installed", name_hashtable[state_status]) == 0) {
int field_start = 0;
/* Only write the Package, Status, Priority and Section lines */
fprintf(new_status_file, "Package: %s\n", package_name);
fprintf(new_status_file, "Status: %s\n", status_from_hashtable);
while (1) {
while (control_buffer[field_start]) {
char *field_name;
char *field_value;
field_start += read_package_field(&control_buffer[field_start], &field_name, &field_value);
//FIXME: the questionable ": VALUE" lines (empty NAME)
//probably should not stop parsing of the entire file?
if (field_name == NULL) {
break;
}
@@ -894,13 +908,17 @@ static void write_status_file(deb_file_t **deb_file)
) {
fprintf(new_status_file, "%s: %s\n", field_name, field_value);
}
free(field_name);
free(field_value);
}
write_flag = TRUE;
fputs("\n", new_status_file);
}
else if (strcmp("config-files", name_hashtable[state_status]) == 0) {
int field_start = 0;
/* only change the status line */
while (1) {
while (control_buffer[field_start]) {
char *field_name;
char *field_value;
field_start += read_package_field(&control_buffer[field_start], &field_name, &field_value);
@@ -913,13 +931,15 @@ static void write_status_file(deb_file_t **deb_file)
} else {
fprintf(new_status_file, "%s: %s\n", field_name, field_value);
}
free(field_name);
free(field_value);
}
write_flag = TRUE;
fputs("\n", new_status_file);
}
}
}
/* If the package from the status file wasn't handle above, do it now*/
/* If the package from the status file wasn't handled above, do it now */
if (!write_flag) {
fprintf(new_status_file, "%s\n\n", control_buffer);
}
@@ -927,7 +947,7 @@ static void write_status_file(deb_file_t **deb_file)
free(status_from_file);
free(package_name);
free(control_buffer);
}
} /* while (control_buffer) */
/* Write any new packages */
for (i = 0; deb_file[i] != NULL; i++) {
@@ -994,14 +1014,14 @@ static int check_deps(deb_file_t **deb_file, int deb_start /*, int dep_max_count
/* Create array of package numbers to check against
* installed package for conflicts*/
while (deb_file[i] != NULL) {
const unsigned package_num = deb_file[i]->package;
unsigned package_num = deb_file[i]->package;
conflicts = xrealloc_vector(conflicts, 2, conflicts_num);
conflicts[conflicts_num] = package_num;
conflicts_num++;
/* add provides to conflicts list */
for (j = 0; j < package_hashtable[package_num]->num_of_edges; j++) {
if (package_hashtable[package_num]->edge[j]->type == EDGE_PROVIDES) {
const int conflicts_package_num = search_package_hashtable(
int conflicts_package_num = search_package_hashtable(
package_hashtable[package_num]->edge[j]->name,
package_hashtable[package_num]->edge[j]->version,
package_hashtable[package_num]->edge[j]->operator);
@@ -1036,7 +1056,7 @@ static int check_deps(deb_file_t **deb_file, int deb_start /*, int dep_max_count
const edge_t *package_edge = package_node->edge[j];
if (package_edge->type == EDGE_CONFLICTS) {
const unsigned package_num =
unsigned package_num =
search_package_hashtable(package_edge->name,
package_edge->version,
package_edge->operator);
@@ -1065,7 +1085,7 @@ static int check_deps(deb_file_t **deb_file, int deb_start /*, int dep_max_count
for (i = 0; i < PACKAGE_HASH_PRIME; i++) {
int status_num = 0;
int number_of_alternatives = 0;
const edge_t * root_of_alternatives = NULL;
const edge_t *root_of_alternatives = NULL;
const common_node_t *package_node = package_hashtable[i];
/* If the package node does not exist then this
@@ -1381,12 +1401,12 @@ static void list_packages(const char *pattern)
}
}
static void remove_package(const unsigned package_num, int noisy)
static void remove_package(unsigned package_num, int noisy)
{
const char *package_name = name_hashtable[package_hashtable[package_num]->name];
const char *package_version = name_hashtable[package_hashtable[package_num]->version];
const unsigned status_num = search_status_hashtable(package_name);
const int package_name_length = strlen(package_name);
unsigned status_num = search_status_hashtable(package_name);
int package_name_length = strlen(package_name);
char **remove_files;
char **exclude_files;
char list_name[package_name_length + 25];
@@ -1432,11 +1452,11 @@ static void remove_package(const unsigned package_num, int noisy)
set_status(status_num, "config-files", 3);
}
static void purge_package(const unsigned package_num)
static void purge_package(unsigned package_num)
{
const char *package_name = name_hashtable[package_hashtable[package_num]->name];
const char *package_version = name_hashtable[package_hashtable[package_num]->version];
const unsigned status_num = search_status_hashtable(package_name);
unsigned status_num = search_status_hashtable(package_name);
char **remove_files;
char **exclude_files;
char list_name[strlen(package_name) + 25];
@@ -1654,8 +1674,8 @@ enum {
static void unpack_package(deb_file_t *deb_file)
{
const char *package_name = name_hashtable[package_hashtable[deb_file->package]->name];
const unsigned status_num = search_status_hashtable(package_name);
const unsigned status_package_num = status_hashtable[status_num]->package;
unsigned status_num = search_status_hashtable(package_name);
unsigned status_package_num = status_hashtable[status_num]->package;
char *info_prefix;
char *list_filename;
archive_handle_t *archive_handle;
@@ -1745,7 +1765,7 @@ static void configure_package(deb_file_t *deb_file)
{
const char *package_name = name_hashtable[package_hashtable[deb_file->package]->name];
const char *package_version = name_hashtable[package_hashtable[deb_file->package]->version];
const int status_num = search_status_hashtable(package_name);
int status_num = search_status_hashtable(package_name);
printf("Setting up %s (%s)...\n", package_name, package_version);
@@ -1786,6 +1806,24 @@ int dpkg_main(int argc UNUSED_PARAM, char **argv)
"force-confold\0" No_argument "\xfd"
;
#endif
//--admindir=DIR
// Set the administrative directory to DIR. This directory
// contains many files that give information about status of
// installed or uninstalled packages, etc. Defaults to
// /var/lib/dpkg if DPKG_ADMINDIR has not been set.
//--instdir=DIR
// Set the installation directory, which refers to the directory
// where packages are to be installed. DIR is also the
// directory passed to chroot(2) before running package's
// installation scripts, which means that the scripts see DIR
// as a root directory. Defaults to / if DPKG_ROOT has not
// been set (since dpkg 1.21.10).
//--root=DIR
// Set the root directory to DIR, which sets the
// installation directory to DIR and the administrative
// directory to DIR/var/lib/dpkg if DPKG_ROOT
// has not been set (since dpkg 1.21.10).
//TODO: implement --root=DIR? necessary for testing
INIT_G();
+6 -7
View File
@@ -463,13 +463,12 @@ static int get_next_block(bunzip_data *bd)
symbols, but a run of length 0 doesn't mean anything in this
context). Thus space is saved. */
runCnt += (runPos << nextSym); /* +runPos if RUNA; +2*runPos if RUNB */
//The 32-bit overflow of runCnt wasn't yet seen, but probably can happen.
//This would be the fix (catches too large count way before it can overflow):
// if (runCnt > bd->dbufSize) {
// dbg("runCnt:%u > dbufSize:%u RETVAL_DATA_ERROR",
// runCnt, bd->dbufSize);
// return RETVAL_DATA_ERROR;
// }
/* Catch 32-bit overflow (we have an example .bz2 file) */
if ((int)runCnt < 0) {
dbg("runCnt:%u > dbufSize:%u RETVAL_DATA_ERROR",
runCnt, bd->dbufSize);
return RETVAL_DATA_ERROR;
}
if (runPos < bd->dbufSize) runPos <<= 1;
goto end_of_huffman_loop;
}
+1 -1
View File
@@ -124,7 +124,7 @@ char FAST_FUNC get_header_ar(archive_handle_t *archive_handle)
typed->name[strcspn(typed->name, " /")] = '\0';
if (archive_handle->filter(archive_handle) == EXIT_SUCCESS) {
archive_handle->action_header(typed);
archive_handle->action_header(archive_handle);
#if ENABLE_DPKG || ENABLE_DPKG_DEB
if (archive_handle->dpkg__sub_archive) {
struct archive_handle_t *sa = archive_handle->dpkg__sub_archive;
+1 -1
View File
@@ -125,7 +125,7 @@ char FAST_FUNC get_header_cpio(archive_handle_t *archive_handle)
//cpio: etc/hosts not created: newer or same age file exists
//etc/hosts <-- should NOT show it
//2 blocks <-- should say "0 blocks"
archive_handle->action_header(file_header);
archive_handle->action_header(archive_handle);
} else {
data_skip(archive_handle);
}
+1 -1
View File
@@ -469,7 +469,7 @@ char FAST_FUNC get_header_tar(archive_handle_t *archive_handle)
cp = last_char_is(file_header->name, '/');
if (archive_handle->filter(archive_handle) == EXIT_SUCCESS) {
archive_handle->action_header(/*archive_handle->*/ file_header);
archive_handle->action_header(archive_handle);
/* Note that we kill the '/' only after action_header() */
/* (like GNU tar 1.15.1: verbose mode outputs "dir/dir/") */
if (cp)
+7 -2
View File
@@ -5,8 +5,13 @@
#include "libbb.h"
#include "bb_archive.h"
void FAST_FUNC header_list(const file_header_t *file_header)
void FAST_FUNC header_list(archive_handle_t *archive_handle)
{
//TODO: cpio -vp DIR should output "DIR/NAME", not just "NAME" */
puts(printable_string(file_header->name));
const file_header_t *file_header = archive_handle->file_header;
/* "tar xvOf TARFILE >OUTFILE" should use stderr for file list output: */
FILE *fp = (archive_handle->action_data == data_extract_to_stdout) ? stderr : stdout;
fprintf(fp, "%s\n", printable_string(file_header->name));
}
+1 -1
View File
@@ -5,6 +5,6 @@
#include "libbb.h"
#include "bb_archive.h"
void FAST_FUNC header_skip(const file_header_t *file_header UNUSED_PARAM)
void FAST_FUNC header_skip(archive_handle_t *archive_handle UNUSED_PARAM)
{
}
+9 -6
View File
@@ -5,11 +5,14 @@
#include "libbb.h"
#include "bb_archive.h"
void FAST_FUNC header_verbose_list(const file_header_t *file_header)
void FAST_FUNC header_verbose_list(archive_handle_t *archive_handle)
{
const file_header_t *file_header = archive_handle->file_header;
struct tm tm_time;
struct tm *ptm = &tm_time; //localtime(&file_header->mtime);
char modestr[12];
/* "tar xvvOf TARFILE >OUTFILE" should use stderr for file list output: */
FILE *fp = (archive_handle->action_data == data_extract_to_stdout) ? stderr : stdout;
#if ENABLE_FEATURE_TAR_UNAME_GNAME
char uid[sizeof(int)*3 + 2];
@@ -29,7 +32,7 @@ void FAST_FUNC header_verbose_list(const file_header_t *file_header)
/*sprintf(gid, "%u", (unsigned)file_header->gid);*/
group = utoa(file_header->gid);
}
printf("%s %s/%s %9"OFF_FMT"u %4u-%02u-%02u %02u:%02u:%02u %s",
fprintf(fp, "%s %s/%s %9"OFF_FMT"u %4u-%02u-%02u %02u:%02u:%02u %s",
bb_mode_string(modestr, file_header->mode),
user,
group,
@@ -40,13 +43,13 @@ void FAST_FUNC header_verbose_list(const file_header_t *file_header)
ptm->tm_hour,
ptm->tm_min,
ptm->tm_sec,
file_header->name);
printable_string(file_header->name));
#else /* !FEATURE_TAR_UNAME_GNAME */
localtime_r(&file_header->mtime, ptm);
printf("%s %u/%u %9"OFF_FMT"u %4u-%02u-%02u %02u:%02u:%02u %s",
fprintf(fp, "%s %u/%u %9"OFF_FMT"u %4u-%02u-%02u %02u:%02u:%02u %s",
bb_mode_string(modestr, file_header->mode),
(unsigned)file_header->uid,
(unsigned)file_header->gid,
@@ -63,7 +66,7 @@ void FAST_FUNC header_verbose_list(const file_header_t *file_header)
/* NB: GNU tar shows "->" for symlinks and "link to" for hardlinks */
if (file_header->link_target) {
printf(" -> %s", printable_string(file_header->link_target));
fprintf(fp, " -> %s", printable_string(file_header->link_target));
}
bb_putchar('\n');
putc('\n', fp);
}
+6
View File
@@ -8,6 +8,12 @@
const char* FAST_FUNC skip_unsafe_prefix(const char *str)
{
const char *cp = str;
/* if "..": malicious, return "" */
/* (causes harmless errors trying to create or hardlink a file named "") */
if (cp[0] == '.' && cp[1] == '.' && cp[2] == '\0')
return cp + 2;
while (1) {
const char *cp2;
if (*cp == '/') {
+47 -8
View File
@@ -17,26 +17,65 @@ void FAST_FUNC create_or_remember_link(llist_t **link_placeholders,
return;
}
if (symlink(target, linkname) != 0) {
/* shared message */
// shared message
bb_perror_msg_and_die("can't create %slink '%s' to '%s'",
"sym", linkname, target
);
}
}
static int all_dir_components_are_dirs(char *path)
{
struct stat sb;
char *slash;
slash = path;
while ((slash = strchr(slash, '/')) != NULL) {
int ok;
*slash = '\0';
ok = (lstat(path, &sb) == 0 && S_ISDIR(sb.st_mode));
*slash++ = '/';
if (!ok)
return 0;
}
return 1;
}
void FAST_FUNC create_links_from_list(llist_t *list)
{
// This idea sounds better (fewer file ops):
// Create hardlinks first, then symlinks.
// ^^^ but it breaks the "hardlink to symlink" case:
// mkdir dir
// >dir/a
// ln -s ../dir/a dir/b
// ln dir/b dir/c
// mkdir new; tar cf - dir/a dir/b dir/c | tar -C new -xvf -
// On extract, 'c' will have no 'b' to be a hardlink to.
while (list) {
char *target;
char *linkname = list->data + 1;
target = list->data + 1 + strlen(list->data + 1) + 1;
if ((*list->data ? link : symlink) (target, list->data + 1)) {
/* shared message */
bb_error_msg_and_die("can't create %slink '%s' to '%s'",
*list->data ? "hard" : "sym",
list->data + 1, target
target = linkname + strlen(linkname) + 1;
// Check whether the linkname has suspicious components:
// SYMLINK_OUTSIDE_EXTRACT_DIR/etc/passwd sort of thing.
// (Our delayed creation of symlinks is not defending against it,
// we could create SYMLINK_OUTSIDE_EXTRACT_DIR ourself!)
if (!all_dir_components_are_dirs(linkname)) {
errno = ENOTDIR;
goto err;
}
if ((list->data[0] ? link : symlink) (target, linkname)) {
// shared message
err:
bb_perror_msg_and_die("can't create %slink '%s' to '%s'",
list->data[0] ? "hard" : "sym",
linkname, target
);
/* Note: GNU tar 1.34 errors out only _after_ all links are (attempted to be) created */
// Note: GNU tar 1.34 errors out only _after_ all links are (attempted to be) created
// We bail out at once
}
list = list->link;
}
+6 -6
View File
@@ -154,7 +154,7 @@ static NOINLINE int lzo1x_optimize(uint8_t *in, unsigned in_len,
unsigned lit = 0;
unsigned next_lit = NO_LIT;
unsigned nl;
unsigned long o_m1_a = 0, o_m1_b = 0, o_m2 = 0, o_m3_a = 0, o_m3_b = 0;
// unsigned long o_m1_a = 0, o_m1_b = 0, o_m2 = 0, o_m3_a = 0, o_m3_b = 0;
// LZO_UNUSED(wrkmem);
@@ -227,7 +227,7 @@ static NOINLINE int lzo1x_optimize(uint8_t *in, unsigned in_len,
*litp = (unsigned char)((*litp & ~3) | lit);
/* copy over the 2 literals that replace the match */
copy2(ip-2, m_pos, pd(op, m_pos));
o_m1_a++;
// o_m1_a++;
}
/* test if a literal run follows */
else
@@ -249,7 +249,7 @@ static NOINLINE int lzo1x_optimize(uint8_t *in, unsigned in_len,
lit += 2 + t + 3;
*litp = (unsigned char)(lit - 3);
o_m1_b++;
// o_m1_b++;
*op++ = *m_pos++;
*op++ = *m_pos++;
goto copy_literal_run;
@@ -284,7 +284,7 @@ static NOINLINE int lzo1x_optimize(uint8_t *in, unsigned in_len,
/* set new length of previous literal run */
lit += 3 + t + 3;
*litp = (unsigned char)(lit - 3);
o_m2++;
// o_m2++;
*op++ = *m_pos++;
*op++ = *m_pos++;
*op++ = *m_pos++;
@@ -330,7 +330,7 @@ static NOINLINE int lzo1x_optimize(uint8_t *in, unsigned in_len,
*litp = (unsigned char)((*litp & ~3) | lit);
/* copy over the 3 literals that replace the match */
copy3(ip-3, m_pos, pd(op, m_pos));
o_m3_a++;
// o_m3_a++;
}
/* test if a literal run follows */
else if (t == 1 && lit <= 3 && nl == 0
@@ -349,7 +349,7 @@ static NOINLINE int lzo1x_optimize(uint8_t *in, unsigned in_len,
lit += 3 + t + 3;
*litp = (unsigned char)(lit - 3);
o_m3_b++;
// o_m3_b++;
*op++ = *m_pos++;
*op++ = *m_pos++;
*op++ = *m_pos++;
+9 -3
View File
@@ -116,8 +116,13 @@ static int rpm_gettags(const char *filename)
xread(fd, &header, sizeof(header));
if (header.magic_and_ver != htonl(RPM_HEADER_MAGICnVER))
bb_error_msg_and_die("invalid RPM header magic in '%s'", filename);
#if BB_LITTLE_ENDIAN
header.size = ntohl(header.size);
#endif
cnt = ntohl(header.entries);
/* Prevent multiplication overflow leading to undersized allocations */
if (sizeof(cnt) <= 4 && cnt >= 0x00400000) /* ~4 million */
bb_error_msg_and_die("bad RPM header.entries:%u", cnt);
storepos += sizeof(header) + cnt * 16;
G.tagcount += cnt;
@@ -125,9 +130,11 @@ static int rpm_gettags(const char *filename)
xread(fd, &tags[idx], sizeof(tags[0]) * cnt);
while (cnt--) {
rpm_index *tag = &tags[idx];
#if BB_LITTLE_ENDIAN
tag->tag = ntohl(tag->tag);
tag->type = ntohl(tag->type);
tag->count = ntohl(tag->count);
#endif
tag->offset = storepos + ntohl(tag->offset);
if (pass == 0)
tag->tag -= 743;
@@ -146,7 +153,6 @@ static int rpm_gettags(const char *filename)
storepos = (storepos + G_pagesize) & -(int)G_pagesize;
/* remember size for munmap */
G.mapsize = storepos;
/* some NOMMU systems prefer MAP_PRIVATE over MAP_SHARED */
G.map = mmap_read(fd, storepos);
if (G.map == MAP_FAILED)
bb_perror_msg_and_die("mmap '%s'", filename);
@@ -533,9 +539,9 @@ int rpm2cpio_main(int argc UNUSED_PARAM, char **argv)
// /* We need to know whether child (gzip/bzip/etc) exits abnormally */
// signal(SIGCHLD, check_errors_in_children);
str = NULL;
str = rpm_getstr0(TAG_PAYLOADCOMPRESSOR);
if (ENABLE_FEATURE_SEAMLESS_LZMA
&& (str = rpm_getstr0(TAG_PAYLOADCOMPRESSOR)) != NULL
&& str != NULL
&& strcmp(str, "lzma") == 0
) {
// lzma compression can't be detected
+1 -1
View File
@@ -428,7 +428,7 @@ static int writeTarHeader(struct TarBallInfo *tbInfo,
/* GNU "tar cvvf" prints "extended" listing a-la "ls -l" */
/* We don't have such excesses here: for us "v" == "vv" */
/* '/' is probably a GNUism */
fprintf(vbFd, "%s%s\n", header_name,
fprintf(vbFd, "%s%s\n", printable_string(header_name),
S_ISDIR(statbuf->st_mode) ? "/" : "");
}
+28
View File
@@ -29,6 +29,11 @@
//config: bool "Enable --reflink[=auto]"
//config: default y
//config: depends on FEATURE_CP_LONG_OPTIONS
//config:
//config:config FEATURE_CP_SPARSE
//config: bool "Enable --sparse=WHEN"
//config: default y
//config: depends on FEATURE_CP_LONG_OPTIONS
//applet:IF_CP(APPLET_NOEXEC(cp, cp, BB_DIR_BIN, BB_SUID_DROP, cp))
/* NOEXEC despite cases when it can be a "runner" (cp -r LARGE_DIR NEW_DIR) */
@@ -108,6 +113,8 @@
#include "libbb.h"
#include "libcoreutils/coreutils.h"
#define DBG_OPTION_PARSING 0
/* This is a NOEXEC applet. Be very careful! */
int cp_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
@@ -129,6 +136,9 @@ int cp_main(int argc, char **argv)
};
# if ENABLE_FEATURE_CP_REFLINK
char *reflink = NULL;
# endif
# if ENABLE_FEATURE_CP_SPARSE
char *sparse = NULL;
# endif
flags = getopt32long(argv, "^"
FILEUTILS_CP_OPTSTR
@@ -158,12 +168,20 @@ int cp_main(int argc, char **argv)
"parents\0" No_argument "\xfe"
# if ENABLE_FEATURE_CP_REFLINK
"reflink\0" Optional_argument "\xfd"
# endif
# if ENABLE_FEATURE_CP_SPARSE
"sparse\0" Required_argument "\xfc"
# endif
, &last
# if ENABLE_FEATURE_CP_REFLINK
, &reflink
# endif
# if ENABLE_FEATURE_CP_SPARSE
// NOP for now
, &sparse
# endif
);
# if ENABLE_FEATURE_CP_REFLINK
BUILD_BUG_ON((int)OPT_reflink != (int)FILEUTILS_REFLINK);
if (flags & FILEUTILS_REFLINK) {
@@ -175,6 +193,16 @@ int cp_main(int argc, char **argv)
bb_show_usage();
}
# endif
# if DBG_OPTION_PARSING
bb_error_msg("flags: 0x%08x", flags);
# define showopt(o) bb_error_msg("flags & %s(%x):\t%x", #o, o, flags & o);
showopt(FILEUTILS_RMDEST );
showopt(OPT_parents );
showopt(OPT_reflink );
showopt(FILEUTILS_REFLINK_ALWAYS);
return 0;
# undef showopt
# endif
#else
flags = getopt32(argv, "^"
FILEUTILS_CP_OPTSTR
+2 -1
View File
@@ -156,7 +156,7 @@ int id_main(int argc UNUSED_PARAM, char **argv)
const char *prefix;
const char *username;
#if ENABLE_SELINUX
security_context_t scontext = NULL;
char *scontext = NULL;
#endif
if (ENABLE_GROUPS && (!ENABLE_ID || applet_name[0] == 'g')) {
@@ -230,6 +230,7 @@ int id_main(int argc UNUSED_PARAM, char **argv)
prefix = ",";
}
} else if (n < 0) { /* error in get_groups() */
bb_putchar('\n');
if (ENABLE_DESKTOP)
bb_simple_error_msg_and_die("can't get groups");
return EXIT_FAILURE;
+2 -2
View File
@@ -73,7 +73,7 @@ static const char install_longopts[] ALIGN1 =
static void setdefaultfilecon(const char *path)
{
struct stat s;
security_context_t scontext = NULL;
char *scontext = NULL;
if (!is_selinux_enabled()) {
return;
@@ -119,7 +119,7 @@ int install_main(int argc, char **argv)
int ret = EXIT_SUCCESS;
int isdir;
#if ENABLE_SELINUX
security_context_t scontext;
char *scontext;
bool use_default_selinux_context = 1;
#endif
enum {
+546
View File
@@ -0,0 +1,546 @@
/* vi: set sw=4 ts=4: */
/*
* join -- equality join on two files
*
* Written by Morgan Bartlett
* Copyright (C) 2025 Morgan Bartlett
*
* Licensed under GPLv2 or later, see file LICENSE in this source tree.
*/
//config:config JOIN
//config: bool "join (6.6 kb)"
//config: default y
//config: help
//config: Equality join on two files
//applet:IF_JOIN(APPLET_NOEXEC(join, join, BB_DIR_USR_BIN, BB_SUID_DROP, join))
//kbuild:lib-$(CONFIG_JOIN) += join.o
//usage:#define join_trivial_usage
//usage: "[-a 1|2 | -v 1|2] [-e STR] [-o LIST] [-t SEP_CHAR] [-1 NUM] [-2 NUM] FILE1 FILE2"
//usage:#define join_full_usage "\n\n"
//usage: "Join FILE1 and FILE2, writing to stdout\n"
//usage: "\n -a 1|2 Also write unpaired lines from FILE1/2"
//usage: "\n -v 1|2 Only write unpaired lines from FILE1/2"
//usage: "\n -e STR Replace empty fields with STR"
//usage: "\n -o LIST Write the fields in LIST"
//usage: "\n -t CHAR Use a different field separator"
//usage: "\n -1 NUM Join on field NUM from FILE1"
//usage: "\n -2 NUM Join on field NUM from FILE2"
//usage: "\n"
//usage: "\nLIST is a space or comma separated list of 1/2.FIELD or 0 (the join field)"
#include "libbb.h"
#include "unicode.h"
#include "common_bufsiz.h"
/* This is a NOEXEC applet. Be very careful! */
typedef struct {
char *line;
char **fields;
int fieldcount;
} LINE;
typedef struct {
FILE *fp;
int idx; /* index of join field in fields array */
const char *field; /* pointer to lines[0].fields[idx] or "" */
LINE *lines;
LINE pushback;
int linecount; /* number of lines currently cached */
int linecap; /* current capacity of lines array */
} FDAT;
/* "globals" can be made local to main(), but then passing them
down the callchains as parameters requires ~90 bytes of code (on x86).
*/
struct globals {
int *format; // = NULL;
const char *empty_str;
/* \0 can't be separator, 0 means: "whitespace+" pattern */
char sep; // = 0;
} FIX_ALIASING;
#define G (*(struct globals*)bb_common_bufsiz1)
#define INIT_G() do { \
setup_common_bufsiz(); \
/* we have to zero it out because of NOEXEC */ \
memset(&G, 0, sizeof(G)); \
} while (0)
/* split s by sep, and put the results into *curr */
static void field_split(char *s, LINE *curr)
{
/* compare awk_split from editors/awk.c */
int n;
char *ps = s;
char *s1 = s;
char **sl;
size_t sn;
/* in worst case, every character is a separator */
curr->fields = sl = xzalloc(sizeof(char*) * (strlen(s) + 2));
curr->line = s;
n = 0;
if (G.sep != '\0') { /* single-character split */
while ((s1 = strchr(ps, G.sep)) != NULL) {
sl[n] = ps;
*s1 = '\0';
ps = s1 + 1;
n++;
}
/* Add the last field */
sl[n] = ps;
n++;
curr->fieldcount = n;
return;
}
/* default split: skip the initial whitespace and then any run
of non-whitespace characters is a field */
while (*s) {
/* blanks are space and tab in the POSIX locale */
while (*s == ' ' || *s == '\t')
s++;
if (!*s)
break;
s1 = strpbrk(s, " \t");
if (s1 == NULL) {
/* last field */
sn = strlen(s);
} else {
sn = s1 - s;
*s1 = '\0';
}
sl[n] = s;
n++;
s += sn + 1;
}
curr->fieldcount = n;
}
static inline void freefields(LINE *lp)
{
free(lp->line);
free(lp->fields);
lp->line = NULL;
lp->fields = NULL;
}
static void freelines(FDAT *f)
{
for (int n = 0; n < f->linecount; n++) {
freefields(f->lines + n);
}
f->linecount = 0;
f->field = "";
}
static void readfields(FDAT *f)
{
LINE curr = { .line = NULL, .fields = NULL, .fieldcount = 0 };
char *line;
const char *field2;
bool first = TRUE;
freelines(f);
while (true) {
if (first && f->pushback.fields) {
/* first check for a pushed back line */
curr = f->pushback;
f->pushback = (LINE) { .line = NULL, .fields = NULL, .fieldcount = 0 };
} else {
/* read a line and split */
line = xmalloc_fgetline(f->fp);
if (line == NULL) {
return;
}
field_split(line, &curr);
}
if (f->idx >= curr.fieldcount)
field2 = "";
else
field2 = curr.fields[f->idx];
/* Ensure strcmp() matches on first pass through loop */
if (first)
f->field = field2;
if (strcmp(f->field, field2) == 0) {
/* add to the stack */
if (f->linecount == f->linecap) {
f->linecap = f->linecap ? f->linecap * 2 : 8;
f->lines = xrealloc(f->lines, sizeof(LINE) * f->linecap);
}
f->lines[f->linecount++] = curr;
} else {
f->pushback = curr;
return;
}
first = FALSE;
}
}
static inline const char *fieldorempty(const char *field)
{
if (*field == '\0')
return G.empty_str;
return field;
}
static void printfields(FDAT *f1, FDAT *f2)
{
const char *field = (f1 == NULL) ? f2->field : f1->field;
int linef1;
int linef2;
int fn;
int format_fl;
int format_idx;
int *formatcurr;
bool first;
char sep;
LINE *l1;
LINE *l2;
sep = (G.sep == '\0') ? ' ' : G.sep;
for (linef1 = 0; linef1 < (f1 ? f1->linecount : 1); linef1++) {
l1 = f1 ? &f1->lines[linef1] : NULL;
for (linef2 = 0; linef2 < (f2 ? f2->linecount : 1); linef2++) {
l2 = f2 ? &f2->lines[linef2] : NULL;
if (G.format) {
/*
Format is a sort of null-terminated array:
They are indexed by [n] for file number and [n + 1] for field number.
If file number is 0 then that is the null-terminator.
If file number is neither 1 nor 2 then we have the join field.
*/
first = true;
formatcurr = G.format;
while (formatcurr[0]) {
if (first)
first = false;
else
bb_putchar(sep);
format_fl = formatcurr[0];
format_idx = formatcurr[1];
if (format_fl == 1) {
if (l1 != NULL && l1->fieldcount > format_idx)
fputs_stdout(fieldorempty(l1->fields[format_idx]));
else
fputs_stdout(G.empty_str);
} else if (format_fl == 2) {
if (l2 != NULL && l2->fieldcount > format_idx)
fputs_stdout(fieldorempty(l2->fields[format_idx]));
else
fputs_stdout(G.empty_str);
} else
fputs_stdout(fieldorempty(field));
formatcurr += 2;
}
} else {
fputs_stdout(fieldorempty(field));
fn = 0;
if (l1 != NULL)
while (l1->fields[fn]) {
if (fn != f1->idx) {
bb_putchar(sep);
fputs_stdout(fieldorempty(l1->fields[fn]));
}
fn++;
}
fn = 0;
if (l2 != NULL)
while (l2->fields[fn]) {
if (fn != f2->idx) {
bb_putchar(sep);
fputs_stdout(fieldorempty(l2->fields[fn]));
}
fn++;
}
}
bb_putchar('\n');
}
}
}
static void parsejformat(const char *format_str)
{
int *format;
int field_idx;
char scache[20] = { 0 };
int n = 0;
const char *s1 = format_str;
size_t sn;
/* The most formats we can have is if the format_str is noted as 0,0,0,0
which ends up being (strlen + 1) / 2
and then we need to have two for each entry plus one for the terminator.
( (strlen+1) / 2 * 2 is optimized out in the alloc) */
G.format = format = xzalloc(sizeof(format[0]) * ((strlen(format_str) + 1) + 1));
/* default split: skip the initial whitespace and then any run
of non-whitespace characters is a field */
while (*format_str) {
/* blanks are space and tab in the POSIX locale */
while (*format_str == ' ' || *format_str == '\t' || *format_str == ',')
format_str++;
if (!*format_str)
break;
s1 = strpbrk(format_str, " \t,");
if (s1 == NULL)
/* last field */
sn = strlen(format_str);
else
sn = s1 - format_str;
if (sn == 1 && *format_str == '0') {
format[n * 2] = 3;
} else if (sn >= 3 && (*format_str == '1' || *format_str == '2') && format_str[1] == '.') {
if (sn > 21) /* res_str > 19 */
bb_simple_error_msg_and_die("field specifier too large");
memcpy(scache, format_str + 2, sn - 2);
scache[sn - 2] = '\0';
field_idx = xatoi_positive(scache);
if (--field_idx < 0)
bb_simple_error_msg_and_die("field number can't be 0");
format[n * 2] = *format_str - '0';
format[n * 2 + 1] = field_idx;
} else {
bb_simple_error_msg_and_die("field specifier must be 0, 1.x or 2.x");
}
n++;
format_str += sn;
}
}
int join_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
int join_main(int argc UNUSED_PARAM, char **argv)
{
struct {
llist_t *unpaired_list; // = NULL;
const char *format_str; // = NULL;
bool print1unpaired; // = false;
bool print2unpaired; // = false;
bool printpaired;
FDAT f1; // = { };
FDAT f2; // = { };
} L;
#define unpaired_list L.unpaired_list
#define format_str L.format_str
#define print1unpaired L.print1unpaired
#define print2unpaired L.print2unpaired
#define printpaired L.printpaired
#define f1 L.f1
#define f2 L.f2
char *separator;
uint32_t opts;
/* Must match getopt32 call */
enum {
FLAG_UNPAIRED_ADD = (1 << 0),
FLAG_UNPAIRED_ONLY = (1 << 1),
FLAG_EMPTY_STRING = (1 << 2),
FLAG_LIST_OUTPUT = (1 << 3),
FLAG_SEP_USED = (1 << 4),
FLAG_FIELD_1 = (1 << 5),
FLAG_FIELD_2 = (1 << 6),
};
INIT_G();
G.empty_str = "";
memset(&L, 0, sizeof(L));
init_unicode();
opts = getopt32(argv,
"^a:*v:*"
"e:"
"o:"
"t:"
"1:+2:+"
"\0""=2:a--v:v--a",
&unpaired_list,
&unpaired_list,
&G.empty_str,
&format_str,
&separator,
&f1.idx,
&f2.idx);
argv += optind;
printpaired = !(opts & FLAG_UNPAIRED_ONLY);
if (opts & (FLAG_UNPAIRED_ADD|FLAG_UNPAIRED_ONLY)) {
char *unpaired_str;
while ((unpaired_str = llist_pop(&unpaired_list)) != NULL) {
if (*unpaired_str == '1')
print1unpaired = true;
else if (*unpaired_str == '2')
print2unpaired = true;
else
bb_show_usage();
if (unpaired_str[1])
bb_show_usage();
}
}
if (((opts & FLAG_FIELD_1) && --f1.idx < 0)
|| ((opts & FLAG_FIELD_2) && --f2.idx < 0)
) {
bb_simple_error_msg_and_die("field 0 doesn't exist");
}
if (opts & FLAG_SEP_USED) {
if (separator[0] && separator[1])
bb_simple_error_msg_and_die("separators are single characters");
G.sep = *separator;
}
if (opts & FLAG_LIST_OUTPUT)
parsejformat(format_str);
f1.fp = xfopen_stdin(argv[0]);
f2.fp = xfopen_stdin(argv[1]);
if (f1.fp == f2.fp)
bb_simple_error_msg_and_die("can't combine stdin with itself");
/*
Outline of the program:
- Read a line set from each file into cache
- While there are cached current lines from both files:
- If the two indexing fields are the same:
- If no unpaired_only options:
- Print joined line set formatted with fields
- Read line sets from both files
- Elseif indexing1 < indexing2 then
- If print1unpaired:
- Print line set from file 1
- Read another line set from file 1
- Elseif indexing1 > indexing2 then
- If print2unpaired:
- Print line set from file 2
- Read another line set from file 2
- If there are cached lines from file 1 AND print1unpaired:
- Print the rest of the lines from file 1
- If there are cached lines from file 2 AND print2unpaired:
- Print the rest of the lines from file 2
*/
/*
Notes for POSIX:
https://pubs.opengroup.org/onlinepubs/9699919799/utilities/join.html
Multiple instances of the same key are meant to give combinatorial results.
E.g:
file1:
a 1
a 2
file2:
a A
a B
a C
result:
a 1 A
a 1 B
a 1 C
a 2 A
a 2 B
a 2 C
This is done in this implementation by reading all the lines that have the same key
and then iterating through the combinations when printing them.
(test with `./busybox join <(printf 'a 1\na 2\n';) <(printf 'a A\na B\na C\n')`)
*/
readfields(&f1);
readfields(&f2);
while (f1.linecount != 0 && f2.linecount != 0) {
int res = strcmp(f1.field, f2.field);
if (res == 0) {
if (printpaired)
printfields(&f1, &f2);
readfields(&f1);
readfields(&f2);
} else if (res < 0) {
if (print1unpaired)
printfields(&f1, NULL);
readfields(&f1);
} else {
if (print2unpaired)
printfields(NULL, &f2);
readfields(&f2);
}
}
if (print1unpaired) {
while (f1.linecount != 0) {
printfields(&f1, NULL);
readfields(&f1);
}
}
if (print2unpaired) {
while (f2.linecount != 0) {
printfields(NULL, &f2);
readfields(&f2);
}
}
#if ENABLE_FEATURE_CLEAN_UP
if (f1.linecap) {
freelines(&f1);
free(f1.lines);
}
if (f2.linecap) {
freelines(&f2);
free(f2.lines);
}
free(G.format);
fclose_if_not_stdin(f1.fp);
fclose_if_not_stdin(f2.fp);
#endif
fflush_stdout_and_exit_SUCCESS();
}
+1 -1
View File
@@ -26,7 +26,7 @@ mode_t FAST_FUNC getopt_mk_fifo_nod(char **argv)
mode_t mode = 0666;
char *smode = NULL;
#if ENABLE_SELINUX
security_context_t scontext;
char *scontext;
#endif
int opt;
opt = getopt32(argv, "m:" IF_SELINUX("Z:"), &smode IF_SELINUX(,&scontext));
+1 -1
View File
@@ -311,7 +311,7 @@ struct dnode {
const char *name; /* usually basename, but think "ls -l dir/file" */
const char *fullname; /* full name (usable for stat etc) */
struct dnode *dn_next; /* for linked list */
IF_SELINUX(security_context_t sid;)
IF_SELINUX(char *sid;)
smallint fname_allocated;
/* Used to avoid re-doing [l]stat at printout stage
+1 -1
View File
@@ -57,7 +57,7 @@ int mkdir_main(int argc UNUSED_PARAM, char **argv)
unsigned opt;
char *smode;
#if ENABLE_SELINUX
security_context_t scontext;
char *scontext;
#endif
opt = getopt32long(argv, "m:pv" IF_SELINUX("Z:"),
+7 -7
View File
@@ -355,6 +355,7 @@ static char **print_formatted(char *f, char **argv, int *conv_err)
{
static const char format_chars[] ALIGN1 = "diouxXfeEgGcs";
char *p = (char*)strchr(format_chars, *f);
const char *arg = "0";
/* needed - try "printf %" without it */
if (p == NULL || *f == '\0') {
bb_error_msg("%s: invalid format", direc_start);
@@ -373,15 +374,14 @@ static char **print_formatted(char *f, char **argv, int *conv_err)
direc_length += 2;
direc_start = p;
} else {
if (p - format_chars >= 11) /* %c or %s? */
++arg; /* "" */
p = NULL;
}
if (*argv) {
print_direc(direc_start, direc_length, field_width,
precision, *argv++);
} else {
print_direc(direc_start, direc_length, field_width,
precision, "");
}
if (*argv)
arg = *argv++;
print_direc(direc_start, direc_length, field_width,
precision, arg);
*conv_err |= errno;
free(p);
}
+13 -6
View File
@@ -163,13 +163,18 @@ static char *get_key(char *str, struct sort_key *key, int flags)
/* Loop through fields */
else {
unsigned char ch = 0;
/* -kSTART,N.ENDCHAR: stop at the start of field N instead
* of its end, ENDCHAR below is an offset from there */
unsigned fields = key->range[2*j] + j;
if (j && key->range[3])
fields--;
end = 0;
for (i = 1; i < key->range[2*j] + j; i++) {
for (i = 1; i < fields; i++) {
if (key_separator) {
/* Skip body of key and separator */
while ((ch = str[end]) != '\0') {
end++;
end++;
if (ch == key_separator)
break;
}
@@ -186,9 +191,9 @@ static char *get_key(char *str, struct sort_key *key, int flags)
}
}
/* Remove last delim: "abc:def:" => "abc:def" */
if (j && ch) {
if (j && ch && !key->range[3]) {
//if (str[end-1] != key_separator)
// bb_error_msg(_and_die("BUG! "
// bb_error_msg_and_die("BUG! "
// "str[start:%d,end:%d]:'%.*s'",
// start, end, (int)(end-start), &str[start]);
end--;
@@ -203,9 +208,11 @@ static char *get_key(char *str, struct sort_key *key, int flags)
/* Strip trailing whitespace if necessary */
if (flags & FLAG_bb)
while (end > start && isspace(str[end-1])) end--;
/* -kSTART,N.ENDCHAR: honor ENDCHAR (1-based) */
/* -kSTART,N.ENDCHAR: honor ENDCHAR (1-based), counted from the
* start of field N, which the loop above stopped at
*/
if (key->range[3]) {
end = key->range[3];
end += key->range[3];
if (end > len) end = len;
}
/* -kN.STARTCHAR[,...]: honor STARTCHAR (1-based) */
+84 -72
View File
@@ -248,53 +248,84 @@ static void strcatc(char *str, char c)
str[len] = '\0';
}
static void printfs(char *pformat, const char *msg)
/* printf is a vararg function, on some arches varargs
* require more code, increasing code size win
* from factoring out common uses of printf into
* non-vararg functions.
*/
static void printf_s(char *pformat, const char *msg)
{
strcatc(pformat, 's');
printf(pformat, msg);
}
static void printf_lu(char *pformat, unsigned long v)
{
strcat(pformat, "lu");
printf(pformat, v);
}
static void printf_llu(char *pformat, unsigned long long v)
{
strcat(pformat, "llu");
printf(pformat, v);
}
static void printf_lx(char *pformat, unsigned long v)
{
strcat(pformat, "lx");
printf(pformat, v);
}
static void printf_llx(char *pformat, unsigned long long v)
{
strcat(pformat, "llx");
printf(pformat, v);
}
static void printf_time_t(char *pformat, time_t val)
{
#define TYPE_SIGNED(t) ((t) -1 < (t) 0)
if (TYPE_SIGNED(time_t)) {
strcat(pformat, "lld");
printf(pformat, (long long) val);
} else {
printf_llu(pformat, val);
}
}
#if ENABLE_FEATURE_STAT_FILESYSTEM
/* print statfs info */
static void FAST_FUNC print_statfs(char *pformat, const char m,
const char *const filename, const void *data
IF_SELINUX(, security_context_t scontext))
IF_SELINUX(, char *scontext))
{
const struct statfs *statfsbuf = data;
if (m == 'n') {
printfs(pformat, filename);
printf_s(pformat, filename);
} else if (m == 'i') {
strcat(pformat, "llx");
printf(pformat, get_f_fsid(statfsbuf));
printf_llx(pformat, get_f_fsid(statfsbuf));
} else if (m == 'l') {
strcat(pformat, "lu");
printf(pformat, (unsigned long) statfsbuf->f_namelen);
printf_lu(pformat, statfsbuf->f_namelen);
} else if (m == 't') {
strcat(pformat, "lx");
printf(pformat, (unsigned long) statfsbuf->f_type); /* no equiv */
printf_lx(pformat, statfsbuf->f_type); /* no equiv */
} else if (m == 'T') {
printfs(pformat, human_fstype(statfsbuf->f_type));
printf_s(pformat, human_fstype(statfsbuf->f_type));
} else if (m == 'b') {
strcat(pformat, "llu");
printf(pformat, (unsigned long long) statfsbuf->f_blocks);
printf_llu(pformat, statfsbuf->f_blocks);
} else if (m == 'f') {
strcat(pformat, "llu");
printf(pformat, (unsigned long long) statfsbuf->f_bfree);
printf_llu(pformat, statfsbuf->f_bfree);
} else if (m == 'a') {
strcat(pformat, "llu");
printf(pformat, (unsigned long long) statfsbuf->f_bavail);
printf_llu(pformat, statfsbuf->f_bavail);
} else if (m == 's' || m == 'S') {
strcat(pformat, "lu");
printf(pformat, (unsigned long) statfsbuf->f_bsize);
printf_lu(pformat, statfsbuf->f_bsize);
} else if (m == 'c') {
strcat(pformat, "llu");
printf(pformat, (unsigned long long) statfsbuf->f_files);
printf_llu(pformat, statfsbuf->f_files);
} else if (m == 'd') {
strcat(pformat, "llu");
printf(pformat, (unsigned long long) statfsbuf->f_ffree);
printf_llu(pformat, statfsbuf->f_ffree);
# if ENABLE_SELINUX
} else if (m == 'C' && (option_mask32 & OPT_SELINUX)) {
printfs(pformat, scontext);
printf_s(pformat, scontext);
# endif
} else {
strcatc(pformat, 'c');
@@ -306,15 +337,14 @@ static void FAST_FUNC print_statfs(char *pformat, const char m,
/* print stat info */
static void FAST_FUNC print_stat(char *pformat, const char m,
const char *const filename, const void *data
IF_SELINUX(, security_context_t scontext))
IF_SELINUX(, char *scontext))
{
#define TYPE_SIGNED(t) (! ((t) 0 < (t) -1))
struct stat *statbuf = (struct stat *) data;
struct passwd *pw_ent;
struct group *gw_ent;
if (m == 'n') {
printfs(pformat, filename);
printf_s(pformat, filename);
} else if (m == 'N') {
strcatc(pformat, 's');
if (S_ISLNK(statbuf->st_mode)) {
@@ -327,78 +357,60 @@ static void FAST_FUNC print_stat(char *pformat, const char m,
printf(pformat, filename);
}
} else if (m == 'd') {
strcat(pformat, "llu");
printf(pformat, (unsigned long long) statbuf->st_dev);
printf_llu(pformat, statbuf->st_dev);
} else if (m == 'D') {
strcat(pformat, "llx");
printf(pformat, (unsigned long long) statbuf->st_dev);
printf_llx(pformat, statbuf->st_dev);
} else if (m == 'i') {
strcat(pformat, "llu");
printf(pformat, (unsigned long long) statbuf->st_ino);
printf_llu(pformat, statbuf->st_ino);
} else if (m == 'a') {
strcat(pformat, "lo");
printf(pformat, (unsigned long) (statbuf->st_mode & (S_ISUID|S_ISGID|S_ISVTX|S_IRWXU|S_IRWXG|S_IRWXO)));
} else if (m == 'A') {
char modestr[12];
printfs(pformat, bb_mode_string(modestr, statbuf->st_mode));
printf_s(pformat, bb_mode_string(modestr, statbuf->st_mode));
} else if (m == 'f') {
strcat(pformat, "lx");
printf(pformat, (unsigned long) statbuf->st_mode);
printf_lx(pformat, statbuf->st_mode);
} else if (m == 'F') {
printfs(pformat, file_type(statbuf));
printf_s(pformat, file_type(statbuf));
} else if (m == 'h') {
strcat(pformat, "lu");
printf(pformat, (unsigned long) statbuf->st_nlink);
printf_lu(pformat, statbuf->st_nlink);
} else if (m == 'u') {
strcat(pformat, "lu");
printf(pformat, (unsigned long) statbuf->st_uid);
printf_lu(pformat, statbuf->st_uid);
} else if (m == 'U') {
pw_ent = getpwuid(statbuf->st_uid);
printfs(pformat, (pw_ent != NULL) ? pw_ent->pw_name : "UNKNOWN");
printf_s(pformat, (pw_ent != NULL) ? pw_ent->pw_name : "UNKNOWN");
} else if (m == 'g') {
strcat(pformat, "lu");
printf(pformat, (unsigned long) statbuf->st_gid);
printf_lu(pformat, statbuf->st_gid);
} else if (m == 'G') {
gw_ent = getgrgid(statbuf->st_gid);
printfs(pformat, (gw_ent != NULL) ? gw_ent->gr_name : "UNKNOWN");
printf_s(pformat, (gw_ent != NULL) ? gw_ent->gr_name : "UNKNOWN");
} else if (m == 't') {
strcat(pformat, "lx");
printf(pformat, (unsigned long) major(statbuf->st_rdev));
printf_lx(pformat, major(statbuf->st_rdev));
} else if (m == 'T') {
strcat(pformat, "lx");
printf(pformat, (unsigned long) minor(statbuf->st_rdev));
printf_lx(pformat, minor(statbuf->st_rdev));
} else if (m == 's') {
strcat(pformat, "llu");
printf(pformat, (unsigned long long) statbuf->st_size);
printf_llu(pformat, statbuf->st_size);
} else if (m == 'B') {
strcat(pformat, "lu");
printf(pformat, (unsigned long) 512); //ST_NBLOCKSIZE
printf_lu(pformat, 512); //ST_NBLOCKSIZE
} else if (m == 'b') {
strcat(pformat, "llu");
printf(pformat, (unsigned long long) statbuf->st_blocks);
printf_llu(pformat, statbuf->st_blocks);
} else if (m == 'o') {
strcat(pformat, "lu");
printf(pformat, (unsigned long) statbuf->st_blksize);
printf_lu(pformat, statbuf->st_blksize);
} else if (m == 'x') {
printfs(pformat, human_time(&statbuf->st_atim));
printf_s(pformat, human_time(&statbuf->st_atim));
} else if (m == 'X') {
strcat(pformat, TYPE_SIGNED(time_t) ? "ld" : "lu");
/* note: (unsigned long) would be wrong:
* imagine (unsigned long64)int32 */
printf(pformat, (long) statbuf->st_atime);
printf_time_t(pformat, statbuf->st_atime);
} else if (m == 'y') {
printfs(pformat, human_time(&statbuf->st_mtim));
printf_s(pformat, human_time(&statbuf->st_mtim));
} else if (m == 'Y') {
strcat(pformat, TYPE_SIGNED(time_t) ? "ld" : "lu");
printf(pformat, (long) statbuf->st_mtime);
printf_time_t(pformat, statbuf->st_mtime);
} else if (m == 'z') {
printfs(pformat, human_time(&statbuf->st_ctim));
printf_s(pformat, human_time(&statbuf->st_ctim));
} else if (m == 'Z') {
strcat(pformat, TYPE_SIGNED(time_t) ? "ld" : "lu");
printf(pformat, (long) statbuf->st_ctime);
printf_time_t(pformat, statbuf->st_ctime);
# if ENABLE_SELINUX
} else if (m == 'C' && (option_mask32 & OPT_SELINUX)) {
printfs(pformat, scontext);
printf_s(pformat, scontext);
# endif
} else {
strcatc(pformat, 'c');
@@ -408,9 +420,9 @@ static void FAST_FUNC print_stat(char *pformat, const char m,
static void print_it(const char *masterformat,
const char *filename,
void FAST_FUNC (*print_func)(char*, char, const char*, const void* IF_SELINUX(, security_context_t scontext)),
void FAST_FUNC (*print_func)(char*, char, const char*, const void* IF_SELINUX(, char *scontext)),
const void *data
IF_SELINUX(, security_context_t scontext))
IF_SELINUX(, char *scontext))
{
/* Create a working copy of the format string */
char *format = xstrdup(masterformat);
@@ -475,7 +487,7 @@ static bool do_statfs(const char *filename, const char *format)
const char *format;
#endif
#if ENABLE_SELINUX
security_context_t scontext = NULL;
char *scontext = NULL;
if (option_mask32 & OPT_SELINUX) {
if ((option_mask32 & OPT_DEREFERENCE
@@ -590,7 +602,7 @@ static bool do_stat(const char *filename, const char *format)
{
struct stat statbuf;
#if ENABLE_SELINUX
security_context_t scontext = NULL;
char *scontext = NULL;
if (option_mask32 & OPT_SELINUX) {
if ((option_mask32 & OPT_DEREFERENCE
+5 -5
View File
@@ -621,15 +621,15 @@ static int binop(void)
/* if (is_file_op(op->op_num)) */
{
struct stat b1, b2;
int sb1 = stat(opnd1, &b1);
int sb2 = stat(opnd2, &b2);
if (stat(opnd1, &b1) || stat(opnd2, &b2))
return 0; /* false, since at least one stat failed */
if (op->op_num == FILNT)
return b1.st_mtime > b2.st_mtime;
return !sb1 && (sb2 || b1.st_mtime > b2.st_mtime);
if (op->op_num == FILOT)
return b1.st_mtime < b2.st_mtime;
return !sb2 && (sb1 || b1.st_mtime < b2.st_mtime);
/*if (op->op_num == FILEQ)*/
return b1.st_dev == b2.st_dev && b1.st_ino == b2.st_ino;
return !sb1 && !sb2 && b1.st_dev == b2.st_dev && b1.st_ino == b2.st_ino;
}
/*return 1; - NOTREACHED */
}
+15 -11
View File
@@ -113,15 +113,20 @@ static unsigned expand(char *arg, char **buffer_p)
*buffer_p = buffer = xrealloc(buffer, size);
}
if (*arg == '\\') {
const char *z;
arg++;
z = arg;
ac = bb_process_escape_sequence(&z);
arg = (char *)z;
arg--;
char *z = ++arg;
if (*z == '-') {
/* "\-X" isn't a range, but a literal dash and X */
buffer[pos++] = '-';
continue;
}
ac = bb_process_escape_sequence((void*)&z);
// if unknown seq "\k": ac='\', z->k: store '\' before 'k'
// if known seq "\n": ac='\n', z->past n: store '\n' into 'n'
// if known seq "\041": ac='!', z->past 1: store '!' into '1'
arg = z - 1;
*arg = ac;
/*
* fall through, there may be a range.
* fall through, there may be a range. Example: "\n-@"
* If not, current char will be treated anyway.
*/
}
@@ -134,10 +139,9 @@ static unsigned expand(char *arg, char **buffer_p)
i = (unsigned char) *arg;
arg += 3; /* skip 0-9 or 0-\ */
if (ac == '\\') {
const char *z;
z = arg;
ac = bb_process_escape_sequence(&z);
arg = (char *)z;
char *z = arg;
ac = bb_process_escape_sequence((void*)&z);
arg = z;
}
while (i <= ac) /* ok: i is unsigned _int_ */
buffer[pos++] = i++;
+23 -9
View File
@@ -40,6 +40,15 @@
//config: fsck is used to check and optionally repair one or more filesystems.
//config: In actuality, fsck is simply a front-end for the various file system
//config: checkers (fsck.fstype) available under Linux.
//config:
//config:config FEATURE_FSCK_LABEL
//config: bool "Support specifying devices by label or UUID"
//config: default y
//config: depends on FSCK
//config: select VOLUMEID
//config: help
//config: This allows for specifying a device by label or uuid, rather than by
//config: name. This feature utilizes the same functionality as blkid/findfs.
//applet:IF_FSCK(APPLET(fsck, BB_DIR_SBIN, BB_SUID_DROP))
@@ -60,6 +69,11 @@
//usage: "\n -t TYPE List of filesystem types to check"
#include "libbb.h"
#if ENABLE_FEATURE_FSCK_LABEL
# include "volume_id.h"
#else
# define resolve_mount_spec(fsname) ((void)0)
#endif
#include "common_bufsiz.h"
/* "progress indicator" code is somewhat buggy and ext[23] specific.
@@ -318,7 +332,7 @@ static struct fs_info *create_fs_device(const char *device, const char *mntpnt,
if (strchr(type, ','))
type = (char *)"auto";
fs->type = xstrdup(type);
fs->opts = xstrdup(opts ? opts : "");
fs->opts = xstrdup(opts); /* can be NULL */
fs->passno = passno < 0 ? 1 : passno;
/*fs->flags = 0; */
/*fs->next = NULL; */
@@ -358,7 +372,7 @@ static void load_fs_info(const char *filename)
}
/* Lookup filesys in /etc/fstab and return the corresponding entry. */
static struct fs_info *lookup(char *filesys)
static struct fs_info *lookup_in_fs_info(const char *filesys)
{
struct fs_info *fs;
@@ -522,7 +536,7 @@ static int wait_many(int flags)
* Execute a particular fsck program, and link it into the list of
* child processes we are waiting for.
*/
static void execute(const char *type, const char *device,
static void execute(const char *type, char *device,
const char *mntpt /*, int interactive */)
{
int i;
@@ -542,7 +556,10 @@ static void execute(const char *type, const char *device,
}
#endif
G.args[G.num_args - 2] = (char*)device;
/* int free_the_pointer = */ resolve_mount_spec(&device);
/* NB: the possible new pointer is malloced, we leak it */
G.args[G.num_args - 2] = device;
/* G.args[G.num_args - 1] = NULL; - already is */
if (G.verbose || G.noexecute) {
@@ -630,7 +647,7 @@ static void fsck_device(struct fs_info *fs /*, int interactive */)
* Returns TRUE if a partition on the same disk is already being
* checked.
*/
static int device_already_active(char *device)
static int device_already_active(const char *device)
{
struct fsck_instance *inst;
char *base;
@@ -971,9 +988,6 @@ int fsck_main(int argc UNUSED_PARAM, char **argv)
/* "/dev/blk" or "/path" or "UUID=xxx" or "LABEL=xxx" */
if ((arg[0] == '/' && !opts_for_fsck) || strchr(arg, '=')) {
// FIXME: must check that arg is a blkdev, or resolve
// "/path", "UUID=xxx" or "LABEL=xxx" into block device name
// ("UUID=xxx"/"LABEL=xxx" can probably shifted to fsck.auto duties)
devices = xrealloc_vector(devices, 2, num_devices);
devices[num_devices++] = arg;
continue;
@@ -1093,7 +1107,7 @@ int fsck_main(int argc UNUSED_PARAM, char **argv)
break;
}
fs = lookup(devices[i]);
fs = lookup_in_fs_info(devices[i]);
if (!fs)
fs = create_fs_device(devices[i], "", "auto", NULL, -1);
fsck_device(fs /*, interactive */);
+356 -106
View File
@@ -890,24 +890,30 @@ static char *nextword(char **s)
return p;
}
/* Note: will NOT stop at NUL (either on <NUL> or \<newline><NUL>):
* *s will be advanced past NUL!
* Make sure you always check NUL return before continuing.
*/
static char nextchar(char **s)
{
char c, *pps;
char c;
again:
c = *(*s)++;
pps = *s;
if (c == '\\')
if (c == '\\') {
char *pps = *s;
c = bb_process_escape_sequence((const char**)s);
/* Example awk statement:
* s = "abc\"def"
* we must treat \" as "
*/
if (c == '\\' && *s == pps) { /* unrecognized \z? */
c = *(*s); /* yes, fetch z */
if (c) { /* advance unless z = NUL */
(*s)++;
if (c == '\n') /* \<newline>? eat it */
goto again;
/* Example awk statement:
* s = "abc\"def"
* we must treat \" as "
*/
if (c == '\\' && *s == pps) { /* unrecognized \z? */
c = *(*s); /* yes, fetch z */
if (c) { /* advance unless z = NUL */
(*s)++;
if (c == '\n') /* \<newline>? eat it */
goto again;
}
}
}
return c;
@@ -961,20 +967,71 @@ static double my_strtod_or_hexoct(char **pp)
/* -------- working with variables (set/get/copy/etc) -------- */
/* Perform OFMT or CONVFMT float-to-string conversion.
* According to POSIX, awk's behavior is undefined if OFMT
* contains anything but a floating-point conversion specification.
* However, GNU awk 5.3.0 allows prefix and suffix: "N:%.1f!"
* integer formats (%d et al), %s formats.
* It even allows %c, but we don't implement this.
* GNU awk also supports %ld, %lx, we don't (yet). GNU awk doesn't support %lld.
*/
static const char *fmt_num(const char *format, double n)
{
if (n == (long long)n) {
snprintf(g_buf, MAXVARFMT, "%lld", (long long)n);
if (n == trunc(n)) {
/* No fractionals? Try: awk -v OFMT='R:%d!' 'BEGIN { print 2**128 }' */
snprintf(g_buf, MAXVARFMT, "%.0f", n);
} else {
const char *s = format;
const char *p2;
char c;
do { c = *s; } while (c && *++s);
/* Find %SPEC in format string */
for (;;) {
s = strchr(s, '%');
if (!s)
goto print_verbatim;
if (s[1] != '%')
break;
s += 2; /* skip "%%" */
}
/* We are at %SPEC. Is there a second %SPEC? (%% and trailing % aren't %SPEC) */
p2 = s;
for (;;) {
p2 = strchr(p2 + 1, '%');
if (!p2) break; /* no more %SPEC: ok */
if (*++p2 == '\0') break; /* trailing lone %: ok */
if (*p2 != '%') goto INV_FMT; /* more than one %SPEC: error */
/* else: %% - ok, look for %SPEC past it by iterating once more */
}
//TODO: factor out awk_printf machinery to make %d print large numbers too. Example:
// awk -v OFMT='R:%d!' 'BEGIN { print 184467440737095.1 }'
// R:184467440737095!
/* Find the format letter */
for (;;) {
c = *++s;
if (!c) /* unterminated "....%SPEC" */
goto print_verbatim;
if (c == '*')
goto INV_FMT; /* CONVFMT/OFMT='%*f' is not allowed */
if (isalpha(c))
break;
}
if (strchr("diouxX", c)) {
snprintf(g_buf, MAXVARFMT, format, (int)n);
} else if (strchr("eEfFgGaA", c)) {
print_verbatim:
snprintf(g_buf, MAXVARFMT, format, n);
} else if (c == 's') {
/* GNU awk OFMT="%..s" formats number through "%.6g",
* then prints string through %s:
*/
char nbuf[sizeof(n)*3 + 12]; /* +5 should do? +12 is paranoia */
sprintf(nbuf, "%.6g", n);
snprintf(g_buf, MAXVARFMT, format, nbuf);
} else {
INV_FMT:
syntax_error(EMSG_INV_FMT);
}
}
@@ -1205,11 +1262,22 @@ static uint32_t next_token(uint32_t expected)
/* it's a string */
char *s = t_string = ++p;
while (*p != '"') {
char *pp;
if (*p == '\0' || *p == '\n')
char c, *pp;
/* Since we need to handle \<newline><NUL>
* below, we can handle ordinary NUL there as well,
* instead of here. Thus commented out.
*/
if (/* *p == '\0' || */ *p == '\n')
syntax_error(EMSG_UNEXP_EOS);
pp = p;
*s++ = nextchar(&pp);
c = *s++ = nextchar(&pp);
/* awk 'BEGIN { print "unterminated\
* '
* results in NUL here after nextchar() eats \<newline>
*/
if (c == '\0')
syntax_error(EMSG_UNEXP_EOS);
p = pp;
}
p++;
@@ -2420,9 +2488,9 @@ static int awk_getline(rstream *rsm, var *v)
#endif
static char *awk_printf(node *n, size_t *len)
{
char *b;
char *fmt, *f;
size_t i;
char *fmt, *fmt_cur;
char *res_buf;
size_t res_len;
//tmpvar = nvalloc(1);
#define TMPVAR (&G.awk_printf__tmpvar)
@@ -2430,103 +2498,245 @@ static char *awk_printf(node *n, size_t *len)
// to decrease memory consumption in deeply-recursive awk programs.
// The rule to work safely is to never call evaluate() while our static
// TMPVAR's value is still needed.
fmt = f = xstrdup(getvar_s(evaluate(nextarg(&n), TMPVAR)));
fmt = fmt_cur = xstrdup(getvar_s(evaluate(nextarg(&n), TMPVAR)));
// ^^^^^^^^^ here we immediately strdup() the value, so the later call
// to evaluate() potentially recursing into another awk_printf() can't
// mangle the value.
b = NULL;
i = 0;
res_buf = NULL;
res_len = 0;
while (1) { /* "print one format spec" loop */
char *s;
char c;
char sv;
var *arg;
/* s is the next string to append to res_buf.
* it can be either a literal trailing segment of fmt (then c == NUL),
* or allocated result of the formatting */
char *s;
size_t slen;
char *after_fmt;
int starred;
int width;
int prec;
enum { MAX_FMT_LEN = sizeof("%+- 0#'99.99llx plus paranoia") + 2 * sizeof(int)*3 };
char baked_format[MAX_FMT_LEN];
char *baked_cur;
char *use_fmt;
const char *diouxX;
/* Find end of the next format spec, or end of line */
s = f;
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) /* "....%" */
/* find end of the next format spec, or end of string */
s = fmt_cur;
//bb_error_msg("s:'%s'", s);
fmt_cur = strchrnul(fmt_cur, '%');
c = *fmt_cur;
if (!c) { /* no more percent chars */
goto nul;
if (c == '%') { /* "....%%...." */
slen = f - s;
s = xstrndup(s, slen);
f++;
goto append; /* print "....%" part verbatim */
}
fmt_cur++;
/* we are past % in "....%..." */
c = *fmt_cur;
if (c == '%') { /* "....%%...." */
slen = fmt_cur - s;
fmt_cur++;
goto append_slen; /* append "....%" part verbatim */
}
/* find trailing letter of the %FMT */
starred = 0;
after_fmt = fmt_cur;
while (1) {
if (!c) { /* unterminated "....%FMT" */
fmt_cur = after_fmt;
nul:
slen = fmt_cur - s;
//bb_error_msg("fmt:'%s', res_buf:'%s'", fmt, res_buf);
if (!res_buf) { /* the entire fmt had no (valid) %FMTs? */
/* optimize this case (avoid xrealloc+free) */
res_buf = fmt;
res_len = slen;
goto ret;
}
goto tail; /* append remaining string, exit loop */
}
//TODO: GNU awk 5.3.0 also supports %ld, %lx, we don't (yet). It does not support %lld.
if (isalpha(c))
break;
if (c == '*') /* gawk supports %*d and %*.*f, we don't... */
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 */
starred |= (c == '*');
c = *++after_fmt;
}
diouxX = strchr("diouxX", c);
if (!(diouxX || strchr("cs""eEfFgGaA", c))
|| (after_fmt - fmt_cur) >= MAX_FMT_LEN
) {
/* unknown, or overlong "....%FMT...." */
/* append "....%<notletters><letter>" part verbatim */
//this works (unknown conversion char means "print %FMT verbatim"):
// awk 'BEGIN { printf "%W\n"; }
//since we check for this early, even this works:
// awk 'BEGIN { printf "%*W\n"; }
//whereas GNU awk 5.3.0 says "not enough arguments to satisfy format string"
fmt_cur = after_fmt + 1;
slen = fmt_cur - s;
goto append_slen;
}
if (*s != '%') {
/* the %FMT does not start immediately at the beginning of s */
if (starred || diouxX) {
/* It is a "%*s"-like starred %FMT, or an integer conversion.
* In this case we will use fixed baked_format[].
* Which means "literal_prefix%FMT" can't be used as one piece.
* Append "literal_prefix" to res_buf.
*/
fmt_cur--;
slen = fmt_cur - s;
append_slen:
//s = xstrndup(s, slen);
//goto append;
/* a bit bloaty, but avoids dup+free: */
res_buf = xrealloc(res_buf, res_len + slen + 1);
strncpy(res_buf + res_len, s, slen); /* s can't contain NULs here */
res_len += slen;
continue;
}
}
/* we are at A in "....%...A..." */
/* NUL-terminate "...%FMT" */
after_fmt++;
if (*after_fmt && *after_fmt != '%') {
// optimization for common cases:
// printf "Number:%d\n" (one extra char between %FMT and EOL)
// printf "String:'%s'\n" (two extra chars)
// - we can handle a small tail of literals after %FMT in one pass!
// (careful: they are added to baked_format[] array, do not overflow it!)
after_fmt++;
if (*after_fmt && *after_fmt != '%')
after_fmt++;
}
sv = *after_fmt;
*after_fmt = '\0';
/* flags */
baked_cur = baked_format;
*baked_cur++ = '%';
c = *fmt_cur;
while (strchr("+- 0#'", c) && (baked_cur - baked_format) <= 6) {
*baked_cur++ = c;
c = *++fmt_cur;
}
/* width */
width = -1;
if (c == '*') {
width = (int)getvar_i(evaluate(nextarg(&n), TMPVAR));
//bb_error_msg("*width=%d", width);
c = *++fmt_cur;
//if (isdigit(c)) /* we do not support "%*2$d" format */
// syntax_error("invalid format specifier");
} else if (isdigit(c)) {
width = atoi(fmt_cur);
do
c = *++fmt_cur;
while (isdigit(c));
}
/* precision? */
prec = -1;
if (c == '.') {
c = *++fmt_cur;
if (c == '*') {
prec = (int)getvar_i(evaluate(nextarg(&n), TMPVAR));
//bb_error_msg("*prec=%d", prec);
c = *++fmt_cur;
//if (isdigit(c)) /* we do not support "%5.*2$d" format */
// syntax_error("invalid format specifier");
} else if (isdigit(c)) {
prec = atoi(fmt_cur);
//do
// c = *++fmt_cur;
//while (isdigit(c));
//^^^^ unnecessary, while () below skips everything to format type letter
}
}
while (!isalpha(c))
c = *++fmt_cur;
/* we are at A in "....%fmtA..." */
arg = evaluate(nextarg(&n), TMPVAR);
/* Result can be arbitrarily long. Example:
* printf "%99999s", "BOOM"
*/
sv = *++f;
*f = '\0';
use_fmt = s;
//bb_error_msg("w:%d p:%d conv:'%c' fmt_cur:%p after_fmt:%p", width, prec, c, fmt_cur, after_fmt);
if (starred || diouxX) {
if (width >= 0
|| (starred && (c == 's' || c == 'c'))
//GNU awk 5.3.0 compat: "%*s",-10,"A" works like "%-10s","A"
) {
baked_cur += sprintf(baked_cur, "%d", width);
}
if (diouxX) {
/* print %d, %i, positive %u as floats: */
/* this avoids losing most-significant bits, try */
/* awk 'BEGIN { printf "%d\n", 2**128 }' */
sprintf(baked_cur, ".0f%s", fmt_cur + 1);
} else {
if (prec >= 0)
baked_cur += sprintf(baked_cur, ".%u", prec);
sprintf(baked_cur, "%s", fmt_cur);
}
use_fmt = baked_format;
//bb_error_msg("baked_format:'%s'", baked_format);
}
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 */);
char *r = xasprintf(use_fmt, cc ? cc : '^' /* else strlen will be wrong */);
slen = strlen(r);
if (cc == '\0') /* if cc is NUL, re-format the string with it */
sprintf(r, s, cc);
if (cc == '\0') { /* if cc is NUL, re-format the string with it */
sprintf(r, use_fmt, cc);
}
s = r;
} else {
if (c == 's') {
s = xasprintf(s, getvar_s(arg));
} else {
const char *cs = getvar_s(arg);
//bb_error_msg("format_s:'%s'", use_fmt);
s = xasprintf(use_fmt, cs);
} else { /* numeric conversion */
double d = getvar_i(arg);
if (strchr("diouxX", c)) {
//TODO: make it wider here (%x -> %llx etc)?
//Can even print the value into a temp string with %.0f,
//then replace diouxX with s and print that string.
//This will correctly print even very large numbers,
//but some replacements are not equivalent:
//%09d -> %09s: breaks zero-padding;
//%+d -> %+s: won't prepend +; etc
s = xasprintf(s, (int)d);
} else if (strchr("eEfFgGaA", c)) {
s = xasprintf(s, d);
if (diouxX)
d = trunc(d);
//bb_error_msg("d:%f", d);
if ((c|0x20) == 'x' || c == 'o' || (c == 'u' && d < 0)) {
sprintf(baked_cur, "ll%s", fmt_cur);
// -1.9 => -1 => integer (0xfff..fff)
// => interpret as unsigned integer
// awk 'BEGIN { printf "%u\n",-1.9; }': 18446744073709551615
// awk 'BEGIN { printf "%x\n",-1.9; }': ffffffffffffffff
s = xasprintf(use_fmt, (unsigned long long)d);
} else {
/* gawk 5.1.1 printf("%W") prints "%W", does not error out */
s = xstrndup(s, f - s);
s = xasprintf(use_fmt, d);
}
}
slen = strlen(s);
}
*f = sv;
append:
if (i == 0) {
b = s;
i = slen;
*after_fmt = sv;
fmt_cur = after_fmt;
//bb_error_msg("after_fmt:'%s'", after_fmt);
//bb_error_msg("slen:%d", slen);
if (res_len == 0) {
//bb_error_msg("initial:'%.*s'", slen, s);
res_buf = s;
res_len = slen;
continue;
}
tail:
b = xrealloc(b, i + slen + 1);
strcpy(b + i, s);
i += slen;
if (slen != 0 || res_len == 0) {
//bb_error_msg("appending:'%.*s'", slen, s);
res_buf = xrealloc(res_buf, res_len + slen + 1);
((char*)mempcpy(res_buf + res_len, s, slen))[0] = '\0';
res_len += slen;
}
if (!c) /* s is NOT allocated and this is the last part of string? */
break;
free(s);
@@ -2535,12 +2745,12 @@ static char *awk_printf(node *n, size_t *len)
free(fmt);
//nvfree(tmpvar, 1);
#undef TMPVAR
ret:
#if ENABLE_FEATURE_AWK_GNU_EXTENSIONS
if (len)
*len = i;
*len = res_len;
#endif
return b;
return res_buf;
}
/* Common substitution routine.
@@ -2548,9 +2758,8 @@ static char *awk_printf(node *n, size_t *len)
* store result into (dest), return number of substitutions.
* If nm = 0, replace all matches.
* If src or dst is NULL, use $0.
* If subexp != 0, enable subexpression matching (\0-\9).
*/
static int awk_sub(node *rn, const char *repl, int nm, var *src, var *dest /*,int subexp*/)
static int awk_sub(node *rn, const char *repl, int nm, var *src, var *dest /*,int in_gensub*/)
{
char *resbuf;
const char *sp;
@@ -2559,7 +2768,7 @@ static int awk_sub(node *rn, const char *repl, int nm, var *src, var *dest /*,in
regmatch_t pmatch[10];
regex_t sreg, *regex;
/* True only if called to implement gensub(): */
int subexp = (src != dest);
int in_gensub = (src != dest);
#if defined(REG_STARTEND)
const char *src_string;
size_t src_strlen;
@@ -2607,32 +2816,74 @@ static int awk_sub(node *rn, const char *repl, int nm, var *src, var *dest /*,in
residx += eo;
if (++match_no >= nm) {
const char *s;
int bslash;
/* replace */
residx -= (eo - so);
bslash = 0;
for (s = repl; *s; s++) {
char c = *s;
if (c == '\\' && s[1]) {
bslash ^= 1;
if (bslash)
continue;
s = repl;
while (*s) {
// https://www.gnu.org/software/gawk/manual/html_node/Gory-Details.html
// Table 9.2: gawk rules for sub() and backslash:
// You type sub() sees sub() generates
// \\q \q A literal ‘\q’ <<-- THIS IS DIFFERENT
// & & The matched text
// \\& \& A literal ‘&’
// \\\\ \\ Two literal ‘\’s <<-- THIS IS DIFFERENT
// \\\\& \\& A literal ‘\’, then the matched text
// \\\\\\& \\\& A literal ‘\&’
// \\\\\\q \\\q Two literal ‘\’s and literal ‘\q’ <<-- THIS IS DIFFERENT
// (^^^ non-POSIX special-casing of two backslashes by gawk)
// Table 9.4: Escape sequence processing for gensub():
// You type gensub() sees gensub() generates
// \\q \q A literal ‘q’ <<-- THIS IS DIFFERENT
// & & The matched text
// \\& \& A literal ‘&’
// \\\\ \\ A literal ‘\’ <<-- THIS IS DIFFERENT
// \\\\& \\& A literal ‘\’, then the matched text
// \\\\\\& \\\& A literal ‘\&’
// \\\\\\q \\\q A literal ‘\’ and literal ‘q’ <<-- THIS IS DIFFERENT
char c;
unsigned bslash = 0;
while ((c = *s++) == '\\' && *s) {
bslash++;
}
if ((!bslash && c == '&')
|| (subexp && bslash && c >= '0' && c <= '9')
if ((!(bslash & 1) && c == '&')
|| (in_gensub && (bslash & 1) && c >= '0' && c <= '9')
) {
int n, j = 0;
if (c != '&') {
j = c - '0';
}
bslash /= 2;
while (bslash) {
resbuf[residx++] = '\\';
bslash--;
}
n = pmatch[j].rm_eo - pmatch[j].rm_so;
resbuf = qrealloc(resbuf, residx + replen + n, &resbufsize);
memcpy(resbuf + residx, sp + pmatch[j].rm_so - start_ofs, n);
residx += n;
} else
resbuf[residx++] = c;
bslash = 0;
continue;
}
// We saw N backslashes, and we are at a "normal char", not special one.
// The "normal char" can be a "&" or backslash, examples:
// "\\\\\\&..." (in awk program) -> (what we process here) "\\\&...": escaped "&" become "normal".
// "\\\\\\" (in awk program) -> (what we process here) "\\\": last unpaired backslash is "normal".
//bb_error_msg("in_gensub:%d bslash:%d c:'%c'",in_gensub,bslash,c);
if (!in_gensub) {
// for non-gensub:
// special-case "two backslashes" case, including "\\\q" case which is logically "\\"+"\q"
// if (c != '&' && (bslash == 2 || bslash == 3)) // what doc claims
if (c != '&' && (bslash & 2)) // the actual logic in gawk-5.3.0 special-cases NOT ONLY 2,3 - but every two out of four!
bslash += 2;
if (c != '&') // gensub removes backslash from \q, sub does not:
bslash++; // if odd no.of backslashes, print one more, if even: no change
}
bslash /= 2;
while (bslash) {
resbuf[residx++] = '\\';
bslash--;
}
resbuf[residx++] = c;
}
}
@@ -2663,7 +2914,7 @@ static int awk_sub(node *rn, const char *repl, int nm, var *src, var *dest /*,in
return match_no;
}
static NOINLINE int do_mktime(const char *ds)
static NOINLINE time_t do_mktime(const char *ds)
{
struct tm then;
int count;
@@ -3149,8 +3400,7 @@ static var *evaluate(node *op, var *res)
for (;;) {
var *v = evaluate(nextarg(&op1), TMPVAR0);
if (v->type & VF_NUMBER) {
fputs(fmt_num(getvar_s(intvar[OFMT]), getvar_i(v)),
F);
fputs(fmt_num(getvar_s(intvar[OFMT]), getvar_i(v)), F);
} else {
fputs(getvar_s(v), F);
}
+9 -6
View File
@@ -44,7 +44,7 @@ static const char fmt_differ[] ALIGN1 = "%s %s differ: byte %llu, line %u\n";
// This fmt_l_opt is gnu-ism. SUSv3 is "%.0s%.0s%llu %o %o\n"
static const char fmt_l_opt[] ALIGN1 = "%.0s%.0s%llu %3o %3o\n";
#define OPT_STR "sln:+"
#define OPT_STR "sln:"
#define CMP_OPT_s (1<<0)
#define CMP_OPT_l (1<<1)
#define CMP_OPT_n (1<<2)
@@ -55,12 +55,13 @@ int cmp_main(int argc UNUSED_PARAM, char **argv)
FILE *fp1, *fp2, *outfile = stdout;
const char *filename1, *filename2 = "-";
unsigned long long skip1 = 0, skip2 = 0, char_pos = 0;
unsigned long long max_count = max_count;
int line_pos = 1; /* Hopefully won't overflow... */
const char *fmt;
int c1, c2;
unsigned opt;
int retval = 0;
int max_count = -1;
char *max_count_str;
#if !ENABLE_LONG_OPTS
opt = getopt32(argv, "^"
@@ -69,8 +70,7 @@ int cmp_main(int argc UNUSED_PARAM, char **argv)
IF_DESKTOP(":?4")
IF_NOT_DESKTOP(":?2")
":l--s:s--l",
//TODO: -n MAXCOUNT should allow KMG suffixes
&max_count
&max_count_str
);
#else
static const char cmp_longopts[] ALIGN1 =
@@ -86,7 +86,7 @@ int cmp_main(int argc UNUSED_PARAM, char **argv)
IF_NOT_DESKTOP(":?2")
":l--s:s--l",
cmp_longopts,
&max_count
&max_count_str
);
#endif
argv += optind;
@@ -102,6 +102,9 @@ int cmp_main(int argc UNUSED_PARAM, char **argv)
}
}
if (opt & CMP_OPT_n)
max_count = xatoull_sfx(max_count_str, kmg_i_suffixes);
xfunc_error_retval = 2; /* missing file results in exitcode 2 */
if (opt & CMP_OPT_s)
logmode = 0; /* -s suppresses open error messages */
@@ -126,7 +129,7 @@ int cmp_main(int argc UNUSED_PARAM, char **argv)
while (skip2) { if (getc(fp2) == EOF) break; skip2--; }
}
do {
if (max_count >= 0 && --max_count < 0)
if ((opt & CMP_OPT_n) && max_count-- == 0)
break;
c1 = getc(fp1);
c2 = getc(fp2);
+7 -1
View File
@@ -113,6 +113,9 @@
//usage: "\n -N Treat absent files as empty"
//usage: "\n -q Output only whether files differ"
//usage: "\n -r Recurse"
//usage: IF_LONG_OPTS(
//usage: "\n --no-dereference Don't follow symlinks"
//usage: )
//usage: "\n -S Start with FILE when comparing directories"
//usage: "\n -T Make tabs line up by prefixing a tab when necessary"
//usage: "\n -s Report when two files are the same"
@@ -154,6 +157,7 @@ enum { /* Commandline flags */
FLAG_p, /* not implemented */
FLAG_B,
FLAG_E, /* not implemented */
FLAG_no_deref,
};
#define FLAG(x) (1 << FLAG_##x)
@@ -867,7 +871,8 @@ static void diffdir(char *p[2], const char *s_start)
* Using list.len to specify its length,
* add_to_dirlist will remove it. */
list[i].len = strlen(p[i]);
recursive_action(p[i], ACTION_RECURSE | ACTION_FOLLOWLINKS,
recursive_action(p[i], ACTION_RECURSE |
((option_mask32 & FLAG(no_deref)) ? 0 : ACTION_FOLLOWLINKS),
add_to_dirlist, skip_dir, &list[i]);
/* Sort dl alphabetically.
* GNU diff does this ignoring any number of trailing dots.
@@ -964,6 +969,7 @@ static const char diff_longopts[] ALIGN1 =
"report-identical-files\0" No_argument "s"
"starting-file\0" Required_argument "S"
"minimal\0" No_argument "d"
"no-dereference\0" No_argument "\xff"
;
# define GETOPT32 getopt32long
# define LONGOPTS ,diff_longopts
+29 -4
View File
@@ -57,6 +57,7 @@ struct double_list {
struct double_list *next;
struct double_list *prev;
char *data;
int no_newline;
};
// Free all the elements of a linked list
@@ -76,7 +77,7 @@ static void dlist_free(struct double_list *list, void (*freeit)(void *data))
static struct double_list *dlist_add(struct double_list **list, char *data)
{
struct double_list *llist;
struct double_list *line = xmalloc(sizeof(*line));
struct double_list *line = xzalloc(sizeof(*line));
line->data = data;
llist = *list;
@@ -140,7 +141,8 @@ static void do_line(void *data)
if (TT.state > 1 && *dlist->data != TT.state)
fdprintf(TT.state == 2 ? 2 : TT.fileout,
"%s\n", dlist->data + (TT.state > 3 ? 1 : 0));
dlist->no_newline && TT.state != 2 ? "%s" : "%s\n",
dlist->data + (TT.state > 3 ? 1 : 0));
if (PATCH_DEBUG) fdprintf(2, "DO %d: %s\n", TT.state, dlist->data);
@@ -433,7 +435,17 @@ int patch_main(int argc UNUSED_PARAM, char **argv)
// Are we assembling a hunk?
if (state >= 2) {
if (*patchline == ' ' || *patchline == '+' || *patchline == '-') {
switch (*patchline) {
case '\\':
// '\ No newline at end of file' detected, mark
// previous line, if it exists.
if (TT.current_hunk->prev)
TT.current_hunk->prev->no_newline = TRUE;
free(patchline);
continue;
case ' ':
case '+':
case '-':
dlist_add(&TT.current_hunk, patchline);
if (*patchline != '+') oldlen--;
@@ -445,7 +457,20 @@ int patch_main(int argc UNUSED_PARAM, char **argv)
// If we've consumed all expected hunk lines, apply the hunk.
if (!oldlen && !newlen) state = apply_one_hunk();
if (!oldlen && !newlen) {
// Peek ahead for '\ No newline at end of file', mark
// previous line, if it exists.
int c = getchar();
ungetc(c, stdin);
if (c == '\\') {
if (TT.current_hunk->prev)
TT.current_hunk->prev->no_newline = TRUE;
do {
c = getchar();
} while (c != EOF && c != '\n');
}
state = apply_one_hunk();
}
continue;
}
fail_hunk();
+9 -5
View File
@@ -176,7 +176,7 @@
//config: Enable more verbose reporting of the results of yank, change,
//config: delete, undo and substitution commands.
//applet:IF_VI(APPLET(vi, BB_DIR_BIN, BB_SUID_DROP))
//applet:IF_VI(APPLET(vi, BB_DIR_USR_BIN, BB_SUID_DROP))
//kbuild:lib-$(CONFIG_VI) += vi.o
@@ -2685,21 +2685,25 @@ static void setops(char *args, int flg_no)
static char *expand_args(char *args)
{
char *s;
const char *replace;
args = xstrdup(args);
for (s = args; *s; s++) {
const char *replace;
unsigned n;
//NB: vim 9.2 replaces "\%" with "%" _over entire string_,
//then replaces "\c" with "c". Result:
// "\%" is "%" (ok),
// "\\" is "\" (ok),
// "\\%" is "\%" (!!!), not "\CURFILE" as you would think.
//We don't do that. Should we?
if (*s == '%') {
replace = current_filename;
} else if (*s == '#') {
replace = alt_filename;
} else {
if (*s == '\\' && s[1] != '\0') {
char *t;
for (t = s; *t; t++)
*t = t[1];
overlapping_strcpy(s, s + 1);
s++;
}
continue;
+11 -2
View File
@@ -50,9 +50,17 @@ if ! test "$mask"; then
fi
# some servers do not return router option.
# assume DHCP server is the router.
# assume either DHCP relay or DHCP server is the router.
if ! test "$router"; then
if test "$serverid"; then
# serverid is:
# = not necessarily an IP addr at all (but usually is).
# = can be NOT on our network (can use relays).
# If giaddr is set, the relay is in use and that's its IP address -
# will try using that.
if test "$giaddr"; then
router="$giaddr"
echo "No 'router' from the server, assuming 'giaddr' is the router: $giaddr"
elif test "$serverid"; then
router="$serverid"
echo "No 'router' from the server, assuming 'serverid' is the router: $serverid"
fi
@@ -66,6 +74,7 @@ test "$ip" && test "$mask" \
&& echo "ipmask[\$cfg]='$ip/$mask'"
test "$router" && echo "gw[\$cfg]='$router'"
test "$dns" && echo "dns[\$cfg]='$dns'"
# TODO: I never saw a dhcp server which correctly announces
# which subnet(s) is/are available thru advertised router
# Assume 0/0
+2 -2
View File
@@ -467,7 +467,7 @@ 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;))
IF_FEATURE_FIND_CONTEXT(ACTS(context, char *context;))
IF_FEATURE_FIND_PAREN( ACTS(paren, action ***subexpr;))
IF_FEATURE_FIND_PRUNE( ACTS(prune))
IF_FEATURE_FIND_QUIT( ACTS(quit))
@@ -983,7 +983,7 @@ ACTF(empty)
#if ENABLE_FEATURE_FIND_CONTEXT
ACTF(context)
{
security_context_t con;
char *con;
int rc;
if (G.recurse_flags & ACTION_FOLLOWLINKS) {
+70 -7
View File
@@ -73,10 +73,10 @@
//usage: "\n -c Show only count of matching lines"
//usage: "\n -o Show only the matching part of line"
//usage: "\n -q Quiet. Return 0 if PATTERN is found, 1 otherwise"
//usage: "\n -v Select non-matching lines"
//usage: "\n -s Suppress open and read errors"
//usage: "\n -r Recurse"
//usage: "\n -R Recurse and dereference symlinks"
//usage: "\n -v Select non-matching lines"
//usage: "\n -i Ignore case"
//usage: "\n -w Match whole words only"
//usage: "\n -x Match whole lines only"
@@ -105,6 +105,58 @@
//usage:#define fgrep_trivial_usage NOUSAGE_STR
//usage:#define fgrep_full_usage ""
// GNU grep 3.7 options:
// s:short option supported by our code
// S:short option "supported" by ignoring it
// l:long option supported
// .:not supported
// s. | -E, --extended-regexp
// s. | -F, --fixed-strings
// .. | -G, --basic-regexp: Interpret PATTERNS as basic regular expressions (this is the default)
// .. | -P, --perl-regexp
// s. | -e PATTERNS, --regexp=PATTERNS
// s. | -f FILE, --file=FILE
// s. | -i, --ignore-case (-y is an obsolete synonym)
// . | --no-ignore-case
// s. | -v, --invert-match
// s. | -w, --word-regexp
// s. | -x, --line-regexp
// s. | -c, --count
// l. | --color[=WHEN], --colour[=WHEN]
// s. | -L, --files-without-match
// s. | -l, --files-with-matches
// s. | -m NUM, --max-count=NUM
// s. | -o, --only-matching
// sl.| -q, --quiet, --silent
// s. | -s, --no-messages
// .. | -b, --byte-offset
// s. | -H, --with-filename
// s. | -h, --no-filename
// . | --label=LABEL: Display input coming from standard input as input coming from file LABEL
// s. | -n, --line-number
// .. | -T, --initial-tab
// .. | -Z, --null: Output zero byte (the ASCII NUL character) instead of the character that normally follows filename
// s. | -A NUM, --after-context=NUM
// s. | -B NUM, --before-context=NUM
// s. | -C NUM, --context=NUM
// . | -NUM: same as -C NUM
// . | --group-separator=SEP: When -A, -B, or -C are in use, print SEP instead of -- between groups of lines
// . | --no-group-separator: When -A, -B, or -C are in use, do not print a separator between groups of lines
// s. | -a, --text
// . | --binary-files=TYPE
// S | -I: Process binary files as if they did not contain matching data (equivalent to --binary-files=without-match)
// .. | -D ACTION, --devices=ACTION
// .. | -d ACTION, --directories=ACTION
// . | --exclude=GLOB: Skip any file with a name suffix that matches the pattern GLOB
// . | --exclude-from=FILE: Skip files whose base name matches any of the file-name globs read from FILE
// . | --exclude-dir=GLOB: Skip any directory with a name suffix that matches the pattern GLOB
// . | --include=GLOB: Search only files whose base name matches GLOB
// s. | -r, --recursive
// s. | -R, --dereference-recursive
// . | --line-buffered
// .. | -U, --binary
// s. | -z, --null-data
/* -e,-f are lists; -m,-A,-B,-C have numeric param */
#define OPTSTR_GREP \
"lnqvscFiHhe:*f:*LorRm:+wx" \
@@ -712,23 +764,31 @@ int grep_main(int argc UNUSED_PARAM, char **argv)
llist_t *fopt = NULL;
#if ENABLE_FEATURE_GREP_CONTEXT
int Copt, opts;
#endif
#if ENABLE_LONG_OPTS
static const char grep_longopts[] ALIGN1 =
"quiet\0" No_argument "q"
"color\0" Optional_argument "\xff"
;
# define GETOPT32 getopt32long
#else
# define GETOPT32 getopt32
#endif
INIT_G();
/* For grep, exitcode of 1 is "not found". Other errors are 2: */
xfunc_error_retval = 2;
/* do normal option parsing */
#if ENABLE_FEATURE_GREP_CONTEXT
/* -H unsets -h; -C unsets -A,-B */
opts = getopt32long(argv, "^"
opts = GETOPT32(argv, "^"
OPTSTR_GREP
"\0"
"H-h:C-AB",
"color\0" Optional_argument "\xff",
IF_LONG_OPTS(grep_longopts,)
&pattern_head, &fopt, &max_matches,
&lines_after, &lines_before, &Copt
, NULL
IF_LONG_OPTS(, NULL)
);
if (opts & OPT_C) {
@@ -753,8 +813,11 @@ int grep_main(int argc UNUSED_PARAM, char **argv)
}
#else
/* with auto sanity checks */
getopt32(argv, "^" OPTSTR_GREP "\0" "H-h:c-n:q-n:l-n:", // why trailing ":"?
&pattern_head, &fopt, &max_matches);
GETOPT32(argv, "^" OPTSTR_GREP "\0" "H-h:c-n:q-n:l-n",
IF_LONG_OPTS(grep_longopts,)
&pattern_head, &fopt, &max_matches
IF_LONG_OPTS(, NULL)
);
#endif
invert_search = ((option_mask32 & OPT_v) != 0); /* 0 | 1 */
+4 -4
View File
@@ -68,7 +68,7 @@ typedef struct archive_handle_t {
llist_t *link_placeholders;
/* Process the header component, e.g. tar -t */
void FAST_FUNC (*action_header)(const file_header_t *);
void FAST_FUNC (*action_header)(struct archive_handle_t *);
/* Process the data component, e.g. extract to filesystem */
void FAST_FUNC (*action_data)(struct archive_handle_t *);
@@ -187,9 +187,9 @@ void data_extract_all(archive_handle_t *archive_handle) FAST_FUNC;
void data_extract_to_stdout(archive_handle_t *archive_handle) FAST_FUNC;
void data_extract_to_command(archive_handle_t *archive_handle) FAST_FUNC;
void header_skip(const file_header_t *file_header) FAST_FUNC;
void header_list(const file_header_t *file_header) FAST_FUNC;
void header_verbose_list(const file_header_t *file_header) FAST_FUNC;
void header_skip(archive_handle_t *archive_handle) FAST_FUNC;
void header_list(archive_handle_t *archive_handle) FAST_FUNC;
void header_verbose_list(archive_handle_t *archive_handle) FAST_FUNC;
char get_header_ar(archive_handle_t *archive_handle) FAST_FUNC;
char get_header_cpio(archive_handle_t *archive_handle) FAST_FUNC;
+28 -9
View File
@@ -460,10 +460,12 @@ void *xmmap_anon(size_t size) FAST_FUNC;
# define BB_ARCH_FIXED_PAGESIZE 4096
#elif defined(__arm__) /* only 32bit, 64bit ARM has variable page size */
# define BB_ARCH_FIXED_PAGESIZE 4096
#elif defined(__riscv) /* both rv32 and rv64 have fixed page size of 4KiB */
# define BB_ARCH_FIXED_PAGESIZE 4096
#else /* if defined(ARCH) */
/* add you favorite arch today! */
//From Linux kernel inspection:
//xtenza,s390[x],riscv,nios2,csky,sparc32: fixed 4k pages
//xtenza,s390[x],nios2,csky,sparc32: fixed 4k pages
//sparc64,alpha,openrisc: fixed 8k pages
#endif
@@ -505,16 +507,17 @@ enum { /* cp.c, mv.c, install.c depend on these values. CAREFUL when changing th
#endif
#define FILEUTILS_CP_OPTSTR "pdRfinlsLHarPvuTt:" IF_SELINUX("c")
/* How many bits in FILEUTILS_CP_OPTSTR? */
FILEUTILS_CP_OPTBITS = 18 - !ENABLE_SELINUX,
FILEUTILS_CP_OPTBITS = (18 - !ENABLE_SELINUX),
FILEUTILS_RMDEST = 1 << (19 - !ENABLE_SELINUX), /* cp --remove-destination */
/* bit 18 skipped for "cp --parents" */
FILEUTILS_RMDEST = 1 << (18 - !ENABLE_SELINUX), /* cp --remove-destination */
/* bit 19 is used in cp for "cp --parents" */
FILEUTILS_REFLINK = 1 << (20 - !ENABLE_SELINUX), /* cp --reflink=auto */
FILEUTILS_REFLINK_ALWAYS = 1 << (21 - !ENABLE_SELINUX), /* cp --reflink[=always] */
/* bit 21 is used in cp for "cp --sparse=... */
/*
* Hole. cp may have some bits set here,
* they should not affect remove_file()/copy_file()
*/
FILEUTILS_REFLINK_ALWAYS = 1 << 29, /* cp --reflink, --reflink=always */
#if ENABLE_SELINUX
FILEUTILS_SET_SECURITY_CONTEXT = 1 << 30,
#endif
@@ -678,6 +681,8 @@ void bb_unsetenv_and_free(char *key) FAST_FUNC;
void xunlink(const char *pathname) FAST_FUNC;
void xstat(const char *pathname, struct stat *buf) FAST_FUNC;
void xfstat(int fd, struct stat *buf, const char *errmsg) FAST_FUNC;
mode_t FAST_FUNC xfstat_mode(int fd, const char *file_name);
off_t FAST_FUNC xfstat_size(int fd, const char *file_name);
int open3_or_warn(const char *pathname, int flags, int mode) FAST_FUNC;
int open_or_warn(const char *pathname, int flags) FAST_FUNC;
int xopen3(const char *pathname, int flags, int mode) FAST_FUNC;
@@ -692,10 +697,11 @@ off_t xlseek(int fd, off_t offset, int whence) FAST_FUNC;
int xmkstemp(char *template) FAST_FUNC;
off_t fdlength(int fd) FAST_FUNC;
/* NB: code requires that minsize is 2 bytes or larger */
uoff_t FAST_FUNC get_volume_size_in_bytes(int fd,
const char *override,
unsigned override_units,
int extend);
unsigned minsize_extend);
void xpipe(int *filedes) FAST_FUNC;
/* In this form code with pipes is much more readable */
@@ -721,6 +727,11 @@ typedef struct ioloop_state {
unsigned current_iteration_timeout;
unsigned last_timeout;
int (*pre_poll_callback)(struct ioloop_state*);
/* select() fd sets, sized to fit the largest fd seen so far.
* One allocation: [rdbits: N longs][wrbits: N longs], N = wrbits - rdbits.
* Both NULL initially (N = 0).
*/
unsigned long *rdbits, *wrbits;
} ioloop_state_t;
#define STRUCT_CONNECTION \
@@ -751,6 +762,7 @@ static ALWAYS_INLINE ioloop_state_t *new_ioloop_state(void)
}
static ALWAYS_INLINE void free_ioloop_state(ioloop_state_t *io)
{
free(io->rdbits); /* frees wrbits too */
free(io);
}
static ALWAYS_INLINE void ioloop_decrease_current_timeout(ioloop_state_t *io, unsigned n)
@@ -1881,10 +1893,10 @@ void getcaps(void *caps) FAST_FUNC;
#if ENABLE_SELINUX
extern void renew_current_security_context(void) FAST_FUNC;
extern void set_current_security_context(security_context_t sid) FAST_FUNC;
extern context_t set_security_context_component(security_context_t cur_context,
extern void set_current_security_context(char *sid) FAST_FUNC;
extern context_t set_security_context_component(char *cur_context,
char *user, char *role, char *type, char *range) FAST_FUNC;
extern void setfscreatecon_or_die(security_context_t scontext) FAST_FUNC;
extern void setfscreatecon_or_die(char *scontext) FAST_FUNC;
extern void selinux_preserve_fcontext(int fdesc) FAST_FUNC;
#else
#define selinux_preserve_fcontext(fdesc) ((void)0)
@@ -2484,6 +2496,11 @@ extern const char bb_PATH_root_path[] ALIGN1; /* BB_PATH_ROOT_PATH */
*/
#define bb_default_path (bb_PATH_root_path + sizeof("PATH=/sbin:/usr/sbin"))
/* Stored without terminating NUL */
extern const char bb_SWAPSPACE2[sizeof("SWAPSPACE2")-1];
/* Stored with terminating NUL */
extern const char bb_NO_NAME_11[sizeof("NO NAME ")];
extern const int const_int_0;
//extern const int const_int_1;
@@ -2604,6 +2621,8 @@ do { \
BUG_wrong_field_size(); \
} while (0)
#define FETCH_LE16(field) \
(sizeof(field) == 2 ? SWAP_LE16(field) : BUG_wrong_field_size())
#define FETCH_LE32(field) \
(sizeof(field) == 4 ? SWAP_LE32(field) : BUG_wrong_field_size())
+16
View File
@@ -151,6 +151,21 @@
# endif
#endif
/* Somewhere after gcc-9, it stopped recognizing "int var = var;" initializer
* as the "this variable is intentionally not initialized, don't warn" idiom.
*/
#if !__GNUC_PREREQ(10,0)
# define UNINITIALIZED_VAR(var,zero) var = var
#else
# define UNINITIALIZED_VAR(var,zero) var = zero
/* NB: in case newer gcc is able to see that the variable
* is never used before initialization on all possible code paths,
* you can use int UNINITIALIZED_VAR(var,var);
* instead of int UNINITIALIZED_VAR(var,0);
* and avoid having extra zeroing instruction.
*/
#endif
/* ---- Endian Detection ------------------------------------ */
@@ -272,6 +287,7 @@ typedef uint64_t bb__aliased_uint64_t FIX_ALIASING;
#endif
/* Unaligned, fixed-endian accessors */
#define get_unaligned_le16(buf) ({ uint16_t v; move_from_unaligned16(v, buf); SWAP_LE16(v); })
#define get_unaligned_le32(buf) ({ uint32_t v; move_from_unaligned32(v, buf); SWAP_LE32(v); })
#define get_unaligned_be32(buf) ({ uint32_t v; move_from_unaligned32(v, buf); SWAP_BE32(v); })
#define put_unaligned_le32(val, buf) move_to_unaligned32(buf, SWAP_LE32(val))
+8 -7
View File
@@ -17,15 +17,16 @@
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
int FAST_FUNC add_to_uuid_cache(const char *device);
void FAST_FUNC display_uuid_cache(int scan_devices);
char *get_devname_from_label(const char *spec);
char *get_devname_from_uuid(const char *spec);
void display_uuid_cache(int scan_devices);
//static: char *get_devname_from_label(const char *spec);
//static: char *get_devname_from_uuid(const char *spec);
/* Returns:
* 0: no UUID= or LABEL= prefix found
* 1: UUID= or LABEL= prefix found. In this case,
* *fsname is replaced if device with such UUID or LABEL is found
* *fsname is replaced if device with such UUID or LABEL is found.
* The new string is malloced. The old string is NOT freed!
* *fsname is NOT replaced in "LABEL=notfound" case! [FIXME: return 2 in this case to make distinguishable?]
*/
int resolve_mount_spec(char **fsname);
int add_to_uuid_cache(const char *device);
int FAST_FUNC resolve_mount_spec(char **fsname);
+16 -9
View File
@@ -27,14 +27,14 @@
//config: requires no special support.
//config:
//config:config FEATURE_USE_INITTAB
//config: bool "Support reading an inittab file"
//config: bool "Read /etc/inittab file"
//config: default y
//config: depends on INIT || LINUXRC
//config: help
//config: Allow init to read an inittab file when the system boot.
//config: init will read /etc/inittab.
//config:
//config:config FEATURE_KILL_REMOVED
//config: bool "Support killing processes that have been removed from inittab"
//config: bool "Kill processes that have been removed from inittab"
//config: default n
//config: depends on FEATURE_USE_INITTAB
//config: help
@@ -113,10 +113,10 @@
//config: wipes all the arguments but argv[0] and rewrites argv[0] to
//config: contain only "init", so that its command line appears solely as
//config: "init" in tools such as ps.
//config: If this option is set to Y, init will keep its original behavior,
//config: otherwise, all the arguments including argv[0] will be preserved,
//config: If this option is set to Y, init clears its command line.
//config: Otherwise, all arguments including argv[0] will be preserved,
//config: be they parsed or ignored by init.
//config: The original command-line used to launch init can then be
//config: The original command line used to launch init can then be
//config: retrieved in /proc/1/cmdline on Linux, for example.
//applet:IF_INIT(APPLET(init, BB_DIR_SBIN, BB_SUID_DROP))
@@ -766,6 +766,7 @@ static void run_shutdown_and_kill_processes(void)
/* Send signals to every process _except_ pid 1 */
kill(-1, SIGTERM);
//TODO: also send SIGCONT?
message(L_CONSOLE, "Sent SIG%s to all processes", "TERM");
sync();
sleep1();
@@ -821,17 +822,23 @@ static void halt_reboot_pwoff(int sig)
*/
reset_sighandlers_and_unblock_sigs();
run_shutdown_and_kill_processes();
m = "halt";
m = "halt"; // SIGPWR/SIGUSR1 case
rb = RB_HALT_SYSTEM;
if (sig == SIGTERM) {
m = "reboot";
rb = RB_AUTOBOOT;
// Some users want to be able to know whether they reboot or shut down the machine: e.g.
// "I want to be notified on unattended shutdowns signaled by UPS discharge,
// but I don't want to get 42 'SHUTDOWN!' text messages while I debug my server."
// Setting RC_REBOOT=YES only on reboot mimics openrc's behavior:
putenv((char*)"RC_REBOOT=YES");
} else if (sig == SIGUSR2) {
m = "poweroff";
rb = RB_POWER_OFF;
}
run_shutdown_and_kill_processes();
message(L_CONSOLE, "Requesting system %s", m);
pause_and_low_level_reboot(rb);
/* not reached */
+3 -3
View File
@@ -118,10 +118,10 @@ int FAST_FUNC copy_file(const char *source, const char *dest, int flags)
#if ENABLE_SELINUX
if ((flags & FILEUTILS_PRESERVE_SECURITY_CONTEXT) && is_selinux_enabled() > 0) {
security_context_t con;
char *con;
if (lgetfilecon(source, &con) >= 0) {
if (setfscreatecon(con) < 0) {
bb_perror_msg("can't set setfscreatecon %s", con);
bb_perror_msg("can't setfscreatecon %s", con);
freecon(con);
return -1;
}
@@ -327,7 +327,7 @@ int FAST_FUNC copy_file(const char *source, const char *dest, int flags)
if ((flags & (FILEUTILS_PRESERVE_SECURITY_CONTEXT|FILEUTILS_SET_SECURITY_CONTEXT))
&& is_selinux_enabled() > 0
) {
security_context_t con;
char *con;
if (getfscreatecon(&con) == -1) {
bb_simple_perror_msg("getfscreatecon");
return -1;
+31 -17
View File
@@ -8,41 +8,55 @@
*/
#include "libbb.h"
#define ULL(x) ((unsigned long long)(x))
uoff_t FAST_FUNC get_volume_size_in_bytes(int fd,
const char *override,
unsigned override_units,
int extend)
unsigned minsize_extend)
{
uoff_t result;
#define extend ((minsize_extend) & 1)
#define minsize ((minsize_extend) & ~1u)
if (override) {
result = XATOOFF(override);
if (result >= (uoff_t)(MAXINT(off_t)) / override_units)
bb_simple_error_msg_and_die("image size is too big");
bb_error_msg_and_die("image size %lld is too big", ULL(result));
result *= override_units;
/* seek past end fails on block devices but works on files */
if (result < minsize) // NB: we expect caller to pass nonzero minsize
goto insane;
// Do we need to extend the file?
// Seek past end fails on block devices but works on files!
if (lseek(fd, result - 1, SEEK_SET) != (off_t)-1) {
if (extend)
xwrite(fd, "", 1); /* file grows if needed */
char dummy;
//NB: here, fd needs a O_RDWR open, not O_WRONLY!
if (extend && safe_read(fd, &dummy, 1) != 1) {
// the file is shorter
xwrite(fd, "", 1); // grow it
}
} else {
// we use %lld instead of %llu in order for small negative offsets
// (which are often results of underflow in some buggy math)
// to be easily seen as such: show -1, not 18446744073709551615.
bb_error_msg("warning, block device is smaller than %lld bytes", ULL(result));
}
//else {
// bb_error_msg("warning, block device is smaller");
//}
} else {
/* more portable than BLKGETSIZE[64] */
// more portable than BLKGETSIZE[64]
result = xlseek(fd, 0, SEEK_END);
}
xlseek(fd, 0, SEEK_SET);
/* Prevent things like this:
* $ dd if=/dev/zero of=foo count=1 bs=1024
* $ mkswap foo
* Setting up swapspace version 1, size = 18446744073709548544 bytes
*
* Picked 16k arbitrarily: */
if (result < 16*1024)
bb_simple_error_msg_and_die("image is too small");
// Prevent things like this:
// $ dd if=/dev/zero of=foo count=1 bs=1024
// $ mkswap foo
// Setting up swapspace version 1, size = 18446744073709548544 bytes
if (result < minsize) {
insane:
/* common message */
bb_error_msg_and_die("image is too small: %lld bytes", ULL(result));
}
return result;
}
+68 -18
View File
@@ -152,6 +152,49 @@ static ALWAYS_INLINE int read_to_buf(connection_t *conn)
return conn->read(conn);
}
/* Linux select() is not limited to FD_SETSIZE fds, but FD_SET/FD_ISSET are
* (with _FORTIFY_SOURCE, glibc aborts on fd >= FD_SETSIZE).
* Use our own bit ops on variable-sized sets.
*/
#define BPL (sizeof(long) * 8)
#define FDBIT_SET(set, fd) ((set)[(unsigned)(fd) / BPL] |= 1UL << ((unsigned)(fd) % BPL))
#define FDBIT_ISSET(set, fd) (((set)[(unsigned)(fd) / BPL] >> ((unsigned)(fd) % BPL)) & 1)
/* NB: bit ops must stay on longs: on big-endian, fd_set bit order
* within bytes differs from "byte fd/8, bit fd%8" */
#define IO_FDBYTES(io) ((uint8_t*)((io)->wrbits) - (uint8_t*)((io)->rdbits))
#define IO_FDBITS(io) (IO_FDBYTES(io) * 8)
static NOINLINE void grow_fdsets(ioloop_state_t *io, unsigned fd)
{
uint8_t *p;
/* Kernel reads fd_sets in longs: size must be a multiple of sizeof(long)
* (this also keeps wrbits aligned) */
unsigned new = (fd / BPL + 1) * sizeof(long);
unsigned old = IO_FDBYTES(io);
if (new <= old) return; /* paranoia */
/* Must preserve bits: we are called in the middle of filling the sets */
p = xrealloc(io->rdbits, 2 * new);
io->rdbits = (void*)p;
io->wrbits = (void*)(p + new);
/* [old, 2*old) -> [new, new+old) may overlap if new < 2*old */
memmove(p + new, p + old, old); /* move wrbits */
memset(p + new + old, 0, new - old); /* wrbits tail */
memset(p + old, 0, new - old); /* rdbits tail */
}
static ALWAYS_INLINE int track_maxfd(ioloop_state_t *io, int fd, int maxfd)
{
if (fd > maxfd) {
if ((unsigned)fd >= IO_FDBITS(io))
grow_fdsets(io, fd);
maxfd = fd;
}
return maxfd;
}
int FAST_FUNC ioloop_run(ioloop_state_t *io)
{
connection_t *conn;
@@ -160,13 +203,16 @@ int FAST_FUNC ioloop_run(ioloop_state_t *io)
int count;
struct timeval tv;
struct timeval *tv_ptr;
fd_set rdfdset, wrfdset;
io->current_iteration_timeout = io->max_timeout ? io->max_timeout : UINT_MAX;
//bb_error_msg("io->current_iteration_timeout:%d", io->current_iteration_timeout);
again:
FD_ZERO(&rdfdset);
FD_ZERO(&wrfdset);
/* The sets are contiguous: one memset clears both.
* (Guard is needed: memset's arg is declared nonnull,
* the compiler may assume rdbits != NULL afterwards).
*/
if (io->rdbits)
memset(io->rdbits, 0, 2 * IO_FDBYTES(io));
conn = io->conns;
if (!conn)
@@ -190,16 +236,14 @@ int FAST_FUNC ioloop_run(ioloop_state_t *io)
rcr = should_poll_read_fd(conn);
if (rcr < 0)
goto next;
/* track_maxfd() before FDBIT_SET(): it may grow the sets */
if (rcw > 0) {
FD_SET(conn->write_fd, &wrfdset);
//FIXME: what if fd > 1023
if (conn->write_fd > maxfd)
maxfd = conn->write_fd;
maxfd = track_maxfd(io, conn->write_fd, maxfd);
FDBIT_SET(io->wrbits, conn->write_fd);
}
if (rcr > 0) {
FD_SET(conn->read_fd, &rdfdset);
if (conn->read_fd > maxfd)
maxfd = conn->read_fd;
maxfd = track_maxfd(io, conn->read_fd, maxfd);
FDBIT_SET(io->rdbits, conn->read_fd);
}
next:
conn = next;
@@ -218,8 +262,9 @@ int FAST_FUNC ioloop_run(ioloop_state_t *io)
tv.tv_usec = poll_timeout_us % 1000000;
tv_ptr = &tv;
}
maxfd++;
count = select(maxfd, maxfd ? &rdfdset : NULL, maxfd ? &wrfdset : NULL, NULL, tv_ptr);
maxfd++; /* now: highest fd + 1, or 0 if no fds to wait on */
/* If maxfd == 0, sets are not accessed (they may be NULL) */
count = select(maxfd, (fd_set*)io->rdbits, (fd_set*)io->wrbits, NULL, tv_ptr);
dbg("select:%d", count);
/* Any function in the loop can change it, modifying next select() timeout */
@@ -240,22 +285,27 @@ int FAST_FUNC ioloop_run(ioloop_state_t *io)
while (conn) {
connection_t *next = conn->next; /* in case conn freed */
int rcw;
int fd;
/* We do check for valid fd >=0: this means that conns
* may prevent I/O of other conns by setting fds to -1.
* fd < maxfd check: conns inserted (or fds changed) after
* the sets were filled may have fds beyond the sets' size.
*/
dbg("conn->write_fd:%d ?", conn->write_fd);
if (conn->write_fd >= 0 && FD_ISSET(conn->write_fd, &wrfdset)) {
dbg("conn->write_fd:%d ready", conn->write_fd);
fd = conn->write_fd;
dbg("conn->write_fd:%d ?", fd);
if (fd >= 0 && fd < maxfd && FDBIT_ISSET(io->wrbits, fd)) {
dbg("conn->write_fd:%d ready", fd);
rcw = write_from_buf(conn);
if (rcw < 0) {
/* often indicates that conn is gone (freed), do not use it anymore */
goto next1;
}
}
dbg("conn->read_fd:%d ?", conn->read_fd);
if (conn->read_fd >= 0 && FD_ISSET(conn->read_fd, &rdfdset)) {
dbg("conn->read_fd:%d ready", conn->read_fd);
fd = conn->read_fd;
dbg("conn->read_fd:%d ?", fd);
if (fd >= 0 && fd < maxfd && FDBIT_ISSET(io->rdbits, fd)) {
dbg("conn->read_fd:%d ready", fd);
read_to_buf(conn);
}
next1:
+2 -1
View File
@@ -2502,8 +2502,8 @@ int FAST_FUNC read_line_input(line_input_t *st, const char *prompt, char *comman
* (example: interactive python ^Z-backgrounded,
* tty is still in "raw mode").
*/
parse_and_put_prompt(prompt);
fflush_all();
parse_and_put_prompt(prompt);
if (fgets(command, maxsize, stdin) == NULL)
len = -1; /* EOF or error */
else
@@ -2548,6 +2548,7 @@ int FAST_FUNC read_line_input(line_input_t *st, const char *prompt, char *comman
#endif
#define command command_must_not_be_used
fflush_all();
tcsetattr_stdin_TCSANOW(&new_settings);
#if 0
+8
View File
@@ -33,6 +33,14 @@ const char bb_default_login_shell[] ALIGN1 = LIBBB_DEFAULT_LOGIN_SHELL;
* but I want to save a few bytes here. Check libbb.h before changing! */
const char bb_PATH_root_path[] ALIGN1 = BB_PATH_ROOT_PATH;
#if ENABLE_MKSWAP || ENABLE_SWAPLABEL
/* Stored without terminating NUL */
const char bb_SWAPSPACE2[sizeof("SWAPSPACE2")-1] ALIGN1 = "SWAPSPACE2";
#endif
#if ENABLE_MKDOSFS || ENABLE_MKFS_VFAT || ENABLE_FEATURE_VOLUMEID_FAT
/* Stored with terminating NUL */
const char bb_NO_NAME_11[] = "NO NAME ";
#endif
//const int const_int_1 = 1;
/* explicitly = 0, otherwise gcc may make it a common variable
+6
View File
@@ -15,6 +15,12 @@
#undef _tolower
#define _tolower(X) ((X)|((char) 0x20))
/* (*ptr) points to string directly after '\'.
* Analyze it, if it's special (n, 003, etc) return
* corresponding char ('\n', 0x03, etc) and advance
* (*ptr) to point after the special part of the string.
* Otherwise: return '\' and do not advance (*ptr).
*/
char FAST_FUNC bb_process_escape_sequence(const char **ptr)
{
const char *q;
+2 -2
View File
@@ -33,14 +33,14 @@
#endif
#if ENABLE_SELINUX
static security_context_t current_sid;
static char *current_sid;
void FAST_FUNC renew_current_security_context(void)
{
freecon(current_sid); /* Release old context */
getcon(&current_sid); /* update */
}
void FAST_FUNC set_current_security_context(security_context_t sid)
void FAST_FUNC set_current_security_context(char *sid)
{
freecon(current_sid); /* Release old context */
current_sid = sid;
+3 -3
View File
@@ -9,7 +9,7 @@
#include "libbb.h"
#include <selinux/context.h>
context_t FAST_FUNC set_security_context_component(security_context_t cur_context,
context_t FAST_FUNC set_security_context_component(char *cur_context,
char *user, char *role, char *type, char *range)
{
context_t con = context_new(cur_context);
@@ -31,7 +31,7 @@ error:
return NULL;
}
void FAST_FUNC setfscreatecon_or_die(security_context_t scontext)
void FAST_FUNC setfscreatecon_or_die(char *scontext)
{
if (setfscreatecon(scontext) < 0) {
/* Can be NULL. All known printf implementations
@@ -43,7 +43,7 @@ void FAST_FUNC setfscreatecon_or_die(security_context_t scontext)
void FAST_FUNC selinux_preserve_fcontext(int fdesc)
{
security_context_t context;
char *context;
if (fgetfilecon(fdesc, &context) < 0) {
if (errno == ENODATA || errno == ENOTSUP)
+1 -1
View File
@@ -18,7 +18,7 @@
#if ENABLE_SELINUX
static void check_selinux_update_passwd(const char *username)
{
security_context_t seuser;
char *seuser;
char *p;
if (getuid() != (uid_t)0 || is_selinux_enabled() == 0)
+14
View File
@@ -110,6 +110,7 @@ void* FAST_FUNC xmemdup(const void *s, size_t n)
void* FAST_FUNC mmap_read(int fd, size_t size)
{
/* some NOMMU systems prefer MAP_PRIVATE over MAP_SHARED */
return mmap(NULL, size, PROT_READ, MAP_PRIVATE, fd, 0);
}
@@ -548,6 +549,19 @@ void FAST_FUNC xfstat(int fd, struct stat *stat_buf, const char *errmsg)
bb_simple_perror_msg_and_die(errmsg);
}
mode_t FAST_FUNC xfstat_mode(int fd, const char *file_name)
{
struct stat st;
xfstat(fd, &st, file_name);
return st.st_mode;
}
off_t FAST_FUNC xfstat_size(int fd, const char *file_name)
{
struct stat st;
xfstat(fd, &st, file_name);
return st.st_size;
}
#if ENABLE_SELINUX
// selinux_or_die() - die if SELinux is disabled.
void FAST_FUNC selinux_or_die(void)
+1 -1
View File
@@ -171,7 +171,7 @@ static int tokenize(char *buffer, int ch)
if (p != end)
overlapping_strcpy(p, end);
num_fields++;
if (*end == '\0') {
if (*p == '\0') {
S.tokenize_end = p + 1;
return num_fields;
}
+1 -1
View File
@@ -96,7 +96,7 @@ config USE_BB_CRYPT_YES
default y
depends on USE_BB_CRYPT
help
Enable this if you have passwords starting with "$y$" or
Enable this if you have passwords starting with "$y$"
in your /etc/passwd or /etc/shadow files. These passwords
are hashed using yescrypt algorithms.
With this option off, login will fail password check for any
+4 -5
View File
@@ -51,18 +51,17 @@ int add_remove_shell_main(int argc UNUSED_PARAM, char **argv)
FILE *orig_fp;
char *orig_fn;
char *new_fn;
struct stat sb;
sb.st_mode = 0666;
mode_t st_mode;
argv++;
orig_fn = xmalloc_follow_symlinks(SHELLS_FILE);
if (!orig_fn)
return EXIT_FAILURE;
st_mode = 0666;
orig_fp = fopen_for_read(orig_fn);
if (orig_fp)
xfstat(fileno(orig_fp), &sb, orig_fn);
st_mode = xfstat_mode(fileno(orig_fp), orig_fn);
new_fn = xasprintf("%s.tmp", orig_fn);
/*
@@ -73,7 +72,7 @@ int add_remove_shell_main(int argc UNUSED_PARAM, char **argv)
* after which it should revert to O_TRUNC.
* For now, I settle for O_TRUNC instead.
*/
xmove_fd(xopen3(new_fn, O_WRONLY | O_CREAT | O_TRUNC, sb.st_mode), STDOUT_FILENO);
xmove_fd(xopen3(new_fn, O_WRONLY | O_CREAT | O_TRUNC, st_mode), STDOUT_FILENO);
/* TODO?
xfchown(STDOUT_FILENO, sb.st_uid, sb.st_gid);
*/
+1 -1
View File
@@ -235,7 +235,7 @@ int adduser_main(int argc UNUSED_PARAM, char **argv)
usegroup = "nogroup";
}
if (!(opts & OPT_SHELL)) {
pw.pw_shell = (char *) "/bin/false";
pw.pw_shell = (char *) "/sbin/nologin";
}
}
pw.pw_gid = usegroup ? xgroup2gid(usegroup) : -1; /* exits on failure */
+3 -3
View File
@@ -181,9 +181,9 @@ static void die_if_nologin(void)
#if ENABLE_SELINUX
static void initselinux(char *username, char *full_tty,
security_context_t *user_sid)
char **user_sid)
{
security_context_t old_tty_sid, new_tty_sid;
char *old_tty_sid, *new_tty_sid;
if (!is_selinux_enabled())
return;
@@ -333,7 +333,7 @@ int login_main(int argc UNUSED_PARAM, char **argv)
char *opt_user = opt_user; /* for compiler */
char *full_tty;
char *short_tty;
IF_SELINUX(security_context_t user_sid = NULL;)
IF_SELINUX(char *user_sid = NULL;)
#if ENABLE_PAM
int pamret;
pam_handle_t *pamh;
+2 -2
View File
@@ -6,7 +6,7 @@
# All other options which chose general bbox config, applet features, etc,
# are not modified for the builds.
makeopts="-j9"
test "$MAKEOPS" || export MAKEOPTS="-j`nproc`"
# The list of all applet config symbols
test -f include/applets.h || { echo "No include/applets.h file"; exit 1; }
@@ -62,7 +62,7 @@ for app; do
fail=$((fail+1))
echo "Config error for ${app}"
mv .config busybox_config_${app}
elif ! make $makeopts >>busybox_make_${app}.log 2>&1; then
elif ! make $MAKEOPTS >>busybox_make_${app}.log 2>&1; then
fail=$((fail+1))
grep -i -e error: -e warning: busybox_make_${app}.log
echo "Build error for ${app}"
+2 -2
View File
@@ -1016,9 +1016,9 @@ static void restore(char *spath, struct stat source_stat, int rootlen)
dest_stat.st_mode = 0;
dpath = concat_path_file(mount_point, spath + rootlen);
lstat(dpath, &dest_stat);
free(dpath);
if (S_ISLNK(source_stat.st_mode) || (source_stat.st_mode & S_ISVTX))
copy_inode(dpath, &dest_stat, (source_stat.st_mode & ~S_ISVTX), spath, &source_stat);
free(dpath);
if (S_ISDIR(source_stat.st_mode))
dir_operation(RESTORE, spath, rootlen, NULL);
@@ -1271,7 +1271,7 @@ static void dir_operation(int type, const char * dir_name, int var, unsigned lon
while ((de = readdir(dp)) != NULL) {
if (de->d_name && DOT_OR_DOTDOT(de->d_name))
if (DOT_OR_DOTDOT(de->d_name))
continue;
path = concat_path_file(dir_name, de->d_name);
if (lstat(path, &statbuf) == 0) {
+1 -1
View File
@@ -552,7 +552,7 @@ static void print_ascii(const char *p, int length)
length *= 2;
/* find first non-space & print it */
while (length && p[ofs] != ' ') {
while (length && p[ofs] == ' ') {
p++;
LE_ONLY(ofs = -ofs;)
length--;
+9 -6
View File
@@ -469,7 +469,8 @@ static int at_end(void)
*/
static void read_lines(void)
{
int ndelay_set, eagain, fdflags;
int ndelay_set, eagain;
int UNINITIALIZED_VAR(fdflags, fdflags);
char *current_line, *p;
int w = width;
char last_terminated = terminated;
@@ -501,16 +502,16 @@ static void read_lines(void)
// Consider these cases:
// "less FILE": can set O_NONBLOCK on open.
// "true | less": can't.
// " { less; cat; } <FILE": can't. And must not confuse cat.
// "{ less; cat; } <FILE": can't. And must not confuse cat.
ndelay_set = -1; // "don't know whether stdin is nonblocking"
eagain = 0;
while (1) { /* read lines until we reach cur_fline or wanted_match */
while (1) { // read lines until we reach cur_fline or wanted_match
*p = '\0';
terminated = 0;
while (1) { /* read chars until we have a line */
while (1) { // read chars until we have a line
char c;
/* if no unprocessed chars left, eat more */
// if no unprocessed chars left, eat more
if (readpos >= read_size) {
// Read stdin, temporarily make it nonblocking (if it's not already)
if (ndelay_set < 0) {
@@ -1851,7 +1852,9 @@ int less_main(int argc, char **argv)
getopt32(argv, "EMmN~IF"
IF_FEATURE_LESS_TRUNCATE("S")
IF_FEATURE_LESS_RAW("R")
/*ignored:*/"sX"
/*-T TAGFILE: ignored, for compatibility with mandoc*/ "T:"
/*ignored:*/"sX",
NULL
);
argv += optind;
num_files = argc - optind;
+1 -3
View File
@@ -326,9 +326,7 @@ int ubi_tools_main(int argc UNUSED_PARAM, char **argv)
xmove_fd(xopen(*argv, O_RDONLY), STDIN_FILENO);
if (!(opts & OPTION_s)) {
struct stat st;
xfstat(STDIN_FILENO, &st, *argv);
size_bytes = st.st_size;
size_bytes = xfstat_size(STDIN_FILENO, *argv);
}
bytes64 = size_bytes;
+1 -1
View File
@@ -53,7 +53,7 @@
* New implementation contributed by Richard Henderson <rth@tamu.edu>
* Based on original work by Bjorn Ekwall <bj0rn@blox.se>
* Restructured (and partly rewritten) by:
* Björn Ekwall <bj0rn@blox.se> February 1999
* Björn Ekwall <bj0rn@blox.se> February 1999
*
* Licensed under GPLv2 or later, see file LICENSE in this source tree.
*/
+67 -61
View File
@@ -38,59 +38,60 @@
*
* httpd.conf has the following format:
*
* H:/serverroot # define the server root. It will override -h
* A:172.20. # Allow address from 172.20.0.0/16
* A:10.0.0.0/25 # Allow any address from 10.0.0.0-10.0.0.127
* A:10.0.0.0/255.255.255.128 # Allow any address that previous set
* A:127.0.0.1 # Allow local loopback connections
* D:* # Deny from other IP connections
* H:/serverroot # define the server root. It will override -h
* I:index.html # Show index.html when a directory is requested
* .au:audio/basic # additional mime type for audio.au files
* *.php:/path/php # run xxx.php through an interpreter
*
* E404:/path/e404.html # /path/e404.html is the 404 (not found) error page
* I:index.html # Show index.html when a directory is requested
* Custom error pages can contain an absolute path or be relative to
* 'home_httpd'. Error pages are to be static files (no CGI or script).
* Error pages can only be defined in the main configuration file
* and are not taken into account in local (directories) config files.
*
* P:/url:[http://]hostname[:port]/new/path
* # When /urlXXXXXX is requested, reverse proxy
* # it to http://hostname[:port]/new/pathXXXXXX
*
* /cgi-bin:foo:bar # Require user foo, pwd bar on urls starting with /cgi-bin/
* /adm:admin:setup # Require user admin, pwd setup on urls starting with /adm/
* /adm:toor:PaSsWd # or user toor, pwd PaSsWd on urls starting with /adm/
* /adm:root:* # or user root, pwd from /etc/passwd on urls starting with /adm/
* /wiki:*:* # or any user from /etc/passwd with according pwd on urls starting with /wiki/
* .au:audio/basic # additional mime type for audio.au files
* *.php:/path/php # run xxx.php through an interpreter
*
* A/D may be as a/d or allow/deny - only first char matters.
* A:172.20. # Allow address from 172.20.0.0/16
* A:10.0.0.0/25 # Allow any address from 10.0.0.0-10.0.0.127
* A:10.0.0.0/255.255.255.128 # Same as the previous
* A:127.0.0.1 # Allow local loopback connections
* D:* # Deny from other IP connections
* A/D may be a/d or allow/deny - only first char matters.
* Deny/Allow IP logic:
* - Default is to allow all (Allow all (A:*) is a no-op).
* - Deny rules take precedence over allow rules.
* - "Deny all" rule (D:*) is applied last.
*
* - However, "Deny all" rule (D:*) is applied last.
* Example:
* 1. Allow only specified addresses
* A:172.20 # Allow any address that begins with 172.20.
* A:10.10. # Allow any address that begins with 10.10.
* A:127.0.0.1 # Allow local loopback connections
* D:* # Deny from other IP connections
* Allow only specified addresses
* A:172.20 # allow any address that begins with 172.20.
* A:10.10. # allow any address that begins with 10.10.
* A:127.0.0.1 # allow local loopback connections
* D:* # deny from other IP connections
*
* 2. Only deny specified addresses
* D:1.2.3. # deny from 1.2.3.0 - 1.2.3.255
* D:2.3.4. # deny from 2.3.4.0 - 2.3.4.255
* A:* # (optional line added for clarity)
* Only deny specified addresses
* D:1.2.3. # deny from 1.2.3.0 - 1.2.3.255
* D:2.3.4. # deny from 2.3.4.0 - 2.3.4.255
* A:* # (optional line added for clarity)
*
* If a sub directory contains config file, it is parsed and merged with
* P:/url:[http://]hostname[:port]/new/path
* When /urlXXXXXX is requested, reverse proxy it to http://hostname[:port]/new/pathXXXXXX
* This is done without checking any passwords for /urlXXXXXX.
* A:/D: directives work, but only those in the main configuration file.
*
* /cgi-bin:foo:bar # Require user foo, pwd bar on urls starting with /cgi-bin/
* /adm:admin:setup # Require user admin, pwd setup on urls starting with /adm/
* /adm:toor:PaSsWd # or user toor, pwd PaSsWd on urls starting with /adm/
* /adm:toor:$1$P/eKnWXS$aI1aPGxT.dJD5SzqAKWrF0 # encrypted paaswd
* /adm:root:* # or user root, pwd from /etc/passwd on urls starting with /adm/
* /wiki:*:* # or any user from /etc/passwd with according pwd on urls starting with /wiki/
*
* If a subdirectory contains config file, it is parsed and merged with
* any existing settings as if it was appended to the original configuration.
*
* subdir paths are relative to the containing subdir and thus cannot
* affect the parent rules.
*
* Note that since the sub dir is parsed in the forked thread servicing the
* subdir http request, any merge is discarded when the process exits. As a
* result, the subdir settings only have a lifetime of a single request.
*
* Custom error pages can contain an absolute path or be relative to
* 'home_httpd'. Error pages are to be static files (no CGI or script). Error
* page can only be defined in the root configuration file and are not taken
* into account in local (directories) config files.
* Note that since the subdir is parsed in the forked child servicing
* the subdir http request, any merge is discarded when the child exits.
* As a result, the subdir settings only have a lifetime of a single request.
*
* If -c is not set, an attempt will be made to open the default
* root configuration file. If -c is set and the file is not found, the
@@ -381,8 +382,8 @@ typedef struct Htaccess {
/* Must have "next" as a first member */
typedef struct Htaccess_IP {
struct Htaccess_IP *next;
unsigned ip;
unsigned mask;
uint32_t ip; /* host-endian */
uint32_t mask; /* host-endian */
int allow_deny;
} Htaccess_IP;
#endif
@@ -653,14 +654,14 @@ static ALWAYS_INLINE void free_Htaccess_IP_list(Htaccess_IP **pptr)
#if ENABLE_FEATURE_HTTPD_ACL_IP
/* Returns presumed mask width in bits or < 0 on error.
* Updates strp, stores IP at provided pointer */
static int scan_ip(const char **strp, unsigned *ipp, unsigned char endc)
static int scan_ip(const char **strp, uint32_t *ipp, char endc)
{
const char *p = *strp;
int auto_mask = 8;
unsigned ip = 0;
uint32_t ip = 0;
int j;
if (*p == '/')
if (*p == '/') /* Disallow "D:/24" (empty IP??) */
return -auto_mask;
for (j = 0; j < 4; j++) {
@@ -678,8 +679,11 @@ static int scan_ip(const char **strp, unsigned *ipp, unsigned char endc)
}
if (*p == '.')
p++;
if (*p != '/' && *p)
if (*p
// && *p != '/' -- no need to check, for "IP/MASK" scan_ip_mask() ignores auto_mask value, incorrect +=8 does not matter in this case
) {
auto_mask += 8;
}
ip = (ip << 8) | octet;
}
if (*p) {
@@ -695,10 +699,10 @@ static int scan_ip(const char **strp, unsigned *ipp, unsigned char endc)
}
/* Returns 0 on success. Stores IP and mask at provided pointers */
static int scan_ip_mask(const char *str, unsigned *ipp, unsigned *maskp)
static int scan_ip_mask(const char *str, uint32_t *ipp, uint32_t *maskp)
{
int i;
unsigned mask;
uint32_t mask;
char *p;
i = scan_ip(&str, ipp, '/');
@@ -713,15 +717,16 @@ static int scan_ip_mask(const char *str, unsigned *ipp, unsigned *maskp)
/* (return 0 (success) only if it has N.N.N.N form) */
return scan_ip(&str, maskp, '\0') - 32;
}
if (*p)
if (*p) /* 'xxx' had something apart from just digits */
return -1;
}
//else: i = "automask" (the count of explicit IP components: "10.0[.]" = 16)
if (i > 32)
return -1;
if (sizeof(unsigned) == 4 && i == 32) {
/* mask >>= 32 below may not work */
if (i == 32) {
/* mask >>= 32 below may not work (according to C standard) */
mask = 0;
} else {
mask = 0xffffffff;
@@ -890,15 +895,18 @@ static int parse_conf(const char *path, int flag)
if (scan_ip_mask(after_colon, &pip->ip, &pip->mask)) {
/* IP{/mask} syntax error detected, protect all */
ch = 'D';
//bb_error_msg("ERR");
pip->ip = 0; /* could be set before error is detected - zero it (again) */
pip->mask = 0;
}
//bb_error_msg_and_die("ip:0x%08x mask:0x%08x", pip->ip, pip->mask);
pip->allow_deny = ch;
if (ch == 'D') {
/* Deny:from_IP - prepend */
pip->next = G.ip_a_d;
G.ip_a_d = pip;
} else {
/* A:from_IP - append (thus all D's precedes A's) */
/* A:from_IP - append (thus all D's precede A's) */
Htaccess_IP *prev_IP = G.ip_a_d;
if (prev_IP == NULL) {
G.ip_a_d = pip;
@@ -2045,7 +2053,7 @@ static NOINLINE void send_file_and_exit(const char *url, int what)
}
#if ENABLE_FEATURE_HTTPD_ACL_IP
static void if_ip_denied_send_HTTP_FORBIDDEN_and_exit(unsigned remote_ip)
static void if_ip_denied_send_HTTP_FORBIDDEN_and_exit(uint32_t remote_ip)
{
Htaccess_IP *cur;
@@ -2173,7 +2181,6 @@ static int check_user_passwd(const char *path, char *user_and_passwd)
# if ENABLE_FEATURE_SHADOWPASSWDS && !ENABLE_PAM
char sp_buf[256];
# endif
colon_after_user = strchr(user_and_passwd, ':');
if (!colon_after_user)
goto bad_input;
@@ -2228,8 +2235,9 @@ static int check_user_passwd(const char *path, char *user_and_passwd)
* At least glibc 2.4 does this. Be extra paranoid here. */
struct spwd *result = NULL;
r = getspnam_r(pw->pw_name, &spw, sp_buf, sizeof(sp_buf), &result);
if (r == 0 && result)
passwd = result->sp_pwdp;
if (r != 0 || !result)
continue; /* no shadow, and passwd entry is bogus one-char string */
passwd = result->sp_pwdp;
}
# endif
/* In this case, passwd is ALWAYS encrypted:
@@ -2240,11 +2248,9 @@ static int check_user_passwd(const char *path, char *user_and_passwd)
}
/* Else: passwd is from httpd.conf, it is either plaintext or encrypted */
if (passwd[0] == '$' && isdigit(passwd[1])) {
if (passwd[0] == '$' && (isdigit(passwd[1]) || passwd[1] == 'y')) {
char *encrypted;
# if !ENABLE_PAM
check_encrypted:
# endif
IF_NOT_PAM(check_encrypted:)
/* encrypt pwd from peer and check match with local one */
encrypted = pw_encrypt(
/* pwd (from peer): */ colon_after_user + 1,
@@ -2337,7 +2343,7 @@ static void handle_incoming_and_exit(const len_and_sockaddr *fromAddr)
char *urlp;
char *tptr;
#if ENABLE_FEATURE_HTTPD_ACL_IP
unsigned remote_ip;
uint32_t remote_ip;
#endif
#if ENABLE_FEATURE_HTTPD_CGI
unsigned total_headers_len;
+1 -1
View File
@@ -1043,7 +1043,7 @@ static void reread_config_file(int sig UNUSED_PARAM)
portno = bb_strtou(sep->se_service, NULL, 10);
#if ENABLE_FEATURE_INETD_RPC
if (is_rpc_service(sep)) {
sep->se_rpcprog = n;
sep->se_rpcprog = portno;
if (errno) { /* se_service is not numeric */
struct rpcent *rp = getrpcbyname(sep->se_service);
if (rp == NULL) {
+1 -1
View File
@@ -86,7 +86,7 @@ static unsigned long get_netmask(unsigned long ipaddr)
# if ENABLE_FEATURE_IPCALC_FANCY
"prefix\0" No_argument "p" // prefix from IP[/prefix] [netmask]
"hostname\0" No_argument "h" // hostname from IP
"silent\0" No_argument "s" // don’t ever display error messages
"silent\0" No_argument "s" // don't ever display error messages
# endif
;
# define GETOPT32 getopt32long
+6 -1
View File
@@ -747,6 +747,11 @@ int nc_main(int argc UNUSED_PARAM, char **argv)
int x;
unsigned cnt_l = 0;
unsigned o_lport = 0;
//bbox: always Single=1
//nc-1.10 allows "nc HOST PORT1 PORT2..."
//and "nc HOST PORT1-PORT2..." forms, in which cases
//it unsets this flag:
const int Single = 1;
INIT_G();
@@ -912,7 +917,7 @@ int nc_main(int argc UNUSED_PARAM, char **argv)
x = 1; /* exit status */
/* if we're scanning at a "one -v" verbosity level, don't print refusals.
Give it another -v if you want to see everything. */
if (o_verbose > 1 || (o_verbose && errno != ECONNREFUSED))
if (Single || (o_verbose > 1) || (errno != ECONNREFUSED))
bb_perror_msg("%s (%s)", argv[0], themdotted);
}
}
+10 -7
View File
@@ -721,7 +721,7 @@ static NOINLINE int parse_reply(const unsigned char *msg, size_t len)
int i, n, rdlen;
const char *format = NULL;
char astr[INET6_ADDRSTRLEN], dname[MAXDNAME];
const unsigned char *cp;
const unsigned char *start, *cp;
header = (HEADER *)msg;
if (!header->aa)
@@ -809,6 +809,10 @@ static NOINLINE int parse_reply(const unsigned char *msg, size_t len)
}
n = *(unsigned char *)ns_rr_rdata(rr);
if (n > 0) {
if (rdlen <= n) {
//printf("TXT record too short\n");
return -1;
}
memset(dname, 0, sizeof(dname));
memcpy(dname, ns_rr_rdata(rr) + 1, n);
printf("%s\ttext = \"%s\"\n", ns_rr_name(rr), dname);
@@ -839,10 +843,9 @@ static NOINLINE int parse_reply(const unsigned char *msg, size_t len)
dbg("SOA record too short:%d\n", rdlen);
return -1;
}
printf("%s\n", ns_rr_name(rr));
cp = ns_rr_rdata(rr);
start = cp = ns_rr_rdata(rr);
n = ns_name_uncompress(ns_msg_base(handle), ns_msg_end(handle),
cp, dname, sizeof(dname));
if (n < 0) {
@@ -863,18 +866,18 @@ static NOINLINE int parse_reply(const unsigned char *msg, size_t len)
printf("\tmail addr = %s\n", dname);
cp += n;
if (rdlen < (cp - start) + 20) {
dbg("SOA record too short:%d\n", rdlen);
return -1;
}
printf("\tserial = %lu\n", ns_get32(cp));
cp += 4;
printf("\trefresh = %lu\n", ns_get32(cp));
cp += 4;
printf("\tretry = %lu\n", ns_get32(cp));
cp += 4;
printf("\texpire = %lu\n", ns_get32(cp));
cp += 4;
printf("\tminimum = %lu\n", ns_get32(cp));
break;
+7 -10
View File
@@ -286,21 +286,19 @@ static void put_iac3_IAC_x_y_merged(unsigned wwdd_and_c)
put_iac3_IAC_x_y_merged(((wwdd)<<8) + (c))
#if ENABLE_FEATURE_TELNET_TTYPE
static void put_iac_subopt(byte c, const char *str)
static void put_iac_subopt_TTYPE(const char *p)
{
put_iac4_x_y_z_t(IAC, SB, c, 0);
put_iac4_x_y_z_t(IAC, SB, TELOPT_TTYPE, 0);
while (*str) {
put_iac_byte_escaped(*str);
str++;
}
while (*p)
put_iac_byte_escaped(*p++);
put_iac2_x_y(IAC, SE);
}
#endif
#if ENABLE_FEATURE_TELNET_AUTOLOGIN
static void put_iac_subopt_autologin(const char *p)
static void put_iac_subopt_NEW_ENVIRON(const char *p)
{
put_iac4_x_y_z_t(IAC, SB, TELOPT_NEW_ENVIRON, TELQUAL_IS);
put_iac4_x_y_z_t(NEW_ENV_VAR, 'U', 'S', 'E'); /* "USER" */
@@ -433,7 +431,6 @@ static void handle_changes_in_options(stdin_to_net_t *conn)
log1("C:DO SGA");
put_iac3_IAC_x_y(DO, TELOPT_SGA);
G.flags |= FLAGS_SGA_SEEN; // remember we did it
G.changes_seen -= CHANGED_SGA;
}
G.changes_seen &= ~(CHANGED_ECHO|CHANGED_SGA);
@@ -491,7 +488,7 @@ static void handle_changes_in_options(stdin_to_net_t *conn)
&& remaining_free_bytes(conn->size) > 6 + 2 * strlen(G.ttype)
) {
log1("C:SB %s '%s'", "TTYPE", G.ttype);
put_iac_subopt(TELOPT_TTYPE, G.ttype);
put_iac_subopt_TTYPE(G.ttype);
G.ttype = NULL; // remember we did it
G.changes_seen -= CHANGED_TTYPE;
}
@@ -501,7 +498,7 @@ static void handle_changes_in_options(stdin_to_net_t *conn)
&& remaining_free_bytes(conn->size) > 12 + 2 * strlen(G.autologin)
) {
log1("C:SB %s '%s'", "NEW_ENVIRON", G.autologin);
put_iac_subopt_autologin(G.autologin);
put_iac_subopt_NEW_ENVIRON(G.autologin);
G.autologin = NULL; // remember we did it
G.changes_seen -= CHANGED_NEW_ENVIRON;
}
+8 -8
View File
@@ -1222,11 +1222,11 @@ static int test_net_to_pty_data_integrity(void)
expected_data = xmalloc(TESTDATA_SIZE);
/* Process input_data simulating net_to_pty transformations:
* - IAC IAC → single IAC
* - IAC SB TELOPT_NAWS [4 bytes] IAC SE → stripped
* - Other IAC sequences → stripped
* - \r\n → \r (skip the \n)
* - \r\0 → \r (skip the \0)
* - IAC IAC -> single IAC
* - IAC SB TELOPT_NAWS [4 bytes] IAC SE -> stripped
* - Other IAC sequences -> stripped
* - \r\n -> \r (skip the \n)
* - \r\0 -> \r (skip the \0)
*/
memset(input_data + input_size, 0, 64);
expected_size = 0;
@@ -1235,7 +1235,7 @@ static int test_net_to_pty_data_integrity(void)
/* Tail of 64 extra zero bytes allows to safely read beyond the end */
if (input_data[i] == IAC) {
if (input_data[i + 1] == IAC) {
/* IAC IAC → single IAC */
/* IAC IAC -> single IAC */
expected_data[expected_size++] = IAC;
i += 2;
continue;
@@ -1450,7 +1450,7 @@ static int test_pty_to_net_data_integrity(void)
input_data = xzalloc(TESTDATA_SIZE);
/* Generate random data - this time we want lots of 0xFF (IAC) bytes
* to test IAC escaping (IAC → IAC IAC)
* to test IAC escaping (IAC -> IAC IAC)
*/
randbits = 0;
for (i = 0; i < TESTDATA_SIZE;) {
@@ -1483,7 +1483,7 @@ static int test_pty_to_net_data_integrity(void)
expected_data = xmalloc(TESTDATA_SIZE * 2);
/* Process input_data simulating pty_to_net transformations:
* - IAC (0xFF) → IAC IAC (doubled)
* - IAC (0xFF) -> IAC IAC (doubled)
* - All other bytes pass through unchanged
*/
expected_size = 0;
+101 -82
View File
@@ -92,17 +92,21 @@
//kbuild:lib-$(CONFIG_TFTPD) += tftp.o
//usage:#define tftp_trivial_usage
//usage: "[OPTIONS] HOST [PORT]"
//usage: "-"
//usage: IF_FEATURE_TFTP_GET("g")
//usage: IF_FEATURE_TFTP_GET(IF_FEATURE_TFTP_PUT("|"))
//usage: IF_FEATURE_TFTP_PUT("p")
//usage: " [OPTIONS] HOST [PORT]"
//usage:#define tftp_full_usage "\n\n"
//usage: "Transfer a file from/to tftp server\n"
//usage: "\n -l FILE Local FILE"
//usage: "\n -r FILE Remote FILE"
//usage: IF_FEATURE_TFTP_GET(
//usage: "\n -g Get file"
//usage: )
//usage: IF_FEATURE_TFTP_PUT(
//usage: "\n -p Put file"
//usage: )
//usage: "\n -l FILE Local FILE"
//usage: "\n -r FILE Remote FILE"
//usage: IF_FEATURE_TFTP_BLOCKSIZE(
//usage: "\n -b SIZE Transfer blocks in bytes"
//usage: )
@@ -185,6 +189,17 @@ enum {
* CMD_GET(cmd) and CMD_PUT(cmd) are mutually exclusive
*/
/* RFC2348 says 'blksize' must be between 8 and 65464.
* If we also support 'tsize' protocol option,
* tftpd code sends "OP""blksize\0""NNNNN\0""tsize\0""OFF_T-sized-file-size\0"
* in its first response packet.
* To be able to do this without size checks, we have larger minimum.
* In real world, people do not rely on ridiculously small buffers anyway,
* probably can just require 512 byte minimum...
*/
enum {
MIN_BLKSIZE = 2 + sizeof("blksize\0""NNNNN\0""tsize\0") + sizeof(off_t)*3 + 16/*paranoia*/
};
struct globals {
/* u16 TFTP_ERROR; u16 reason; both network-endian, then error text: */
@@ -238,15 +253,13 @@ static void tftp_progress_done(void)
static int tftp_blksize_check(const char *blksize_str, int maxsize)
{
/* Check if the blksize is valid:
* RFC2348 says between 8 and 65464,
* but our implementation makes it impossible
* to use blksizes smaller than 22 octets. */
/* Check if the blksize is valid */
unsigned blksize = bb_strtou(blksize_str, NULL, 10);
if (errno
|| (blksize < 24) || (blksize > maxsize)
|| (blksize < MIN_BLKSIZE) || (blksize > maxsize)
) {
bb_error_msg("bad blocksize '%s'", blksize_str);
/* Careful: the string is from remote machine */
bb_error_msg("bad blocksize '%s'", printable_string(blksize_str));
return -1;
}
# if ENABLE_TFTP_DEBUG
@@ -257,37 +270,23 @@ static int tftp_blksize_check(const char *blksize_str, int maxsize)
static char *tftp_get_option(const char *option, char *buf, int len)
{
int opt_val = 0;
int opt_found = 0;
int k;
/* buf points to:
* "opt_name<NUL>opt_val<NUL>opt_name2<NUL>opt_val2<NUL>..." */
while (len > 0) {
/* Make sure options are terminated correctly */
for (k = 0; k < len; k++) {
if (buf[k] == '\0') {
goto nul_found;
}
}
return NULL;
nul_found:
if (opt_val == 0) { /* it's "name" part */
if (strcasecmp(buf, option) == 0) {
opt_found = 1;
}
} else if (opt_found) {
while (1) {
char *cur_opt = buf;
char *nul = memchr(buf, '\0', len);
if (!nul)
return NULL;
len -= (++nul) - buf;
buf = nul;
nul = memchr(buf, '\0', len);
if (!nul)
return NULL;
if (strcasecmp(cur_opt, option) == 0)
return buf;
}
k++;
buf += k;
len -= k;
opt_val ^= 1;
len -= (++nul) - buf;
buf = nul;
}
return NULL;
}
#endif
@@ -296,6 +295,8 @@ static int tftp_protocol(
/* NULL if tftp, !NULL if tftpd: */
len_and_sockaddr *our_lsa,
len_and_sockaddr *peer_lsa,
/* tftp: can be NULL if "-l -". If no -l FILE, not NULL: inferred from -r FILE instead */
/* tftpd: known from client's first packet: */
const char *local_file
IF_TFTP(, const char *remote_file)
#if !ENABLE_TFTP
@@ -315,7 +316,6 @@ static int tftp_protocol(
int send_len;
IF_FEATURE_TFTP_BLOCKSIZE(smallint expect_OACK = 0;)
smallint finished = 0;
uint16_t opcode;
uint16_t block_nr;
uint16_t recv_blk;
int local_fd = -1;
@@ -330,6 +330,8 @@ static int tftp_protocol(
*/
char *xbuf = xmalloc(io_bufsize);
char *rbuf = xmalloc(io_bufsize);
#define SET_OPCODE(opc) (*((uint16_t*)(xbuf)) = htons(opc))
#define GET_OPCODE(b) *((uint16_t*)(b))
socket_fd = xsocket(peer_lsa->u.sa.sa_family, SOCK_DGRAM, 0);
setsockopt_reuseaddr(socket_fd);
@@ -362,8 +364,8 @@ static int tftp_protocol(
* tftp -> "\0\4\0\1"
* ...
* Download with option of blksize 16384:
* tftp -> "\0\1FILENAME\0octet\0blksize\00016384\0"
* "\0\6blksize\00016384\0" <- tftpd
* tftp -> "\0\1FILENAME\0octet\0blksize\0""16384\0"
* "\0\6blksize\0""16384\0" <- tftpd
* tftp -> "\0\4\0\0"
* "\0\3\0\1FILEDATA..." <- tftpd
* tftp -> "\0\4\0\1"
@@ -375,8 +377,8 @@ static int tftp_protocol(
* "\0\4\0\1" <- tftpd
* ...
* Upload with option of blksize 16384:
* tftp -> "\0\2FILENAME\0octet\0blksize\00016384\0"
* "\0\6blksize\00016384\0" <- tftpd
* tftp -> "\0\2FILENAME\0octet\0blksize\0""16384\0"
* "\0\6blksize\0""16384\0" <- tftpd
* tftp -> "\0\3\0\1FILEDATA..."
* "\0\4\0\1" <- tftpd
* ...
@@ -397,13 +399,7 @@ static int tftp_protocol(
local_fd = open(local_file, open_mode, 0666);
if (local_fd < 0) {
/* sanitize name, it came from untrusted remote side */
unsigned char *p = (void *) local_file;
while (*p) {
if (*p < ' ')
*p = '?';
p++;
}
bb_perror_msg("can't open '%s'", local_file);
bb_perror_msg("can't open '%s'", printable_string(local_file));
G_error_pkt_reason = ERR_NOFILE;
strcpy(G_error_pkt_str, "can't open file");
goto send_err_pkt_nomsg;
@@ -416,7 +412,7 @@ static int tftp_protocol(
/* For the download case, block_nr is still 1 -
* we expect 1st ACK from peer to be for (block_nr-1),
* that is, for "block 0" which is our OACK pkt */
opcode = TFTP_OACK;
SET_OPCODE(TFTP_OACK);
goto add_blksize_opt;
}
#endif
@@ -449,10 +445,7 @@ static int tftp_protocol(
* first reply. */
/* build opcode */
opcode = TFTP_WRQ;
if (CMD_GET(option_mask32)) {
opcode = TFTP_RRQ;
}
SET_OPCODE(CMD_GET(option_mask32) ? TFTP_RRQ : TFTP_WRQ);
/* add filename and mode */
/* fill in packet if the filename fits into xbuf */
len = strlen(remote_file);
@@ -478,32 +471,37 @@ static int tftp_protocol(
#endif /* ENABLE_TFTP */
#if ENABLE_FEATURE_TFTP_BLOCKSIZE
add_blksize_opt:
add_blksize_opt: /* tftp or tftpd */
if (blksize != TFTP_BLKSIZE_DEFAULT) {
/* add "blksize", <nul>, blksize, <nul> */
strcpy(cp, "blksize");
cp += sizeof("blksize");
/* add "blksize", <nul> */
cp = stpcpy(cp, "blksize") + 1;
/* add blksize, <nul> */
cp += snprintf(cp, 6, "%d", blksize) + 1;
}
if (want_transfer_size) {
/* add "tsize", <nul>, size, <nul> (see RFC2349) */
/* if tftp and downloading, we send "0" (local_fd is not open yet)
* and this makes server to send "tsize" option with the size */
/* if tftp and uploading, we send file size (maybe dont, to not confuse old servers???) */
/* if tftpd and downloading, we are answering to client's request */
/* if tftpd and uploading: !want_transfer_size, this code is not executed */
/* add "tsize", <nul>, size, <nul> (see RFC2349)
* if tftp and downloading, we send "0" (local_fd is not open yet)
* - this makes server send "tsize" option with size back to us.
* if tftp and uploading, we send file size (maybe dont, to not confuse old servers???)
* if tftpd and downloading, we are answering to client's request
* if tftpd and uploading: !want_transfer_size, this code is not executed */
struct stat st;
strcpy(cp, "tsize");
cp += sizeof("tsize");
st.st_size = 0;
if (local_fd >= 0)
fstat(local_fd, &st);
//Do we need this instead? Example?
//if (local_fd >= 0 && (!ENABLE_TFTP || local_file)) {
// mode_t m = xfstat_mode(local_fd, local_file);
// if (!S_ISREG(m))
// bb_error_msg_and_die("'%s' is not a regular file", local_file);
//}
cp = stpcpy(cp, "tsize") + 1;
cp += sprintf(cp, "%"OFF_FMT"u", (off_t)st.st_size) + 1;
# if ENABLE_FEATURE_TFTP_PROGRESS_BAR
/* Save for progress bar. If 0 (tftp downloading),
* we look at server's reply later */
G.size = st.st_size;
if (remote_file && st.st_size)
if (remote_file && st.st_size != 0)
tftp_progress_init();
# endif
}
@@ -515,14 +513,16 @@ static int tftp_protocol(
/* Using mostly goto's - continue/break will be less clear
* in where we actually jump to */
while (1) {
uint16_t opcode;
/* Build ACK or DATA */
cp = xbuf + 2;
*((uint16_t*)cp) = htons(block_nr);
cp += 2;
block_nr++;
opcode = TFTP_ACK;
if (CMD_PUT(option_mask32)) {
opcode = TFTP_DATA;
if (!CMD_PUT(option_mask32)) {
SET_OPCODE(TFTP_ACK);
} else {
len = full_read(local_fd, cp, blksize);
if (len < 0) {
goto send_read_err_pkt;
@@ -532,10 +532,10 @@ static int tftp_protocol(
}
cp += len;
IF_FEATURE_TFTP_PROGRESS_BAR(G.pos += len;)
SET_OPCODE(TFTP_DATA);
}
send_pkt:
/* Send packet */
*((uint16_t*)xbuf) = htons(opcode); /* fill in opcode part */
send_len = cp - xbuf;
/* NB: send_len value is preserved in code below
* for potential resend */
@@ -557,7 +557,7 @@ static int tftp_protocol(
tftp_progress_update();
#endif
/* Was it final ACK? then exit */
if (finished && (opcode == TFTP_ACK))
if (finished && GET_OPCODE(xbuf) == htons(TFTP_ACK))
goto ret;
recv_again:
@@ -610,12 +610,12 @@ static int tftp_protocol(
}
/* Process recv'ed packet */
opcode = ntohs( ((uint16_t*)rbuf)[0] );
opcode = GET_OPCODE(rbuf);
recv_blk = ntohs( ((uint16_t*)rbuf)[1] );
#if ENABLE_TFTP_DEBUG
fprintf(stderr, "received %d bytes: %04x %04x\n", len, opcode, recv_blk);
#endif
if (opcode == TFTP_ERROR) {
if (opcode == htons(TFTP_ERROR)) {
static const char errcode_str[] ALIGN1 =
"\0"
"file not found\0"
@@ -630,8 +630,8 @@ static int tftp_protocol(
const char *msg = "";
if (len > 4 && rbuf[4] != '\0') {
msg = &rbuf[4];
rbuf[io_bufsize - 1] = '\0'; /* paranoia */
msg = printable_string(&rbuf[4]);
} else if (recv_blk <= 8) {
msg = nth_string(errcode_str, recv_blk);
}
@@ -642,7 +642,7 @@ static int tftp_protocol(
#if ENABLE_FEATURE_TFTP_BLOCKSIZE
if (expect_OACK) {
expect_OACK = 0;
if (opcode == TFTP_OACK) {
if (opcode == htons(TFTP_OACK)) {
/* server seems to support options */
char *res;
@@ -685,7 +685,7 @@ static int tftp_protocol(
/* block_nr is already advanced to next block# we expect
* to get / block# we are about to send next time */
if (CMD_GET(option_mask32) && (opcode == TFTP_DATA)) {
if (CMD_GET(option_mask32) && (opcode == htons(TFTP_DATA))) {
if (recv_blk == block_nr) {
int sz;
if (local_fd == -1) {
@@ -715,7 +715,7 @@ static int tftp_protocol(
#endif
}
if (CMD_PUT(option_mask32) && (opcode == TFTP_ACK)) {
if (CMD_PUT(option_mask32) && (opcode == htons(TFTP_ACK))) {
/* did peer ACK our last DATA pkt? */
if (recv_blk == (uint16_t) (block_nr - 1)) {
if (finished)
@@ -759,6 +759,8 @@ static int tftp_protocol(
if (local_fd >= 0 && CMD_GET(option_mask32) && local_file)
unlink(local_file);
return EXIT_FAILURE;
#undef GET_OPCODE
#undef SET_OPCODE
#undef remote_file
}
@@ -832,7 +834,7 @@ int tftp_main(int argc UNUSED_PARAM, char **argv)
# if ENABLE_FEATURE_TFTP_BLOCKSIZE
/* Check if the blksize is valid:
* RFC2348 says between 8 and 65464 */
blksize = tftp_blksize_check(blksize_str, 65564);
blksize = tftp_blksize_check(blksize_str, 65464);
if (blksize < 0) {
//bb_error_msg("bad block size");
return EXIT_FAILURE;
@@ -883,7 +885,7 @@ int tftpd_main(int argc UNUSED_PARAM, char **argv)
len_and_sockaddr *our_lsa;
len_and_sockaddr *peer_lsa;
char *mode, *user_opt;
char *local_file = local_file;
char *UNINITIALIZED_VAR(local_file, NULL);
const char *error_msg;
int opt, result, opcode;
IF_FEATURE_TFTP_BLOCKSIZE(int blksize = TFTP_BLKSIZE_DEFAULT;)
@@ -916,7 +918,15 @@ int tftpd_main(int argc UNUSED_PARAM, char **argv)
G.pw = xgetpwnam(user_opt);
}
if (argv[0]) {
xchroot(argv[0]);
const char *DIR = argv[0];
if (chroot(DIR) == 0)
DIR = "/";
/*
* If chroot failed, assume that we aren't root,
* and at least chdir to the specified DIR.
* If chroot worked, move current dir to new "/":
*/
xchdir(DIR);
}
result = recv_from_to(STDIN_FILENO,
@@ -944,12 +954,21 @@ int tftpd_main(int argc UNUSED_PARAM, char **argv)
G.block_buf_tail[0] = '\0';
local_file = G.block_buf + 2;
/* If someone really wants to expose their entire filesystem, "tftpd /" is the way to do it.
* Most people don't want that.
* Prevent escape via absolute paths or /../:
*/
while (local_file[0] == '/')
local_file++;
if (local_file[0] == '.' || strstr(local_file, "/.")) {
//TODO: disallow only ".."?
error_msg = "dot in file name";
goto err;
}
mode = local_file + strlen(local_file) + 1;
/* RFC 1350 says mode string is case independent */
/* RFC 1350 says mode string is case insensitive */
if (mode >= G.block_buf + result || strcasecmp(mode, "octet") != 0) {
error_msg = "mode is not 'octet'";
goto err;
@@ -962,7 +981,7 @@ int tftpd_main(int argc UNUSED_PARAM, char **argv)
if (opt_len > 0) {
res = tftp_get_option("blksize", opt_str, opt_len);
if (res) {
blksize = tftp_blksize_check(res, 65564);
blksize = tftp_blksize_check(res, 65464);
if (blksize < 0) {
G_error_pkt_reason = ERR_BAD_OPT;
/* will just send error pkt */
+6 -4
View File
@@ -2467,7 +2467,9 @@ static void get_client_hello(tls_state_t *tls)
p += 2;
len -= 2;
if (len < cipher_list_len) {
if (len <= cipher_list_len) {
/* The "<=" is subtle: it aborts even if we do have cipher list,
* but have no compression size byte after it */
bb_simple_error_msg_and_die("malformed ClientHello");
}
@@ -2522,7 +2524,7 @@ static void get_client_hello(tls_state_t *tls)
len -= cipher_list_len;
/* Skip compression methods */
len -= 1 + p[0];
len -= 1 + p[0]; /* touching p[0] is allowed: len was > cipher_list_len */
p += 1 + p[0];
/* Parse extensions if present */
@@ -2729,7 +2731,7 @@ static void send_server_key_exchange(tls_state_t *tls)
sig_len = privRsaEncryptSignedElement(NULL, &tls->hsd->rsa_priv_key,
hash, 32, p + 2, 512, NULL);
if (sig_len < 0) {
bb_error_msg_and_die("RSA signature failed");
bb_simple_error_msg_and_die("RSA signature failed");
}
/* Signature length (2 bytes, big-endian) */
@@ -2958,7 +2960,7 @@ static char *decode_base64_or_die(char *dst, const char *src)
{
char *dst_end = decode_base64(dst, &src);
if (*src != '\0')
bb_error_msg_and_die("base64 decode error");
bb_simple_error_msg_and_die("base64 decode error");
return dst_end;
}
+25 -18
View File
@@ -127,9 +127,9 @@ static uint32_t Subword(uint32_t x)
// The round keys are used in each round to decrypt the states.
static int KeyExpansion(uint32_t *RoundKey, const void *key, unsigned key_len)
{
// The round constant word array, Rcon[i], contains the values given by
// x to th e power (i-1) being powers of x (x is denoted as {02}) in the field GF(2^8).
// Note that i starts at 2, not 0.
// Rcon[i] is x^i in GF(2^8), where x^i is represented by (1<<i).
// AES uses reduction polynomial x^8 + x^4 + x^3 + x + 1,
// thus x^8 = x^4 + x^3 + x + 1, represented as 00011011 (0x1b).
static const uint8_t Rcon[] ALIGN1 = {
0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36
//..... 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6,...
@@ -169,14 +169,21 @@ static int KeyExpansion(uint32_t *RoundKey, const void *key, unsigned key_len)
if (j == words_key) {
j = 0;
k++;
//TODO: we can eliminate k and Rcon[] and just generate Rcon[k]?
//instead of k++, do: Rcon = (Rcon << 1) ^ ((Rcon & 0x80) ? 0x1b : 0)
}
}
return rounds;
}
// The code might be smaller on some arch if astate[16] arrays'
// elements are wider (e.g. 32-bit words rather than bytes).
// If so, make this typedef conditional for such arch:
typedef uint8_t state_t;
// This function adds the round key to state.
// The round key is added to the state by an XOR function.
static void AddRoundKey(unsigned astate[16], const uint32_t *RoundKeys)
static void AddRoundKey(state_t astate[16], const uint32_t *RoundKeys)
{
int i;
@@ -191,7 +198,7 @@ static void AddRoundKey(unsigned astate[16], const uint32_t *RoundKeys)
// The SubBytes Function Substitutes the values in the
// state matrix with values in an S-box.
static void SubBytes(unsigned astate[16])
static void SubBytes(state_t astate[16])
{
int i;
@@ -208,7 +215,7 @@ static void SubBytes(unsigned astate[16])
// The ShiftRows() function shifts the rows in the state to the left.
// Each row is shifted with different offset.
// Offset = Row number. So the first row is not shifted.
static void ShiftRows(unsigned astate[16])
static void ShiftRows(state_t astate[16])
{
unsigned v;
@@ -232,7 +239,7 @@ static void ShiftRows(unsigned astate[16])
}
// MixColumns function mixes the columns of the state matrix
static void MixColumns(unsigned astate[16])
static void MixColumns(state_t astate[16])
{
int i;
@@ -257,7 +264,7 @@ static void MixColumns(unsigned astate[16])
// The SubBytes Function Substitutes the values in the
// state matrix with values in an S-box.
static void InvSubBytes(unsigned astate[16])
static void InvSubBytes(state_t astate[16])
{
int i;
@@ -265,7 +272,7 @@ static void InvSubBytes(unsigned astate[16])
astate[i] = rsbox[astate[i]];
}
static void InvShiftRows(unsigned astate[16])
static void InvShiftRows(state_t astate[16])
{
unsigned v;
@@ -299,7 +306,7 @@ static ALWAYS_INLINE unsigned Multiply(unsigned x)
// MixColumns function mixes the columns of the state matrix.
// The method used to multiply may be difficult to understand for the inexperienced.
// Please use the references to gain more information.
static void InvMixColumns(unsigned astate[16])
static void InvMixColumns(state_t astate[16])
{
int i;
@@ -326,7 +333,7 @@ static void InvMixColumns(unsigned astate[16])
}
}
static void aes_encrypt_1(struct tls_aes *aes, unsigned astate[16])
static void aes_encrypt_1(struct tls_aes *aes, state_t astate[16])
{
unsigned rounds = aes->rounds;
const uint32_t *RoundKey = aes->key;
@@ -350,7 +357,7 @@ void FAST_FUNC aes_setkey(struct tls_aes *aes, const void *key, unsigned key_len
void FAST_FUNC aes_encrypt_one_block(struct tls_aes *aes, const void *data, void *dst)
{
unsigned astate[16];
state_t astate[16];
unsigned i;
const uint8_t *pt = data;
@@ -373,12 +380,12 @@ void FAST_FUNC aes_cbc_encrypt(struct tls_aes *aes, void *iv, const void *data,
memcpy(iv2, iv, 16);
while (len > 0) {
{
/* almost aes_encrypt_one_block(rounds, RoundKey, pt, ct);
/* almost aes_encrypt_one_block(aes, pt, ct);
* but xor'ing of IV with plaintext[] is combined
* with plaintext[] -> astate[]
*/
int i;
unsigned astate[16];
state_t astate[16];
for (i = 0; i < 16; i++)
astate[i] = pt[i] ^ iv2[i];
aes_encrypt_1(aes, astate);
@@ -391,7 +398,7 @@ void FAST_FUNC aes_cbc_encrypt(struct tls_aes *aes, void *iv, const void *data,
}
}
static void aes_decrypt_1(struct tls_aes *aes, unsigned astate[16])
static void aes_decrypt_1(struct tls_aes *aes, state_t astate[16])
{
unsigned rounds = aes->rounds;
const uint32_t *RoundKey = aes->key;
@@ -414,7 +421,7 @@ static void aes_decrypt_one_block(struct tls_aes *aes, const void *data, void *d
{
unsigned rounds = aes->rounds;
const uint32_t *RoundKey = aes->key;
unsigned astate[16];
state_t astate[16];
unsigned i;
const uint8_t *ct = data;
@@ -442,11 +449,11 @@ void FAST_FUNC aes_cbc_decrypt(struct tls_aes *aes, void *iv, const void *data,
while (len) {
ivnext = (ivbuf==iv2) ? iv3 : iv2;
{
/* almost aes_decrypt_one_block(rounds, RoundKey, ct, pt)
/* almost aes_decrypt_one_block(aes, ct, pt)
* but xor'ing of ivbuf is combined with astate[] -> plaintext[]
*/
int i;
unsigned astate[16];
state_t astate[16];
for (i = 0; i < 16; i++)
ivnext[i] = astate[i] = ct[i];
aes_decrypt_1(aes, astate);
+7 -3
View File
@@ -370,6 +370,7 @@ int32 FAST_FUNC pstm_montgomery_reduce(psPool_t *pool, pstm_int *a, pstm_int *m,
pstm_digit *c, *_c, *tmpm, mu;
int32 oldused, x, y;
int pa; //bbox: was int16
uint32 cSize;
pa = m->used;
if (pa > a->alloc) {
@@ -377,11 +378,13 @@ int32 FAST_FUNC pstm_montgomery_reduce(psPool_t *pool, pstm_int *a, pstm_int *m,
return PS_LIMIT_FAIL;
}
if (paD && paDlen >= (uint32)2*pa+1) {
cSize = (2 * pa + 1) * sizeof(pstm_digit);
if (paD && paDlen >= cSize) {
c = paD;
memset(c, 0x0, paDlen);
} else {
c = xzalloc(2*pa+1);//bbox
//bbox: dead code, all callers always pass paD:
c = xzalloc(cSize); //bbox
}
/* copy the input */
oldused = a->used;
@@ -441,7 +444,8 @@ int32 FAST_FUNC pstm_montgomery_reduce(psPool_t *pool, pstm_int *a, pstm_int *m,
x = PS_MEM_FAIL;
}
}
if (paDlen < (uint32)2*pa+1) {
//bbox: dead code, all callers always pass paD:
if (c != paD) {
psFree(c, pool);
}
return x;
+1 -1
View File
@@ -54,7 +54,7 @@
#define TUNSETGROUP _IOW('T', 206, int)
#endif
#define IOCTL(a, b, c) ioctl_or_perror_and_die(a, b, c, NULL)
#define IOCTL(a, b, c) ioctl_or_perror_and_die(a, b, c, "")
#if 1
+2
View File
@@ -61,6 +61,7 @@ struct d6_option {
uint8_t data[1];
} PACKED;
/* Defined in RFC 3315 "DHCP for IPv6": 1-9,11-20 */
#define D6_OPT_CLIENTID 1
#define D6_OPT_SERVERID 2
/* "Identity Association for Non-temporary Addresses",
@@ -95,6 +96,7 @@ struct d6_option {
//#define D6_OPT_RECONF_MSG 19
//#define D6_OPT_RECONF_ACCEPT 20
/* RFC 3646 "DNS Configuration options for DHCPv6": */
#define D6_OPT_DNS_SERVERS 23
#define D6_OPT_DOMAIN_LIST 24
+51 -29
View File
@@ -312,6 +312,10 @@ static void option_to_env(const uint8_t *option, const uint8_t *option_end)
sprint_nip6(ipv6str, option + 4);
*new_env() = xasprintf("ipv6=%s", ipv6str);
move_from_unaligned32(v32, option + 4 + 16);
v32 = ntohl(v32);
*new_env() = xasprintf("preferred_lifetime=%u", (unsigned)v32);
move_from_unaligned32(v32, option + 4 + 16 + 4);
v32 = ntohl(v32);
*new_env() = xasprintf("lease=%u", (unsigned)v32);
@@ -837,7 +841,7 @@ static NOINLINE int send_d6_select(void)
return d6_mcast_from_client_data_ifindex(&packet, opt_ptr);
}
/* Unicast or broadcast a DHCP renew message
/* Send a DHCPv6 Renew or Rebind message
*
* RFC 3315 18.1.3. Creation and Transmission of Renew Messages
*
@@ -884,16 +888,19 @@ static NOINLINE int send_d6_select(void)
* about parameter values the client would like to have returned.
*/
/* NOINLINE: limit stack usage in caller */
static NOINLINE int send_d6_renew(struct in6_addr *server_ipv6, struct in6_addr *our_cur_ipv6)
static NOINLINE int send_d6_renew(int msg_type,
struct in6_addr *server_ipv6, struct in6_addr *our_cur_ipv6)
{
struct d6_packet packet;
uint8_t *opt_ptr;
/* Fill in: msg type, xid, ELAPSED_TIME */
opt_ptr = init_d6_packet(&packet, D6_MSG_RENEW);
opt_ptr = init_d6_packet(&packet, msg_type);
/* server id */
opt_ptr = mempcpy(opt_ptr, client6_data.server_id, client6_data.server_id->len + 2+2);
/* Rebind must not contain a server ID */
if (msg_type == D6_MSG_RENEW) {
opt_ptr = mempcpy(opt_ptr, client6_data.server_id, client6_data.server_id->len + 2+2);
}
/* IA NA (contains requested IP) */
if (client6_data.ia_na)
opt_ptr = mempcpy(opt_ptr, client6_data.ia_na, client6_data.ia_na->len + 2+2);
@@ -906,7 +913,7 @@ static NOINLINE int send_d6_renew(struct in6_addr *server_ipv6, struct in6_addr
*/
opt_ptr = add_d6_client_options(opt_ptr);
bb_info_msg("sending %s", "renew");
bb_info_msg("sending %s", msg_type == D6_MSG_RENEW ? "renew" : "rebind");
if (server_ipv6)
return d6_send_kernel_packet_from_client_data_ifindex(
&packet, (opt_ptr - (uint8_t*) &packet),
@@ -962,11 +969,6 @@ static NOINLINE int d6_recv_raw_packet(struct in6_addr *peer_ipv6, struct d6_pac
return bytes; /* returns -1 */
}
if (bytes < (int) (sizeof(packet.ip6) + sizeof(packet.udp))) {
log1s("packet is too short, ignoring");
return -2;
}
if (bytes < sizeof(packet.ip6) + ntohs(packet.ip6.ip6_plen)) {
/* packet is bigger than sizeof(packet), we did partial read */
log1s("oversized packet, ignoring");
@@ -976,6 +978,15 @@ static NOINLINE int d6_recv_raw_packet(struct in6_addr *peer_ipv6, struct d6_pac
/* ignore any extra garbage bytes */
bytes = sizeof(packet.ip6) + ntohs(packet.ip6.ip6_plen);
if (bytes < (int) (
sizeof(packet.ip6) + sizeof(packet.udp)
+ offsetof(struct d6_packet, d6_options)
/* + 4 - does DHCPv6 require that at least one option is present? */
)) {
log1s("packet is too short, ignoring");
return -2;
}
/* make sure its the right packet for us, and that it passes sanity checks */
if (packet.ip6.ip6_nxt != IPPROTO_UDP
|| (packet.ip6.ip6_vfc >> 4) != 6
@@ -1357,11 +1368,14 @@ int udhcpc6_main(int argc UNUSED_PARAM, char **argv)
/* Goes to stdout (unless NOMMU) and possibly syslog */
bb_simple_info_msg("started, v"BB_VER);
client_data.state = INIT_SELECTING;
deconfig_and_set_INIT_SELECTING:
d6_run_script_no_option("deconfig");
set_INIT_SELECTING:
client_data.state = INIT_SELECTING;
packet_num = 0;
timeout = 0;
lease_remaining = 0;
client_data.first_secs = 0;
/* Main event loop. select() waits on signal pipe and possibly
* on sockfd.
@@ -1510,7 +1524,8 @@ int udhcpc6_main(int argc UNUSED_PARAM, char **argv)
if (opt & OPT_l)
send_d6_info_request();
else
send_d6_renew(OPT_m ? NULL : &srv6_buf, requested_ipv6);
send_d6_renew(D6_MSG_RENEW,
OPT_m ? NULL : &srv6_buf, requested_ipv6);
timeout = discover_timeout;
packet_num++;
continue;
@@ -1527,6 +1542,8 @@ int udhcpc6_main(int argc UNUSED_PARAM, char **argv)
/* Switch to bcast receive */
change_listen_mode(LISTEN_RAW);
packet_num = 0;
client_data.xid = random_xid();
client_data.first_secs = 0;
/* fall right through */
case REBINDING:
/* Lease is *really* about to run out,
@@ -1534,9 +1551,8 @@ int udhcpc6_main(int argc UNUSED_PARAM, char **argv)
if (lease_remaining > 0 && packet_num < 3) {
if (opt & OPT_l)
send_d6_info_request();
else /* send a broadcast renew request */
//TODO: send_d6_renew uses D6_MSG_RENEW message, should we use D6_MSG_REBIND here instead?
send_d6_renew(/*server_ipv6:*/ NULL, requested_ipv6);
else /* send a multicast rebind request */
send_d6_renew(D6_MSG_REBIND, /*server_ipv6:*/ NULL, requested_ipv6);
timeout = discover_timeout;
packet_num++;
continue;
@@ -1544,12 +1560,9 @@ int udhcpc6_main(int argc UNUSED_PARAM, char **argv)
/* Timed out, enter init state */
change_listen_mode(LISTEN_NONE);
bb_simple_info_msg("lease lost, entering init state");
d6_run_script_no_option("deconfig");
client_data.state = INIT_SELECTING;
client_data.first_secs = 0; /* make secs field count from 0 */
timeout = 0;
packet_num = 0;
continue;
/* will set timeout = packet_num = lease_remaining = 0 */
/* also makes secs count from 0: client_data.first_secs = 0 */
goto deconfig_and_set_INIT_SELECTING;
/* case RELEASED: */
}
/* RELEASED state (when we got SIGUSR2) ends up here.
@@ -1768,15 +1781,15 @@ int udhcpc6_main(int argc UNUSED_PARAM, char **argv)
/* return to init state */
bb_info_msg("received DHCP NAK: %u '%.*s'", status, len - 2, option->data + 2);
d6_run_script(packet.d6_options, packet_end, "nak");
if (client_data.state != REQUESTING)
if (client_data.state != REQUESTING) {
deconfig_pause_and_set_INIT_SELECTING:
d6_run_script_no_option("deconfig");
}
sleep(3); /* avoid excessive network traffic */
client_data.state = INIT_SELECTING;
client_data.first_secs = 0; /* make secs field count from 0 */
requested_ipv6 = NULL;
timeout = 0;
packet_num = 0;
continue;
/* will set timeout = packet_num = lease_remaining = 0 */
/* also makes secs count from 0: client_data.first_secs = 0 */
goto set_INIT_SELECTING;
}
}
option = d6_copy_option(packet.d6_options, packet_end, D6_OPT_SERVERID);
@@ -1831,10 +1844,15 @@ int udhcpc6_main(int argc UNUSED_PARAM, char **argv)
requested_ipv6 = (struct in6_addr*) iaaddr->data;
move_from_unaligned32(lease_seconds, iaaddr->data + 16 + 4);
lease_seconds = ntohl(lease_seconds);
/// TODO: check for 0 lease time?
bb_info_msg("%s obtained, lease time %u",
"IPv6", /*inet_ntoa(temp_addr),*/ (unsigned)lease_seconds);
address_timeout = lease_seconds;
/* A zero valid lifetime revokes the address */
if (address_timeout == 0) {
lease_revoked:
bb_simple_info_msg("lease revoked, entering init state");
goto deconfig_pause_and_set_INIT_SELECTING;
}
}
if (option_mask32 & OPT_d) {
struct d6_option *iaprefix;
@@ -1883,6 +1901,10 @@ int udhcpc6_main(int argc UNUSED_PARAM, char **argv)
bb_info_msg("%s obtained, lease time %u",
"prefix", /*inet_ntoa(temp_addr),*/ (unsigned)lease_seconds);
prefix_timeout = lease_seconds;
/* A zero valid lifetime revokes the prefix */
if (prefix_timeout == 0) {
goto lease_revoked;
}
}
if (!address_timeout)
address_timeout = prefix_timeout;
+24 -27
View File
@@ -900,11 +900,6 @@ static NOINLINE int d4_recv_raw_packet(struct dhcp_packet *dhcp_pkt, int fd)
break;
}
if (bytes < (int) (sizeof(packet.ip) + sizeof(packet.udp))) {
log1s("packet is too short, ignoring");
return -2;
}
if (bytes < ntohs(packet.ip.tot_len)) {
/* packet is bigger than sizeof(packet), we did partial read */
log1s("oversized packet, ignoring");
@@ -914,6 +909,16 @@ static NOINLINE int d4_recv_raw_packet(struct dhcp_packet *dhcp_pkt, int fd)
/* ignore any extra garbage bytes */
bytes = ntohs(packet.ip.tot_len);
if (bytes < (int) (
sizeof(packet.ip) + sizeof(packet.udp)
+ offsetof(struct dhcp_packet, options)
/* DHCP requires option 255 is always present, IOW: at least one byte in options[]: */
+ 1
)) {
log1s("packet is too short, ignoring");
return -2;
}
/* make sure its the right packet for us, and that it passes sanity checks */
if (packet.ip.protocol != IPPROTO_UDP
|| packet.ip.version != IPVERSION
@@ -954,7 +959,7 @@ static NOINLINE int d4_recv_raw_packet(struct dhcp_packet *dhcp_pkt, int fd)
packet.ip.tot_len = packet.udp.len; /* yes, this is needed */
check = packet.udp.check;
packet.udp.check = 0;
if (check && check != inet_cksum(&packet, bytes)) {
if (check != 0 && check != inet_cksum(&packet, bytes)) {
log1s("packet with bad UDP checksum, ignoring");
return -2;
}
@@ -1358,11 +1363,14 @@ int udhcpc_main(int argc UNUSED_PARAM, char **argv)
/* We want random_xid to be random... */
srand(monotonic_us());
client_data.state = INIT_SELECTING;
deconfig_and_set_INIT_SELECTING:
d4_run_script_deconfig();
set_INIT_SELECTING:
client_data.state = INIT_SELECTING;
packet_num = 0;
timeout = 0;
lease_remaining = 0;
client_data.first_secs = 0;
/* Main event loop. select() waits on signal pipe and possibly
* on sockfd.
@@ -1540,12 +1548,9 @@ int udhcpc_main(int argc UNUSED_PARAM, char **argv)
/* Timed out, enter init state */
change_listen_mode(LISTEN_NONE);
bb_simple_info_msg("lease lost, entering init state");
d4_run_script_deconfig();
client_data.state = INIT_SELECTING;
client_data.first_secs = 0; /* make secs field count from 0 */
timeout = 0;
packet_num = 0;
continue;
/* sets packet_num = timeout = lease_remaining = 0 */
/* also makes secs count from 0: client_data.first_secs = 0 */
goto deconfig_and_set_INIT_SELECTING;
/* case RELEASED: */
}
/* RELEASED state (when we got SIGUSR2) ends up here.
@@ -1758,15 +1763,14 @@ int udhcpc_main(int argc UNUSED_PARAM, char **argv)
"(got ARP reply), declining");
client_data.xid = random_xid(); //TODO: can omit?
send_decline(server_id, packet.yiaddr);
bad_ip_back_to_INIT_SELECTING:
if (client_data.state != REQUESTING)
d4_run_script_deconfig();
client_data.state = INIT_SELECTING;
client_data.first_secs = 0; /* make secs field count from 0 */
sleep(3); /* avoid excessive network traffic */
requested_ip = 0;
timeout = tryagain_timeout;
packet_num = 0;
continue; /* back to main loop */
/* sets packet_num = timeout = lease_remaining = 0 */
/* also makes secs count from 0: client_data.first_secs = 0 */
goto set_INIT_SELECTING;
}
}
#endif
@@ -1814,14 +1818,7 @@ int udhcpc_main(int argc UNUSED_PARAM, char **argv)
change_listen_mode(LISTEN_NONE);
bb_info_msg("received %s", "DHCP NAK");
d4_run_script(&packet, "nak");
if (client_data.state != REQUESTING)
d4_run_script_deconfig();
sleep(3); /* avoid excessive network traffic */
client_data.state = INIT_SELECTING;
client_data.first_secs = 0; /* make secs field count from 0 */
requested_ip = 0;
timeout = 0;
packet_num = 0;
goto bad_ip_back_to_INIT_SELECTING;
}
continue;
/* case BOUND: - ignore all packets */
+91 -51
View File
@@ -95,7 +95,7 @@
//config: If you still think this is unacceptable, send patches.
//config:
//config: If you still think this is unacceptable, do not want to send
//config: patches, but do want to waste bandwidth expaining how wrong
//config: patches, but do want to waste bandwidth explaining how wrong
//config: it is, you will be ignored.
//config:
//config: FEATURE_WGET_OPENSSL does implement TLS verification
@@ -135,37 +135,42 @@
//usage:#define wget_trivial_usage
//usage: IF_FEATURE_WGET_LONG_OPTIONS(
//usage: "[-cqS] [--spider] [-O FILE] [-o LOGFILE] [--header STR]\n"
//usage: " [--post-data STR | --post-file FILE] [-Y on/off]\n"
//usage: "[-cqS] [--spider] [-O FILE] [-o LOGFILE] [--header STR]...\n"
//usage: " [-U AGENT] [--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: " [--no-cache] [--passive-ftp]" */
/* //usage: " [-nv] [-nc] [-nH] [-np]" */
//usage: " "IF_FEATURE_WGET_OPENSSL("[--no-check-certificate] ")"[-P DIR] [-U AGENT]"IF_FEATURE_WGET_TIMEOUT(" [-T SEC]")" URL..."
//usage: " "IF_FEATURE_WGET_OPENSSL("[--no-check-certificate] ")"[-P DIR] "IF_FEATURE_WGET_TIMEOUT("[-T SEC] ")"[-t TRIES] URL..."
//usage: )
//usage: IF_NOT_FEATURE_WGET_LONG_OPTIONS(
//usage: "[-cqS] [-O FILE] [-o LOGFILE] [-Y on/off] [-P DIR] [-U AGENT]"IF_FEATURE_WGET_TIMEOUT(" [-T SEC]")" URL..."
//usage: "[-cqS] [-O FILE] [-o LOGFILE] [-P DIR] [-U AGENT] [-Y on/off]\n"
//usage: " "IF_FEATURE_WGET_TIMEOUT("[-T SEC] ")"[-t TRIES] URL..."
//usage: )
//usage:#define wget_full_usage "\n\n"
//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: )
//usage: "\n -U AGENT Use AGENT for User-Agent header"
//usage: IF_FEATURE_WGET_LONG_OPTIONS(
//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: )
//usage: )
//usage: "\n -c Continue retrieval of aborted transfer"
//usage: "\n -c Continue retrieval of partial download"
//usage: "\n -q Quiet"
//usage: "\n -P DIR Save to DIR (default .)"
//usage: "\n -S Show server response"
//usage: "\n -t TRIES Retry count (default 20)"
//usage: IF_FEATURE_WGET_TIMEOUT(
//usage: "\n -T SEC Network read timeout is SEC seconds"
//usage: )
//usage: "\n -O FILE Save to FILE ('-' for stdout)"
//usage: "\n -o LOGFILE Log messages to FILE"
//usage: "\n -U STR Use STR for User-Agent header"
//usage: "\n -Y on/off Use proxy"
#include "libbb.h"
@@ -212,14 +217,16 @@ enum {
HDR_USER_AGENT = (1<<1),
HDR_RANGE = (1<<2),
HDR_CONTENT_TYPE = (1<<3),
HDR_AUTH = (1<<4) * ENABLE_FEATURE_WGET_AUTHENTICATION,
HDR_PROXY_AUTH = (1<<5) * ENABLE_FEATURE_WGET_AUTHENTICATION,
HDR_ACCEPT = (1<<4),
HDR_AUTH = (1<<5) * ENABLE_FEATURE_WGET_AUTHENTICATION,
HDR_PROXY_AUTH = (1<<6) * ENABLE_FEATURE_WGET_AUTHENTICATION,
};
static const char wget_user_headers[] ALIGN1 =
"Host:\0"
"User-Agent:\0"
"Range:\0"
"Content-Type:\0"
"Accept:\0"
# if ENABLE_FEATURE_WGET_AUTHENTICATION
"Authorization:\0"
"Proxy-Authorization:\0"
@@ -229,6 +236,7 @@ static const char wget_user_headers[] ALIGN1 =
# 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_ACCEPT (G.user_headers & HDR_ACCEPT)
# 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 :( */
@@ -236,6 +244,7 @@ static const char wget_user_headers[] ALIGN1 =
# define USR_HEADER_USER_AGENT 0
# define USR_HEADER_RANGE 0
# define USR_HEADER_CONTENT_TYPE 0
# define USR_HEADER_ACCEPT 0
# define USR_HEADER_AUTH 0
# define USR_HEADER_PROXY_AUTH 0
#endif
@@ -244,8 +253,9 @@ static const char wget_user_headers[] ALIGN1 =
struct globals {
off_t content_len; /* Content-length of the file */
off_t beg_range; /* Range at which continue begins */
#if ENABLE_FEATURE_WGET_STATUSBAR
off_t transferred; /* Number of bytes transferred so far */
off_t reset_pos; /* Where to seek to if server refuses to continue (usually 0) */
#if ENABLE_FEATURE_WGET_STATUSBAR
const char *curfile; /* Name of current file being transferred */
bb_progress_t pmt;
#endif
@@ -260,6 +270,7 @@ struct globals {
char *fname_log; /* where to direct log (-o) */
const char *proxy_flag; /* Use proxies if env vars are set */
const char *user_agent; /* "User-Agent" header field */
int tries; /* -t/--tries NUM */
int output_fd;
int log_fd;
int o_flags;
@@ -286,24 +297,22 @@ struct globals {
/* Must match option string! */
enum {
WGET_OPT_CONTINUE = (1 << 0),
WGET_OPT_QUIET = (1 << 1),
WGET_OPT_SERVER_RESPONSE = (1 << 2),
WGET_OPT_OUTNAME = (1 << 3),
WGET_OPT_LOGNAME = (1 << 4),
WGET_OPT_PREFIX = (1 << 5),
WGET_OPT_PROXY = (1 << 6),
WGET_OPT_USER_AGENT = (1 << 7),
WGET_OPT_NETWORK_READ_TIMEOUT = (1 << 8),
WGET_OPT_RETRIES = (1 << 9),
WGET_OPT_CONTINUE = (1 << 0), // -c
WGET_OPT_QUIET = (1 << 1), // -q
WGET_OPT_SERVER_RESPONSE = (1 << 2), // -W
WGET_OPT_OUTNAME = (1 << 3), // -O FILE
WGET_OPT_LOGNAME = (1 << 4), // -o LOGFILE
WGET_OPT_PREFIX = (1 << 5), // -P DIR
WGET_OPT_PROXY = (1 << 6), // -Y on/off
WGET_OPT_USER_AGENT = (1 << 7), // -U USER_AGENT
WGET_OPT_NETWORK_READ_TIMEOUT = (1 << 8), // -T SEC
WGET_OPT_RETRIES = (1 << 9), // -t NUM
WGET_OPT_nsomething = (1 << 10),
WGET_OPT_HEADER = (1 << 11) * ENABLE_FEATURE_WGET_LONG_OPTIONS,
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)
@@ -328,6 +337,9 @@ static void progress_meter(int flag)
if (flag == PROGRESS_START)
bb_progress_init(&G.pmt, G.curfile);
if (flag == PROGRESS_END)
G.pmt.last_update_sec = 0; /* force update (and correct "notty") */
notty = bb_progress_update(&G.pmt,
G.beg_range,
G.transferred,
@@ -338,7 +350,6 @@ static void progress_meter(int flag)
bb_progress_free(&G.pmt);
if (notty == 0)
bb_putchar_stderr('\n'); /* it's tty */
G.transferred = 0;
}
}
#else
@@ -669,7 +680,13 @@ static void reset_beg_range_to_zero(void)
{
bb_simple_error_msg("restart failed");
G.beg_range = 0;
xlseek(G.output_fd, 0, SEEK_SET);
/*
* G.reset_pos is zero except for one corner case:
* "wget -O FILE URL1 URL2". If download of URL2
* was partial, and next retry fails to restart from last position,
* we must rewind FILE to where URL2 data starts, not to 0!
*/
xlseek(G.output_fd, G.reset_pos, SEEK_SET);
/* Done at the end instead: */
/* ftruncate(G.output_fd, 0); */
}
@@ -914,8 +931,10 @@ static FILE* prepare_ftp_session(FILE **dfpp, struct host_info *target, len_and_
}
#endif
static void NOINLINE retrieve_file_data(FILE *dfp)
/* Return 0 if successful, !0 if partial file gotten and then got EOF or error */
static int NOINLINE retrieve_file_data(FILE *dfp)
{
off_t pos;
#if ENABLE_FEATURE_WGET_STATUSBAR || ENABLE_FEATURE_WGET_TIMEOUT
# if ENABLE_FEATURE_WGET_TIMEOUT
unsigned second_cnt = G.timeout_seconds;
@@ -931,6 +950,8 @@ static void NOINLINE retrieve_file_data(FILE *dfp)
else
fprintf(stderr, "saving to '%s'\n", G.fname_out);
}
G.transferred = 0;
progress_meter(PROGRESS_START);
if (G.chunked)
@@ -977,9 +998,7 @@ static void NOINLINE retrieve_file_data(FILE *dfp)
if (n > 0) {
xwrite(G.output_fd, G.wget_buf, n);
#if ENABLE_FEATURE_WGET_STATUSBAR
G.transferred += n;
#endif
if (G.got_clen) {
G.content_len -= n;
if (G.content_len == 0)
@@ -998,11 +1017,12 @@ static void NOINLINE retrieve_file_data(FILE *dfp)
* fread does not distinguish between EOF and error.
*/
if (errno != EAGAIN) {
progress_meter(PROGRESS_END);
if (ferror(dfp)) {
progress_meter(PROGRESS_END);
bb_simple_perror_msg_and_die(bb_msg_read_error);
bb_simple_perror_msg(bb_msg_read_error);
}
break; /* EOF, not error */
G.content_len = 1; /* treat end as error, not EOF */
goto EOF_err; /* EOF / error */
}
#if ENABLE_FEATURE_WGET_STATUSBAR || ENABLE_FEATURE_WGET_TIMEOUT
@@ -1013,7 +1033,9 @@ static void NOINLINE retrieve_file_data(FILE *dfp)
# if ENABLE_FEATURE_WGET_TIMEOUT
if (second_cnt != 0 && --second_cnt == 0) {
progress_meter(PROGRESS_END);
bb_simple_error_msg_and_die("download timed out");
bb_simple_error_msg("download timed out");
G.content_len = 1; /* treat end as error, not EOF */
goto EOF_err;
}
# endif
/* We used to loop back to poll here,
@@ -1065,25 +1087,25 @@ static void NOINLINE retrieve_file_data(FILE *dfp)
G.chunked = 0; /* makes it show 100% even for chunked download */
G.got_clen = 1; /* makes it show 100% even for download of (formerly) unknown size */
progress_meter(PROGRESS_END);
EOF_err:
if (G.content_len != 0) {
bb_simple_perror_msg_and_die("connection closed prematurely");
/* GNU wget says "DATE TIME (NN MB/s) - Connection closed at byte NNN. Retrying." */
bb_error_msg("connection closed at byte %llu", (unsigned long long)G.transferred);
return 1; /* "partial download" */
}
/* If -c failed, we restart from the beginning,
/* If partial restart failed, we restarted from the beginning,
* but we do not truncate file then, we do it only now, at the end.
* This lets user to ^C if his 99% complete 10 GB file download
* failed to restart *without* losing the almost complete file.
*/
{
off_t pos = lseek(G.output_fd, 0, SEEK_CUR);
if (pos != (off_t)-1) {
/* do not truncate if -O- is in use, a user complained about
* "wget -qO- 'http://example.com/empty' >>FILE" truncating FILE.
*/
if (!(option_mask32 & WGET_NO_FTRUNCATE))
ftruncate(G.output_fd, pos);
}
pos = lseek(G.output_fd, 0, SEEK_CUR);
if (pos != (off_t)-1) {
/* do not truncate if -O- >>FILE is in use, a user complained about
* "wget -O- 'http://host.com/empty' >>FILE" truncating FILE.
*/
if (!(fcntl(G.output_fd, F_GETFL) & O_APPEND))
ftruncate(G.output_fd, pos);
}
if (!(option_mask32 & WGET_OPT_QUIET)) {
@@ -1092,12 +1114,14 @@ static void NOINLINE retrieve_file_data(FILE *dfp)
else
fprintf(stderr, "'%s' saved\n", G.fname_out);
}
return 0; /* "full download" */
}
static void download_one_url(const char *url)
{
bool use_proxy; /* Use proxies if env vars are set */
int redir_limit;
int retry_cnt = G.tries;
len_and_sockaddr *lsa;
FILE *sfp; /* socket to web/ftp server */
FILE *dfp; /* socket to ftp server (data) */
@@ -1166,6 +1190,7 @@ static void download_one_url(const char *url)
* We are not sure it exists on remote side */
}
restart:
redir_limit = 16;
resolve_lsa:
lsa = xhost2sockaddr(server.host, server.port);
@@ -1234,6 +1259,8 @@ static void download_one_url(const char *url)
SENDFMT(sfp, "Host: %s\r\n", target.host);
if (!USR_HEADER_USER_AGENT)
SENDFMT(sfp, "User-Agent: %s\r\n", G.user_agent);
if (!USR_HEADER_ACCEPT)
SENDFMT(sfp, "Accept: */*\r\n");
/* Ask server to close the connection as soon as we are done
* (IOW: we do not intend to send more requests)
@@ -1310,8 +1337,8 @@ static void download_one_url(const char *url)
str = G.wget_buf;
str = skip_non_whitespace(str);
str = skip_whitespace(str);
// FIXME: no error check
// xatou wouldn't work: "200 OK"
// FIXME: no error check
// xatou wouldn't work: "200 OK"
status = atoi(str);
switch (status) {
case 0:
@@ -1464,10 +1491,23 @@ However, in real world it was observed that some web servers
if (!(option_mask32 & WGET_OPT_SPIDER)) {
if (G.output_fd < 0)
G.output_fd = xopen(G.fname_out, G.o_flags);
retrieve_file_data(dfp);
if (retrieve_file_data(dfp) != 0) {
/* Partial download */
if (G.tries == 0 || retry_cnt-- != 0) {
G.beg_range += G.transferred;
goto restart;
}
/* else: -t TRIES exceeded */
//FIXME: should we abort instead of continuing with next URL?
}
if (!(option_mask32 & WGET_OPT_OUTNAME)) {
xclose(G.output_fd);
G.output_fd = -1;
} else { /* -O FILE receives _all_ URLs concatenated */
/*
* For "wget -O FILE URL1 URL2":
* remember where URL1 data ends in FILE */
G.reset_pos += G.beg_range + G.transferred;
}
} else {
if (!(option_mask32 & WGET_OPT_QUIET))
@@ -1509,8 +1549,7 @@ int wget_main(int argc UNUSED_PARAM, char **argv)
"user-agent\0" Required_argument "U"
IF_FEATURE_WGET_TIMEOUT(
"timeout\0" Required_argument "T")
/* Ignored: */
IF_DESKTOP( "tries\0" Required_argument "t")
"tries\0" Required_argument "t"
"header\0" Required_argument "\xff"
"post-data\0" Required_argument "\xfe"
"spider\0" No_argument "\xfd"
@@ -1538,6 +1577,7 @@ IF_DESKTOP( "no-parent\0" No_argument "\xf0")
INIT_G();
G.tries = 20;
#if ENABLE_FEATURE_WGET_TIMEOUT
G.timeout_seconds = 900;
signal(SIGALRM, alarm_handler);
@@ -1547,7 +1587,7 @@ IF_DESKTOP( "no-parent\0" No_argument "\xf0")
GETOPT32(argv, "^"
"cqSO:o:P:Y:U:T:+"
/*ignored:*/ "t:"
"t:+"
/*ignored:*/ "n::"
/* wget has exactly four -n<letter> opts, all of which we can ignore:
* -nv --no-verbose: be moderately quiet (-q is full quiet)
@@ -1567,7 +1607,7 @@ IF_DESKTOP( "no-parent\0" No_argument "\xf0")
, &G.fname_out, &G.fname_log, &G.dir_prefix,
&G.proxy_flag, &G.user_agent,
IF_FEATURE_WGET_TIMEOUT(&G.timeout_seconds) IF_NOT_FEATURE_WGET_TIMEOUT(NULL),
NULL, /* -t RETRIES */
&G.tries, /* -t RETRIES */
NULL /* -n[ARG] */
IF_FEATURE_WGET_LONG_OPTIONS(, &headers_llist)
IF_FEATURE_WGET_LONG_OPTIONS(, &G.post_data)
@@ -1622,7 +1662,7 @@ IF_DESKTOP( "no-parent\0" No_argument "\xf0")
if (G.fname_out) { /* -O FILE ? */
if (LONE_DASH(G.fname_out)) { /* -O - ? */
G.output_fd = 1;
option_mask32 = (option_mask32 & (~WGET_OPT_CONTINUE)) | WGET_NO_FTRUNCATE;
option_mask32 = (option_mask32 & (~WGET_OPT_CONTINUE));
}
/* compat with wget: -O FILE can overwrite */
G.o_flags = O_WRONLY | O_CREAT | O_TRUNC;
+5 -2
View File
@@ -193,8 +193,11 @@ int kill_main(int argc UNUSED_PARAM, char **argv)
if (!is_killall5 && arg[0] == '-' && arg[1] == '\0')
goto do_it_sooner;
if (argv[1] && arg[0] == 's' && arg[1] == '\0') { /* -s SIG? */
arg = *++argv;
if (arg[0] == 's') {
arg++;
if (!*arg && argv[1]) /* -s SIG? */
arg = *++argv;
/* else -sSIG */
} /* else it must be -SIG */
signo = get_signum(arg);
if (signo < 0) {
+35 -22
View File
@@ -25,7 +25,7 @@
//usage: "\nFormat specifiers:"
//usage: "\n %Nc or %[cN] CPU. N - bar size (default 10)"
//usage: "\n (displays: S:system U:user N:niced D:iowait I:irq i:softirq)"
//usage: "\n %[nINTERFACE] Network INTERFACE"
//usage: "\n %[nINTERFACE] Network INTERFACE (if error counters change, prepends *)"
//usage: "\n %m Allocated memory"
//usage: "\n %[md] Dirty file-backed memory"
//usage: "\n %[mw] Memory being written to storage"
@@ -86,10 +86,11 @@ struct globals {
smallint is26;
// 1 if sample delay is not an integer fraction of a second
smallint need_seconds;
smallint continuous_updates;
char final_char;
char *cur_outbuf;
int delta;
unsigned deltanz;
ullong delta;
ullong deltanz;
struct timeval tv;
struct timeval start;
#define first_proc_file proc_stat
@@ -900,9 +901,14 @@ int nmeter_main(int argc UNUSED_PARAM, char **argv)
}
if (getopt32(argv, "d:", &opt_d)) {
G.delta = xatoi(opt_d) * 1000;
G.deltanz = G.delta > 0 ? G.delta : 1;
need_seconds = (1000000 % G.deltanz) != 0;
if (opt_d[0] != '-') {
G.delta = xatou(opt_d) * 1000ULL;
G.deltanz = G.delta > 0 ? G.delta : 1;
need_seconds = (1000000 % G.deltanz) != 0;
} else {
G.continuous_updates = 1;
}
}
argv += optind;
@@ -979,7 +985,7 @@ int nmeter_main(int argc UNUSED_PARAM, char **argv)
collect_info(first);
reset_outbuf();
if (G.delta >= 0) {
if (!G.continuous_updates) {
xgettimeofday(&G.tv);
usleep(G.delta > 1000000 ? 1000000 : G.delta - G.tv.tv_usec % G.deltanz);
}
@@ -992,8 +998,8 @@ int nmeter_main(int argc UNUSED_PARAM, char **argv)
// 00:00:00.000161 12:32:07.500161
// 00:00:00.500282 12:32:08.000282
// 00:00:01.000286 12:32:08.500286
if (G.delta > 0)
G.start.tv_usec -= (G.start.tv_usec % (unsigned)G.delta);
if (!G.continuous_updates)
G.start.tv_usec -= (G.start.tv_usec % G.delta);
while (1) {
collect_info(first);
@@ -1005,10 +1011,10 @@ int nmeter_main(int argc UNUSED_PARAM, char **argv)
// time resolution ;)
// TODO: detect and avoid useless updates
// (like: nothing happens except time)
if (G.delta >= 0) {
int rem;
// can be commented out, will sacrifice sleep time precision a bit
xgettimeofday(&G.tv);
if (!G.continuous_updates) {
ullong rem;
for (;;) {
xgettimeofday(&G.tv);
// TODO: nmeter -d10000 '%6T %6t'
// 00:00:00.770333 12:34:44.770333
@@ -1018,16 +1024,23 @@ int nmeter_main(int argc UNUSED_PARAM, char **argv)
// we can't syncronize interval to start close to 10 seconds for both
// %T and %t (as shown above), but what if there is only %T
// in format string? Maybe sync _it_ instead of %t in this case?
if (need_seconds)
rem = G.delta - ((ullong)G.tv.tv_sec*1000000 + G.tv.tv_usec) % G.deltanz;
else
rem = G.delta - (unsigned)G.tv.tv_usec % G.deltanz;
// Sometimes kernel wakes us up just a tiny bit earlier than asked
// Do not go to very short sleep in this case
if (rem < (unsigned)G.delta / 128) {
rem += G.delta;
if (need_seconds)
rem = G.delta - ((ullong)G.tv.tv_sec*1000000 + G.tv.tv_usec) % G.deltanz;
else
rem = G.delta - (ullong)G.tv.tv_usec % G.deltanz;
// Sometimes kernel wakes us up just a tiny bit earlier than asked
// Do not go to very short sleep in this case
if (rem < 100) { // less than 0.1ms to sleep?
if (rem < G.delta / 128) // why: cater for tiny cases like -d10: do not skip every update for these
rem += G.delta;
}
if (rem <= 10*1000*1000)
break;
//bb_error_msg("sleep %u", (unsigned)(rem / (1000*1000)) - 1);
sleep((unsigned)(rem / (1000*1000)) - 1);
}
usleep(rem);
//bb_error_msg("usleep %u", (unsigned)rem);
usleep((unsigned)rem);
}
xgettimeofday(&G.tv);
}
+2 -2
View File
@@ -244,7 +244,7 @@ struct globals {
#define INIT_G() do { \
setup_common_bufsiz(); \
SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
linemax = 1000; \
linemax = COMMON_BUFSIZE - 26; \
/*buflen = 1024;*/ \
linecomplete = 1; \
replace = ""; \
@@ -1069,7 +1069,7 @@ int svlogd_main(int argc, char **argv)
}
if (opt & 2) if (!repl) repl = '_'; // -R
if (opt & 4) { // -l
linemax = xatou_range(l, 0, COMMON_BUFSIZE-26);
linemax = xatou_range(l, 0, COMMON_BUFSIZE - 26);
if (linemax == 0)
linemax = COMMON_BUFSIZE-26;
if (linemax < 256)
+7 -3
View File
@@ -4,6 +4,7 @@ run_testsuite=false
run_testsuite=true
# See testsuite/README:
export SKIP_KNOWN_BUGS=1
#export SKIP_KNOWN_BUG_AWK_WORDMATCH=1
#export SKIP_INTERNET_TESTS=1
# See testsuite/mount.tests:
export SKIP_MOUNT_MAND_TESTS=1
@@ -11,6 +12,9 @@ export SKIP_MOUNT_MAND_TESTS=1
run_single_test=false
run_single_test=true
stop_on_failure=false
stop_on_failure=true
export LIBC="uclibc"
export CROSS_COMPILER_PREFIX="i686-"
export MAKEOPTS="-j9"
@@ -35,7 +39,7 @@ while sleep 1; do
if ! "$1/scripts/randomtest" "$1" "$dir" >/dev/null; then
mv -- "$dir" "failed.$dir"
echo "Failed build in: failed.$dir"
exit 1 # you may comment this out...
$stop_on_failure && exit 1
let fail++
continue
fi
@@ -48,7 +52,7 @@ while sleep 1; do
if test $? != 0; then
echo "Failed runtest in $dir"
grep ^FAIL -- "$dir/testsuite/runtest.log"
exit 1 # you may comment this out...
$stop_on_failure && exit 1
let fail++
continue
fi
@@ -71,7 +75,7 @@ while sleep 1; do
)
if test $? != 0; then
echo "Failed make_single_applets.sh in $dir"
exit 1 # you may comment this out...
$stop_on_failure && exit 1
let fail++
continue
fi
+2 -2
View File
@@ -67,8 +67,8 @@ static int FAST_FUNC change_filedir_context(struct recursive_state *state UNUSED
struct stat *stbuf UNUSED_PARAM)
{
context_t context = NULL;
security_context_t file_context = NULL;
security_context_t context_string;
char *file_context = NULL;
const char *context_string;
int rc = FALSE;
int status = 0;
+1 -1
View File
@@ -80,7 +80,7 @@ int matchpathcon_main(int argc UNUSED_PARAM, char **argv)
}
while ((path = *argv++) != NULL) {
security_context_t con;
char *con;
int rc;
if (!(opts & OPT_VERIFY)) {
+2 -2
View File
@@ -62,13 +62,13 @@ static context_t runcon_compute_new_context(char *user, char *role, char *type,
char *command, int compute_trans)
{
context_t con;
security_context_t cur_context;
char *cur_context;
if (getcon(&cur_context))
bb_simple_error_msg_and_die("can't get current context");
if (compute_trans) {
security_context_t file_context, new_context;
char *file_context, *new_context;
if (getfilecon(command, &file_context) < 0)
bb_error_msg_and_die("can't retrieve attributes of '%s'",
+1 -1
View File
@@ -92,7 +92,7 @@ static void read_config(char **pc, int npc, char **fc, int nfc)
static void display_verbose(void)
{
security_context_t con, _con;
char *con, *_con;
char *fc[50], *pc[50], *cterm;
pid_t *pidList;
int i;
+275 -115
View File
@@ -2252,6 +2252,7 @@ struct localvar {
#define VSTRFIXED 0x04 /* variable struct is statically allocated */
#define VTEXTFIXED 0x08 /* text is statically allocated */
#define VSTACK 0x10 /* text is allocated on the stack */
//^^^ is VSTACK unused?
#define VUNSET 0x20 /* the variable is not set */
#define VNOFUNC 0x40 /* don't call the callback function */
#define VNOSET 0x80 /* do not set variable - just readonly test */
@@ -2300,11 +2301,17 @@ static const struct {
*/
{ VSTRFIXED|VTEXTFIXED , defifsvar , NULL },
#if ENABLE_ASH_MAIL
{ VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL" , changemail },
{ VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH" , changemail },
// Two NULs are necessary since mailval()/mpathval() use var_text+5/+9
// to skip over var name and '=' sign (if variable is set).
{ VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL\0" , changemail },
{ VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH\0", changemail },
#endif
{ VSTRFIXED|VTEXTFIXED , bb_PATH_root_path, changepath },
#if ENABLE_FEATURE_EDITING_FANCY_PROMPT
{ VSTRFIXED|VTEXTFIXED , "PS1=\\w \\$ ", NULL },
#else
{ VSTRFIXED|VTEXTFIXED , "PS1=$ " , NULL },
#endif
{ VSTRFIXED|VTEXTFIXED , "PS2=> " , NULL },
{ VSTRFIXED|VTEXTFIXED , "PS4=+ " , NULL },
#if ENABLE_ASH_GETOPTS
@@ -2455,14 +2462,13 @@ initvar(void)
struct var *end;
struct var **vpp;
/*
* PS1 depends on uid
*/
#if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
vps1.var_text = "PS1=\\w \\$ ";
#else
if (!get_cached_euid(&groupinfo.euid));
/* PS1 depends on uid */
#if !ENABLE_FEATURE_EDITING_FANCY_PROMPT
if (get_cached_euid(&groupinfo.euid) == 0)
vps1.var_text = "PS1=# ";
/* else: the default "$ " is already set */
#else
/* default "\\w \\$ " prompt already takes care of #/$ */
#endif
vp = varinit;
end = vp + ARRAY_SIZE(varinit);
@@ -2651,6 +2657,7 @@ setvar(const char *name, const char *val, int flags)
*p++ = '=';
strcpy(p, val);
}
// else: the string is "VARNAME\0\0". Important for var_text+5 to work correctly for "MAIL" et al
vp = setvareq(nameeq, flags | VNOSAVE);
INTON;
@@ -2870,7 +2877,8 @@ static const char *expandstr(const char *ps, int syntax_type);
#if ENABLE_ASH_EXPAND_PRMT
# define PSSYNTAX 4 /* prompt. never passed to SIT() */
#endif
/* PSSYNTAX expansion is identical to DQSYNTAX, except keeping '\$' as '\$' */
/* PSSYNTAX expansion is identical to DQSYNTAX, except keeping '\$' as '\$'
* and '\\' as '\\' */
/*
* called by editline -- any expansions to the prompt should be added here.
@@ -3664,7 +3672,7 @@ signal_handler(int signo)
if (!trap[SIGCHLD])
return;
}
#if ENABLE_FEATURE_EDITING
#if 1 // ENABLE_FEATURE_EDITING || IF_READ_WHICH_WE_ALWAYS_SUPPORT
//TODO: don't do it if it's SIGCHLD?
bb_got_signal = signo; /* for read_line_input / read builtin: "we got a signal" */
#endif
@@ -4333,7 +4341,7 @@ waitproc(int block, int *status)
{
sigset_t oldmask;
int flags = block == DOWAIT_BLOCK ? 0 : WNOHANG;
int err;
int pid;
#if JOBS
if (jobctl)
@@ -4342,48 +4350,59 @@ waitproc(int block, int *status)
do {
gotsigchld = 0;
do
err = waitpid(-1, status, flags);
while (err < 0 && errno == EINTR);
//do
// pid = waitpid(-1, status, flags);
//while (pid < 0 && errno == EINTR);
//bb_error_msg("waitpid(%x)", flags);
pid = safe_waitpid(-1, status, flags);
//bb_error_msg("waitpid(%x)=%d", flags, pid);
/* Return if error (for example, ECHILD); or if pid found;
* or if "block" is DOWAIT_NONBLOCK (=0), in this case return -1.
*/
if (err || (err = -!block))
break;
if (pid != 0) /* waitpid() returned PID or error? */
break; /* return it */
/* "block" is DOWAIT_CHILD_OR_SIG. All children are running
* (waitpid(WNOHAG) above returned 0), wait for signals:
*/
/* We are here only if DOWAIT_NONBLOCK or DOWAIT_CHILD_OR_SIG */
if (block == DOWAIT_NONBLOCK)
return -1;
/* DOWAIT_CHILD_OR_SIG: children exist and running, wait for a signal */
//simpler, but unsafe: a signal can set pending_sig after check, but before pause():
//while (!gotsigchld && !pending_sig)
// pause();
sigblockall(&oldmask);
//bb_error_msg("sigsuspend()");
while (!gotsigchld && !pending_sig)
sigsuspend(&oldmask);
sigclearmask();
} while (gotsigchld);
/* If we fall off the loop, err is 0, which means we got a !SIGCHLD signal */
/* If we fall off the loop, pid is 0, which means we got a !SIGCHLD signal */
return err;
/* Possible returns:
* PID of successfully waited-for child.
* -1 on waitpid() error (can get ECHILD: no one to wait for)
* -1 if DOWAIT_NONBLOCK
* 0 if there were no waitable children and got a signal (not SIGCHLD)
*/
return pid;
}
static int waitone(int block, struct job *job)
#if !BASH_WAIT_N
#define waitone(block, job, pstatus, jpp) \
waitone(block, job)
#endif
static int waitone(int block, struct job *job, int *pstatus, struct job **done_jpp)
{
int pid;
int status;
struct job *jp;
struct job *thisjob = NULL;
#if BASH_WAIT_N
bool want_jobexitstatus = (block & DOWAIT_JOBSTATUS);
int want_jobexitstatus = (block & DOWAIT_JOBSTATUS);
block = (block & ~DOWAIT_JOBSTATUS);
#endif
TRACE(("dowait(0x%x) called\n", block));
TRACE(("waitone(0x%x) called\n", block));
/* It's wrong to call waitpid() outside of INTOFF region:
* signal can arrive just after syscall return and handler can
@@ -4405,7 +4424,7 @@ static int waitone(int block, struct job *job)
*/
INTOFF;
pid = waitproc(block, &status);
TRACE(("wait returns pid %d, status=%d\n", pid, status));
TRACE(("waitproc returns pid %d, status=%d\n", pid, status));
if (pid <= 0)
goto out;
@@ -4414,7 +4433,7 @@ static int waitone(int block, struct job *job)
struct procstat *sp;
struct procstat *spend;
if (jp->state == JOBDONE)
continue;
continue; /* have to skip already DONE jobs (the pids may be stale) */
jobstate = JOBDONE;
spend = jp->ps + jp->nprocs;
sp = jp->ps;
@@ -4462,9 +4481,12 @@ static int waitone(int block, struct job *job)
#if BASH_WAIT_N
if (want_jobexitstatus) {
pid = -1;
if (thisjob && thisjob->state == JOBDONE)
pid = thisjob->ps[thisjob->nprocs - 1].ps_status;
if (thisjob && thisjob->state == JOBDONE) {
if (done_jpp)
*done_jpp = thisjob;
if (pstatus)
*pstatus = status;
} /* else: the job is not found, or not fully completed */
}
#endif
if (thisjob && thisjob == job) {
@@ -4481,30 +4503,64 @@ static int waitone(int block, struct job *job)
return pid;
}
static int dowait(int block, struct job *jp)
#if !BASH_WAIT_N
#define dowait_n(block, jp, pstatus, done_jpp) \
dowait_n(block, jp)
#endif
static int dowait_n(int block, struct job *jp, int *pstatus, struct job **done_jpp)
{
smallint gotchld = *(volatile smallint *)&gotsigchld;
int rpid;
int pid;
if (jp && jp->state != JOBRUNNING)
block = DOWAIT_NONBLOCK;
if (block == DOWAIT_NONBLOCK && !gotchld)
return 1;
rpid = 1;
/* In what cases we loop here:
* = If we waited in blocking mode and got pid > 0,
* but the job we waiting for is still running
* (jp->state == JOBRUNNING), we have to wait in blocking mode again,
* until it's not JOBRUNNING.
* The user is waitforjob(jp) -> dowait(DOWAIT_BLOCK, jp).
* = If we waited in non-blocking mode and got pid > 0,
* we should see whether more processes have terminated,
* we have to wait in non-blocking mode again.
* The users are
* showjobs() -> dowait(DOWAIT_NONBLOCK, NULL)
* waitforjob(NULL) -> dowait(DOWAIT_NONBLOCK, NULL)
* waitcmd() does its own looping while it sees at least one JOBRUNNING
* job, it does not need us to loop here - only to do
* one nonblocking wait and if it gives nothing, wait for signals.
*/
do {
pid = waitone(block, jp);
rpid &= !!pid;
pid = waitone(block, jp, pstatus, done_jpp);
#if BASH_WAIT_N
if (block & DOWAIT_JOBSTATUS)
break;
/* on signals, unknown pids, or not-fully completed jobs we get -1 */
/* it is always DOWAIT_CHILD_OR_SIG in this case */
#endif
if (pid == 0)
break; /* return 0: got a signal */
if (jp && jp->state != JOBRUNNING) {
/* no more running procs in this job, stop waiting */
break; /* return pid != 0: did not get a signal */
}
/* if we saw a process changing state, wait again (is there more?) */
} while (pid > 0);
if (!pid || (jp && jp->state != JOBRUNNING))
block = DOWAIT_NONBLOCK;
} while (pid >= 0);
return rpid;
return pid;
}
/* nake dowait() calls look the same as in dash: */
#if !BASH_WAIT_N
# define dowait(block, jp) dowait_n((block), (jp), UNUSED, UNUSED)
#else
static int dowait(int block, struct job *jp)
{
return dowait_n(block, jp, NULL, NULL);
}
#endif
/*
* Wait for job to finish.
@@ -4678,7 +4734,7 @@ showjobs(int mode)
TRACE(("showjobs(0x%x) called\n", mode));
/* Handle all finished jobs */
dowait(DOWAIT_NONBLOCK, NULL);
dowait(DOWAIT_NONBLOCK, /*job:*/ NULL);
for (jp = curjob; jp; jp = jp->prev_job) {
if (!(mode & SHOW_CHANGED) || jp->changed) {
@@ -4805,36 +4861,90 @@ stoppedjobs(void)
#define stoppedjobs() 0
#endif
static struct job*
getjob_match_last_pid(pid_t pid)
{
struct job *jp = curjob;
while (jp) {
// WRONG: "wait -n $PID;echo $?;wait -n $PID;echo $?"
// should work and produce the same exitcode the second time
//if (/* jp->state == JOBDONE && */ jp->waited)
// ; /* these never match (pids can be very stale) */
//else
if (jp->ps[jp->nprocs - 1].ps_pid == pid)
break;
jp = jp->prev_job;
}
return jp;
}
#if BASH_WAIT_N
static int
match_pid_or_jobspecs(pid_t pid, struct job *done_job, char **argp, int status)
{
while (*argp) {
if (**argp != '%') {
/* number() can't fail here: known to be valid number */
if (pid == number(*argp)) {
if (WIFEXITED(status))
return WEXITSTATUS(status);
return 128 | WTERMSIG(status);
}
} else if (done_job) {
/* getjob() can't fail here either */
struct job *jp = getjob(*argp, /*must_be_jobctl:*/ 0);
if (jp == done_job)
return getstatus(jp);
}
argp++;
}
return -1;
}
#endif
static int FAST_FUNC
waitcmd(int argc UNUSED_PARAM, char **argv)
{
struct job *job;
int retval;
pid_t pid;
struct job *jp;
#if BASH_WAIT_N
int status;
char one = nextopt("n");
struct job *done_job;
char wait_n = nextopt("n");
#else
int wait_n = 0; /* never changes if !BASH_WAIT_N */
nextopt(nullstr);
#endif
retval = 0;
argv = argptr;
if (!argv[0]) {
/* wait for all jobs / one job if -n */
/* Wait for all jobs / one (any) job if -n */
for (;;) {
jp = curjob;
#if BASH_WAIT_N
if (one && !jp)
/* exitcode of "wait -n" with nothing to wait for is 127, not 0 */
retval = 127;
#endif
while (1) {
if (!jp) /* no running procs */
if (!jp) { /* no more jobs */
if (wait_n == 1)
break; /* there is a live job */
if (wait_n == 'n') /* exitcode of "wait -n" with nothing to wait for is 127, not 0 */
retval = 127;
goto ret;
if (jp->state == JOBRUNNING)
break;
jp->waited = 1;
}
if (!wait_n) {
if (jp->state != JOBDONE)
break; /* we have a live job: have to wait */
/* "wait" makes all DONE jobs waited-for */
jp->waited = 1;
} else {
if (jp->state != JOBDONE) {
wait_n = 1; /* replace 'n': mark that we found a live job */
} else if (!jp->waited) {
jp->waited = 1;
/* "wait -n" returns status of unwaited-for dead jobs immediately */
/* (bash-5.3.9 does this in -c 'CMDs' and scripts only) */
retval = getstatus(jp);
goto ret;
}
}
jp = jp->prev_job;
}
/* man bash:
@@ -4845,9 +4955,10 @@ waitcmd(int argc UNUSED_PARAM, char **argv)
* the trap is executed."
*/
#if BASH_WAIT_N
status = dowait(DOWAIT_CHILD_OR_SIG | DOWAIT_JOBSTATUS, NULL);
done_job = NULL;
pid = dowait_n(DOWAIT_CHILD_OR_SIG | DOWAIT_JOBSTATUS, /*job:*/ NULL, &status, &done_job);
#else
dowait(DOWAIT_CHILD_OR_SIG, NULL);
dowait(DOWAIT_CHILD_OR_SIG, /*job:*/ NULL);
#endif
/* if child sends us a signal *and immediately exits*,
* dowait() returns pid > 0. Check this case,
@@ -4856,44 +4967,85 @@ waitcmd(int argc UNUSED_PARAM, char **argv)
if (pending_sig)
goto sigout;
#if BASH_WAIT_N
if (one) {
if (wait_n) {
/* wait -n waits for one _job_, not one _process_.
* date; sleep 3 & sleep 2 | sleep 1 & wait -n; date
* should wait for 2 seconds. Not 1 or 3.
*/
if (status != -1 && !WIFSTOPPED(status)) {
retval = WEXITSTATUS(status);
if (WIFSIGNALED(status))
retval = 128 | WTERMSIG(status);
if (done_job) { /* a job has exited (all its processes) */
done_job->waited = 1;
retval = getstatus(done_job);
goto ret;
}
/* else: not entire job has exited (only a process), wait more */
}
#endif
}
} /* for (;;) */
}
retval = 127;
#if BASH_WAIT_N
if (wait_n) {
/* Check whether an exited job already matches */
char **argp = argv;
do {
if (**argp != '%') {
pid = number(*argp); /* exception thrown if malformed */
jp = getjob_match_last_pid(pid);
if (!jp) {
goto wait_for_anything;
}
} else {
jp = getjob(*argp, /*must_be_jobctl:*/ 0); /* exception thrown if no such job */
}
if (jp->state == JOBDONE) { /* not checking jp->waited - even already waited-for matches */
jp->waited = 1;
/* "wait -n" returns status of dead jobs immediately */
/* (bash-5.3.9 does this in -c 'CMDs' and scripts only) */
retval = getstatus(jp);
goto ret;
}
} while (*++argp);
/* Wait repeatedly, check whether a matching process or job exited */
wait_for_anything:
for (;;) {
done_job = NULL;
pid = dowait_n(DOWAIT_CHILD_OR_SIG | DOWAIT_JOBSTATUS, /*job:*/ NULL, &status, &done_job);
if (pending_sig)
goto sigout;
if (pid < 0 && errno == ECHILD)
break;
if (pid > 0) {
/* either match PID and pid, or %JOB and done_job (in latter case status can change to done_job's status) */
status = match_pid_or_jobspecs(pid, done_job, argv, status);
if (status >= 0) {
/* even if we did "wait -n PID", not %JOB, if this matches exited job's last pid... */
/* ("CMD1|CMD2 & bg=$!; wait -n $bg" idiom uses pid of CMD2 intending to wait for the whole job) */
if (done_job && done_job->ps[done_job->nprocs - 1].ps_pid == pid)
done_job->waited = 1; /* ...the job is now "waited for" */
retval = status;
goto ret;
} /* else: this is not the process "wait -n PID1 JOBSPEC1 PID2..." waits for: wait more */
}
} /* for (;;) */
} else
#endif
do {
if (**argv != '%') {
pid_t pid = number(*argv);
job = curjob;
while (1) {
if (!job)
goto repeat;
if (job->ps[job->nprocs - 1].ps_pid == pid)
break;
job = job->prev_job;
}
pid = number(*argv); /* exception thrown if malformed */
jp = getjob_match_last_pid(pid);
if (!jp)
continue;
} else {
job = getjob(*argv, 0);
jp = getjob(*argv, 0); /* exception thrown if no such job */
}
/* loop until process terminated or stopped */
dowait(DOWAIT_CHILD_OR_SIG, job);
/* loop until process terminated (but stops do not count) */
dowait(DOWAIT_CHILD_OR_SIG, jp);
if (pending_sig)
goto sigout;
job->waited = 1;
retval = getstatus(job);
repeat: ;
jp->waited = 1;
retval = getstatus(jp);
} while (*++argv);
ret:
@@ -5574,6 +5726,7 @@ write2pipe(int pip[2], const char *p, size_t len)
/* openhere needs this forward reference */
static void expandhere(union node *arg);
static void ifsfree(void);
static int
openhere(union node *redir)
{
@@ -5998,6 +6151,17 @@ redirect(union node *redir, int flags)
// preverrout_fd = copied_fd2;
}
static void
restore_handler_expandarg(struct jmploc *savehandler, int err)
{
exception_handler = savehandler;
if (err) {
if (exception_type != EXERROR)
longjmp(exception_handler->loc, 1);
ifsfree();
}
}
static int
redirectsafe(union node *redir, int flags)
{
@@ -6013,9 +6177,7 @@ redirectsafe(union node *redir, int flags)
exception_handler = &jmploc;
redirect(redir, flags);
}
exception_handler = savehandler;
if (err && exception_type != EXERROR)
longjmp(exception_handler->loc, 1);
restore_handler_expandarg(savehandler, err);
RESTORE_INT(saveint);
return err;
}
@@ -9585,8 +9747,7 @@ static int funcline; /* starting line number of current function, or
static int evalstring(char *s, int flags);
/* Called to execute a trap.
* Single callsite - at the end of evaltree().
* If we return non-zero, evaltree raises EXEXIT exception.
* Called in at the beginning and end of evaltree(), and in readcmd() if signal is trapped.
*
* Perhaps we should avoid entering new trap handlers
* while we are executing a trap handler. [is it a TODO?]
@@ -9607,6 +9768,7 @@ dotrap(void)
status = exitstatus;
savestatus = status;
}
bb_got_signal = 0; /* or else read builtin gets immediately "interrupted" by already handled past signal */
pending_sig = 0;
barrier();
@@ -9792,9 +9954,7 @@ evaltree(union node *n, int flags)
trap_depth--;
in_trap_ERR = 0;
exception_handler = savehandler;
if (err && exception_type != EXERROR)
longjmp(exception_handler->loc, 1);
restore_handler_expandarg(savehandler, err);
exitstatus = savestatus;
}
@@ -11384,14 +11544,16 @@ preadfd(void)
* #(bash 5.0.17 exits after first "T", looks like a bug)
*/
bb_got_signal = 0;
if (pending_sig)
goto got_signal;
INTOFF; /* no longjmp'ing out of read_line_input please */
nr = read_line_input(line_input_state, cmdedit_prompt, buf, IBUFSIZ);
if (bb_got_signal == SIGINT)
write(STDOUT_FILENO, "^C\n", 3);
write(STDERR_FILENO, "^C\n", 3);
INTON; /* here non-blocked SIGINT will longjmp */
if (nr == 0) {
/* ^C pressed, "convert" to SIGINT */
write(STDOUT_FILENO, "^C\n", 3);
write(STDERR_FILENO, "^C\n", 3);
raise(SIGINT); /* here non-blocked SIGINT will longjmp */
/* raise(SIGINT) did not work! (e.g. if SIGINT
* is SIG_IGNed on startup, it stays SIG_IGNed)
@@ -11407,21 +11569,22 @@ preadfd(void)
goto again;
}
if (nr < 0) {
if (errno == 0) {
/* ^D pressed */
nr = 0;
}
else if (errno == EINTR) { /* got signal? */
if (errno == EINTR) { /* got signal? */
got_signal:
if (bb_got_signal != SIGINT)
write(STDOUT_FILENO, "\n", 1);
write(STDERR_FILENO, "\n", 1);
goto empty_line_input;
}
# if ENABLE_ASH_IDLE_TIMEOUT
else if (errno == EAGAIN && timeout > 0) {
if (errno == EAGAIN && timeout > 0) { /* bash 5.3.9 writes thsi to stdout, not stderr */
puts("\007timed out waiting for input: auto-logout");
exitshell();
}
# endif
if (errno == 0) {
/* ^D pressed */
nr = 0;
}
}
}
#else
@@ -12468,11 +12631,13 @@ pipeline(void)
negate = 0;
TRACE(("pipeline: entered\n"));
if (readtoken() == TNOT) {
/* At least bash 5.2.15 allows multiple negations */
/* "! ! CMD" does not mean "normalize to only 0 or 1", it just nullifies first ! */
while (readtoken() == TNOT) {
negate = !negate;
checkkwd = CHKKWD | CHKALIAS;
} else
tokpushback = 1;
checkkwd = CHKKWD | CHKALIAS; /* restore what readtoken() cleared */
}
tokpushback = 1;
n1 = parse_command();
if (readtoken() == TPIPE) {
pipenode = stzalloc(sizeof(struct npipe));
@@ -13076,7 +13241,7 @@ readtoken1(int c, int syntax, struct heredoc *eofmark)
USTPUTC('\\', out);
pungetc();
} else {
if (pssyntax && c == '$') {
if (pssyntax && (c == '$' || c == '\\')) {
USTPUTC(CTLESC, out);
USTPUTC('\\', out);
}
@@ -13856,13 +14021,10 @@ readtoken(void)
int t;
int kwd = checkkwd;
#if DEBUG
smallint alreadyseen = tokpushback;
#endif
#if ENABLE_ASH_ALIAS
top:
int alreadyseen = tokpushback;
#endif
IF_ASH_ALIAS(top:)
t = xxreadtoken();
/*
@@ -14009,9 +14171,7 @@ expandstr(const char *ps, int syntax_type)
result = stackblock();
out:
exception_handler = savehandler;
if (err && exception_type != EXERROR)
longjmp(exception_handler->loc, 1);
restore_handler_expandarg(savehandler, err);
doprompt = saveprompt;
/* Try: PS1='`xxx(`' */
@@ -14654,14 +14814,14 @@ readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
again:
INTOFF;
r = shell_builtin_read(&params);
INTON;
INTON; /* here non-blocked SIGINT will longjmp */
if ((uintptr_t)r == 1 && errno == EINTR) {
/* To get SIGCHLD: sleep 1 & read x; echo $x
* Correct behavior is to not exit "read"
*/
if (pending_sig == 0)
goto again;
dotrap(); /* NOP if pending_sig == 0 */
goto again;
}
if ((uintptr_t)r == 2) /* -t SEC timeout? */
@@ -0,0 +1,6 @@
wait -n
from USR1
prints after USR1
wait
from USR1
prints after USR1 (2)
+21
View File
@@ -0,0 +1,21 @@
# tests wait and signals
trap 'echo from USR1' USR1
echo "wait -n"
{ sleep 1; kill -USR1 $$; sleep 1; echo prints after USR1; } &
wait -n
rc=$?
[ "$rc" = 138 ] || echo "rc not 138: $?"
wait -n
rc=$?
[ "$rc" = 0 ] || echo "rc not 0: $?"
echo "wait"
{ sleep 1; kill -USR1 $$; sleep 1; echo "prints after USR1 (2)"; } &
wait
rc=$?
[ "$rc" = 138 ] || echo "rc not 138: $?"
wait
rc=$?
[ "$rc" = 0 ] || echo "rc not 0: $?"
@@ -0,0 +1,7 @@
wait1
INT
w1:130
wait2
INT
w2:130
Ok:0
@@ -0,0 +1,9 @@
trap 'echo INT' INT
(sleep 2;sh -c 'kill -sstop $$') &
bg=$!
(sleep 1;kill -INT $$;sleep 2;kill -INT $$) &
echo wait1; wait; echo w1:$?
echo wait2; wait; echo w2:$?
kill -cont $bg
kill $bg
echo Ok:$?
@@ -0,0 +1,5 @@
Sent SIGTERM:0
Test: wait -n exit code for sigkilled (and possibly already waited-for) pipe
wait -n #1: 143 (should be 143 = 128+SIGTERM)
Test: wait -n exits 127 if nothing to wait for
wait -n #1: 127 (should be 127)
@@ -0,0 +1,15 @@
sleep 1 && echo 'Should not be reached' &
bg=$!
kill $bg
echo "Sent SIGTERM:$?"
# The internal state depends on whether shell manages to see the death of $bg before entering "wait -n":
# will the job be already "dead and waited-for"? In the latter case, the correctness is harder to achieve.
sleep 0.1
echo "Test: wait -n exit code for sigkilled (and possibly already waited-for) pipe"
wait -n
echo "wait -n #1: $? (should be 143 = 128+SIGTERM)"
echo "Test: wait -n exits 127 if nothing to wait for"
wait -n
echo "wait -n #1: $? (should be 127)"
@@ -0,0 +1,3 @@
4:4
8:8
127:127
@@ -0,0 +1,9 @@
#(sleep 0.2;exit 2) &
#^^^ bash will report jobs in order of them exiting, we do the reverse order. fix?
(sleep 0.4;exit 4) &
(sleep 0.8;exit 8) &
sleep 0.6
#wait -n; echo 2:$?
wait -n; echo 4:$?
wait -n; echo 8:$?
wait -n; echo 127:$?
@@ -0,0 +1,4 @@
This should happen before wait -n #1 returns
1:1
3:3
Ok:0
@@ -0,0 +1,7 @@
(sleep 3;exit 3) &
(sleep 2;echo 'This should happen before wait -n #1 returns' >&2;exit 2) | (sleep 1;exit 1) &
# the exit code of pipe is the last member's exitcode: 1
wait -n; echo 1:$?
# next wait -n should wait for the remaining job
wait -n; echo 3:$?
echo Ok:$?
@@ -0,0 +1,7 @@
wait -n $p1 $p2: 42 (should be 42)
p1 active: 0 (should be 0)
p2 active: 1 (should be 1)
wait $p1: 41 (should be 41)
wait -n $p1: 41 (should be 41)
wait -n: 43 (should be 43)
wait -n: 127 (should be 127)
Loaded 100 of 182 files, more files were not shown because too many files have changed in this diff. Show more