Compare commits

...
269 Commits
Author SHA1 Message Date
Denys Vlasenko bd75474639 Bump version to 1.31.1
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-10-25 10:45:05 +02:00
Denys Vlasenko ebc1c38a92 dpkg-deb: work around bogus error message when working with XZ compressed packages
function                                             old     new   delta
unpack_xz_stream                                    2309    2317      +8
bb_full_fd_action                                    464     472      +8

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-10-21 16:54:40 +02:00
Denys Vlasenko be11940911 telnet: fix uninitialized variable bug
function                                             old     new   delta
telnet_main                                         1236    1238      +2

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-10-21 16:54:40 +02:00
Denys Vlasenko 49a8839638 ash: fix BASE##nn bashism for bases 36..64
function                                             old     new   delta
evaluate_string                                      876     932     +56

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-10-21 16:54:40 +02:00
Denys Vlasenko 3004510fdc ash: fix BASE##nn bashism to accept letter 'digits' for bases > 9
function                                             old     new   delta
evaluate_string                                      873     876      +3

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-10-21 16:54:40 +02:00
David Demelier d6a8784f27 wget: increase redirections limit
Some hosting services like sourceforge perform a lot of relocations
before actually serving the file. Example of current limitation:

    busybox wget http://sourceforge.net/projects/fluxbox/files/fluxbox/1.3.7/fluxbox-1.3.7.tar.xz
    Connecting to sourceforge.net (216.105.38.13:80)
    Connecting to sourceforge.net (216.105.38.13:443)
    Connecting to sourceforge.net (216.105.38.13:443)
    Connecting to sourceforge.net (216.105.38.13:443)
    Connecting to downloads.sourceforge.net (216.105.38.13:443)
    wget: too many redirections

Signed-off-by: David Demelier <markand@malikania.fr>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-10-21 16:54:40 +02:00
Denys Vlasenko a1c7a9e976 hush: fix "set -o INVALID" affecting -e flag state
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-10-21 16:54:40 +02:00
Brian Foley 2f3352682e dc: Parse error & fix out of bounds read in xc_program_printString
function                                             old     new   delta
xc_program_print                                     712     735     +23

Signed-off-by: Brian Foley <bpfoley@google.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-10-21 16:54:40 +02:00
Brian Foley 50ba92128b dc: Fix segfault when executing strings generated using asciify
function                                             old     new   delta
zxc_vm_process                                      6884    6891      +7

Signed-off-by: Brian Foley <bpfoley@google.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-10-21 16:54:40 +02:00
Brian Foley 4699b93244 dc: execute shouldn't pop if stack head is not a string
This matches the behaviour of both GNU dc (as specified in
its man page), and BSD dc (where stack_popstring() pops
only if the head is a string.)

Add a couple of tests to verify this behavior.

function                                             old     new   delta
zxc_vm_process                                      6882    6884      +2

Signed-off-by: Brian Foley <bpfoley@google.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-10-21 16:54:40 +02:00
Denys Vlasenko 244c0ebb4f ash: fix set -o to not show "nameless" options
Patch by Martijn Dekker <martijn@inlv.org>

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-10-21 16:54:40 +02:00
Ron Yorston c88d3ec458 ash: only catch unexpected exceptions in PS1 expansion
Commit d1a2fa2a4 (ash: catch error in arithmetic expansion in PS1)
catches all exceptions raised by expandarg().  Some exceptions, such as
the EXEXIT raised when command expansion is used, are expected:

   export PS1='$(echo "$ ")'

These should be processed normally or the shell hangs at the prompt.

function                                             old     new   delta
expandstr                                            344     353      +9
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 1/0 up/down: 9/0)                 Total: 9 bytes

Signed-off-by: Ron Yorston <rmy@pobox.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-10-21 16:54:40 +02:00
Denys Vlasenko 0f1369f0c5 Bump version to 1.31.0
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-06-10 11:53:46 +02:00
Denys Vlasenko 3b69ba799f mount,losetup: use /dev/loop-control is it exists
function                                             old     new   delta
get_free_loop                                          -      58     +58
set_loop                                             597     649     +52
losetup_main                                         482     476      -6
------------------------------------------------------------------------------
(add/remove: 1/0 grow/shrink: 1/1 up/down: 110/-6)            Total: 104 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-06-09 23:20:49 +02:00
Aitor Esteve Alvarado 7b6d4f50c9 start-stop-daemon: change priority before dropping privileges
Currently start-stop-daemon fails when using both the -c option (set uid)
and -N option (set niceness/priority) as it first drops privileges and then
tries to increase the priority. This patch changes the order of execution.

Signed-off-by: Aitor Esteve Alvarado <aesteve@singularaircraft.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-06-09 13:47:49 +02:00
Denys Vlasenko 894f0a3235 tftp: allow -lc and -cl options
function                                             old     new   delta
tftp_main                                            394     396      +2

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-06-09 12:41:17 +02:00
Denys Vlasenko 94ce1c0ebb tftpd: revert erroneous change
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-06-09 11:32:23 +02:00
Denys Vlasenko 3b8025f132 tftp: optional tftp-hpa compat
function                                             old     new   delta
tftp_main                                            276     394    +118

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-06-09 11:12:02 +02:00
Denys Vlasenko 48eebc8d5c expand: add commented-out code to handle NULs
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-06-09 09:16:03 +02:00
Denys Vlasenko 92549250f3 expand,unexpand: drop broken test, add FIXME comment
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-06-08 13:04:44 +02:00
Denys Vlasenko 22cc92833f awk: fix testsuite
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-06-08 13:00:46 +02:00
Denys Vlasenko 04a0b7f080 bc: placate compiler warnings
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-06-08 12:58:16 +02:00
Denys Vlasenko fa182a355a vi: code shrink
function                                             old     new   delta
colon                                               2852    2846      -6

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-06-08 12:57:07 +02:00
Denys Vlasenko 7a4e55422a bc: placate compiler warnings
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-06-08 12:39:30 +02:00
Denys Vlasenko 3e463e1cfd brctl: placate compiler warnings
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-06-08 12:35:06 +02:00
Denys Vlasenko 023ae75fc6 blockdev: add usage comment, no code changes
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-06-08 08:57:11 +02:00
Denys Vlasenko 1230aec77a httpd: .js is "application/javascript", not "application/x-javascript"
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-06-07 12:32:30 +02:00
Denys Vlasenko a5c5dc6f0b passwd: do not set 0 as date of last password change, closes 11951
function                                             old     new   delta
update_passwd                                       1491    1505     +14

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-06-07 12:30:23 +02:00
Denys Vlasenko 5c317c0b8d httpd: add js to built in MIME types list
Firefox needs this to execute .js

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-06-07 09:32:03 +02:00
Vicente Jimenez Aguilar 09b25ecc51 httpd: add svg to built in MIME types list
Signed-off-by: Vicente Jimenez Aguilar <googuy@gmail.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-06-07 09:31:57 +02:00
Denys Vlasenko ed042010dc lpd: avoid SEGVing on immediate EOF from peer
Patch by Luís Marques <luismarques@lowrisc.org>

function                                             old     new   delta
lpd_main                                             749     757      +8

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-06-07 09:14:41 +02:00
Denys Vlasenko 45e3967c20 libbb: move netlink socket binding to the utility function
function                                             old     new   delta
create_and_bind_to_netlink                             -     134    +134
ifplugd_main                                        1117    1052     -65
uevent_main                                          399     306     -93
mdev_main                                            314     215     -99
------------------------------------------------------------------------------
(add/remove: 1/0 grow/shrink: 0/3 up/down: 134/-257)         Total: -123 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-06-03 14:16:52 +02:00
Jan Klötzke 498cec202a mdev: add support to run as daemon
Adds the -d option to run mdev in daemon mode handling hotplug events
from the kernel like udev. If the system generates many hotplug events
this mode of operation will consume less resources than registering
mdev as hotplug helper or using the uevent applet.

function                                             old     new   delta
daemon_loop                                            -     152    +152
initial_scan                                           -     127    +127
open_mdev_log                                          -      85     +85
mdev_main                                            255     314     +59
packed_usage                                       33284   33316     +32
process_action                                      1051     992     -59
------------------------------------------------------------------------------
(add/remove: 3/0 grow/shrink: 2/1 up/down: 455/-59)           Total: 396 bytes

Signed-off-by: Jan Klötzke <jan@kloetzke.net>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-06-03 13:24:49 +02:00
Jan Klötzke 728e53d388 mdev: use option parser helper
function                                             old     new   delta
process_action                                         -    1051   +1051
mdev_main                                           1324     255   -1069
------------------------------------------------------------------------------
(add/remove: 1/0 grow/shrink: 0/1 up/down: 1051/-1069)        Total: -18 bytes

Signed-off-by: Jan Klötzke <jan@kloetzke.net>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-06-03 13:00:47 +02:00
Jan Klötzke d04b726173 mdev: move action processing into separate functions
This purely moves code from main() to separate functions for better
extensibility.

Signed-off-by: Jan Klötzke <jan@kloetzke.net>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-06-03 12:55:30 +02:00
Denys Vlasenko f3634584d0 ash,hush: show 'c' in $- if run in "sh -c CMD"
function                                             old     new   delta
options                                              552     599     +47
expand_one_var                                      2375    2385     +10
optletters_optnames                                   60      64      +4
hush_main                                           1108    1111      +3
ash_main                                            1150    1152      +2
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 5/0 up/down: 66/0)               Total: 66 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-06-03 12:21:04 +02:00
Denys Vlasenko 897475ab02 ash: allocate line editing structure only if needed
function                                             old     new   delta
optschanged                                           91     128     +37
historycmd                                            13      17      +4
setcmd                                                80      78      -2
ash_main                                            1167    1150     -17
options                                              576     552     -24
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 2/3 up/down: 41/-43)             Total: -2 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-06-01 16:35:09 +02:00
Denys Vlasenko 6eb6e6a1e9 dhcp: downgrade "got raw socket fd" message to log3, make log2 default max
log3 messages are very much redundant

function                                             old     new   delta
change_listen_mode                                   322     302     -20

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-05-31 23:52:16 +02:00
Denys Vlasenko 65c34c52df dhcp: get rid of static data signal_pipe
function                                             old     new   delta
udhcp_sp_setup                                        65     110     +45
udhcp_sp_fd_set                                       60      59      -1
udhcpd_main                                         1442    1437      -5
udhcpc_main                                         2684    2679      -5
signal_pipe                                            8       -      -8
packed_usage                                       33292   33284      -8
------------------------------------------------------------------------------
(add/remove: 0/1 grow/shrink: 1/4 up/down: 45/-27)             Total: 18 bytes
   text	   data	    bss	    dec	    hex	filename
 952746	    481	   7296	 960523	  ea80b	busybox_old
 952768	    481	   7288	 960537	  ea819	busybox_unstripped

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-05-31 23:39:22 +02:00
Denys Vlasenko 91755cb16d udhcp: rename server_config to server_data
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-05-30 16:23:34 +02:00
Jack O'Sullivan 726cbb1be8 losetup: Add partition scanning option
Add -P option from util-linux losetup to scan for partitions.

function                                             old     new   delta
losetup_main                                         449     482     +33
packed_usage                                       33264   33292     +28
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 2/0 up/down: 61/0)               Total: 61 bytes

Signed-off-by: Jack O'Sullivan <jackos1998@gmail.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-05-30 16:22:52 +02:00
Denys Vlasenko bcb1fc3e6c udhcp: rename client_config to client_data, server_config to server_data
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-05-26 15:03:05 +02:00
Martin Lewis 818d9e02f2 udhcpc6: Fixed aliasing compilation error
Signed-off-by: Martin Lewis <martin.lewis.x84@gmail.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-05-26 14:24:32 +02:00
Denys Vlasenko 8b35f207bb shell: move all definitions of strto_arith_t() together
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-05-26 14:02:10 +02:00
Denys Vlasenko 9501bc7da5 ls: fix SEGV when --color is used and ENABLE_LS_COLOR=n
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-05-26 13:53:41 +02:00
Denys Vlasenko b2c123d484 testsuite: fix bunzip2.tests expectations
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-05-26 13:51:41 +02:00
Denys Vlasenko eda83c9e69 comment fix
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-05-26 13:46:49 +02:00
Denys Vlasenko cc71f79c1e libarchive: treat one "FIXME: avoid seek", take 2
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-05-26 13:43:06 +02:00
Denys Vlasenko a4ed2c45b9 dhcp: get rid of last global data
function                                             old     new   delta
udhcpc_main                                         2680    2684      +4
state                                                  1       -      -1
listen_mode                                            1       -      -1
sockfd                                                 4       -      -4
------------------------------------------------------------------------------
(add/remove: 0/3 grow/shrink: 1/0 up/down: 4/-6)               Total: -2 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-05-26 13:05:04 +02:00
Denys Vlasenko dff2bd733f libarchive: treat one "FIXME: avoid seek"
function                                             old     new   delta
xmalloc_read_with_initial_buf                          -     205    +205
setup_transformer_on_fd                              154     150      -4
xmalloc_open_zipped_read_close                       143     135      -8
xmalloc_read                                         201      10    -191
------------------------------------------------------------------------------
(add/remove: 1/0 grow/shrink: 0/3 up/down: 205/-203)            Total: 2 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-05-24 17:03:28 +02:00
Denys Vlasenko 309f5e3775 losetup: implement -c
function                                             old     new   delta
losetup_main                                         422     449     +27
packed_usage                                       33243   33264     +21
get_next_block                                      1677    1681      +4
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 3/0 up/down: 52/0)               Total: 52 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-05-23 16:11:42 +02:00
Denys Vlasenko 1115e40c88 dhcp: tweak comments, no code changes
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-05-23 15:24:03 +02:00
Denys Vlasenko 58d998d2f9 bunzip2: the correct condition is "n < groupCount", not "n <= groupCount". Closes 11896
function                                             old     new   delta
get_next_block                                      1677    1681      +4

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-05-23 14:54:13 +02:00
Denys Vlasenko 028c5aa18b ip: use rtnl_send_check() on flush commands, closes 6962
function                                             old     new   delta
rtnl_send_check                                        -     160    +160
xrtnl_wilddump_request                                64      66      +2
ipneigh_list_or_flush                                714     706      -8
rtnl_send                                             69       -     -69
------------------------------------------------------------------------------
(add/remove: 1/1 grow/shrink: 1/1 up/down: 162/-77)            Total: 85 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-05-22 13:54:46 +02:00
Denys Vlasenko 84fc645605 *: slap on a few ALIGN1/2s where appropriate
The result of looking at "grep -F -B2 '*fill*' busybox_unstripped.map"

   text	   data	    bss	    dec	    hex	filename
 952537	    485	   7296	 960318	  ea73e	busybox_old
 952527	    485	   7296	 960308	  ea734	busybox_unstripped

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-05-21 17:29:24 +02:00
Denys Vlasenko 831844c139 udhcpd: fix printing of static leases
function                                             old     new   delta
read_staticlease                                     299     282     -17

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-05-21 16:06:34 +02:00
Denys Vlasenko d8740b265a hush: show 's' in $-
function                                             old     new   delta
expand_one_var                                      2362    2375     +13
hush_main                                           1104    1108      +4
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 2/0 up/down: 17/0)               Total: 17 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-05-19 19:11:21 +02:00
Denys Vlasenko 76a4e8361a hush: allocate line edit buffer only for interactive shell
function                                             old     new   delta
builtin_history                                       16      20      +4

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-05-19 18:24:52 +02:00
Denys Vlasenko 9edd268bad shell: implement optional "BASE#nnnn" numeric literals
function                                             old     new   delta
evaluate_string                                      729     851    +122

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-05-19 17:23:31 +02:00
Denys Vlasenko 30a4c32a4d hush: remove test for "echo ${-}" errorring out - now it works
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-05-19 16:35:56 +02:00
Denys Vlasenko ef8985c688 hush: implement $-, set default PATH if it is not set on startup
function                                             old     new   delta
expand_one_var                                      2311    2362     +51
hush_main                                           1075    1104     +29
parse_dollar                                         790     791      +1
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 3/0 up/down: 81/0)               Total: 81 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-05-19 16:29:09 +02:00
Denys Vlasenko 0c36019369 hush: set default PS1/2 only if we interactive
"env - hush SCRIPT" invocation (that is, with empty environment)
should not show PS1/2 in "set" output.

function                                             old     new   delta
hush_main                                           1070    1075      +5

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-05-19 15:39:32 +02:00
Denys Vlasenko 08fb82c80c hush: handle LINENO the same way as RANDOM: variable is "ephemeral"
"env - hush" invocation (that is, with empty environment)
should not show LINENO in "set" output.

function                                             old     new   delta
get_local_var_value                                  263     294     +31
hush_main                                           1105    1070     -35
handle_changed_special_names                          79      38     -41
run_pipe                                            1834    1765     -69
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 1/3 up/down: 31/-145)          Total: -114 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-05-19 15:39:32 +02:00
Khem Raj ee9e5f92b6 networking: cc is not a register
gcc accepts

  __asm__ ( "" : : : "%cc");

but cc is not a real register and clang does not like it.

networking/tls_pstm_montgomery_reduce.c:385:4: error: unknown register name '%cc' in asm
|                         INNERMUL;
|                         ^

The % syntax nominally goes before a register, in this case cc,
like "memory" isn't a true register it's just a way of specifying that
the condition code registers for the target are clobbered

Signed-off-by: Khem Raj <raj.khem@gmail.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-05-17 22:56:47 +02:00
Denys Vlasenko 4ebcdf7396 hush: remove code to track PS1/2 values dynamically - it's too much work
Assignments / exports / unsets of variables are far more frequent than
prompt printing, and if we show prompt, we are likely to be limited by
user typing speed - do not optimize for that scenario.
Just re-query $PS1 / $PS2 values when need to show the prompt.

function                                             old     new   delta
fgetc_interactive                                    236     259     +23
set_vars_and_save_old                                150     147      -3
pseudo_exec_argv                                     597     594      -3
hush_main                                           1110    1105      -5
enter_var_nest_level                                  38      32      -6
builtin_local                                         56      50      -6
run_pipe                                            1857    1834     -23
leave_var_nest_level                                 127      98     -29
handle_changed_special_names                         111      79     -32
cmdedit_update_prompt                                 57       -     -57
------------------------------------------------------------------------------
(add/remove: 0/1 grow/shrink: 1/8 up/down: 23/-164)          Total: -141 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-05-16 15:39:19 +02:00
Denys Vlasenko a51eec0b5a typo fix in comment
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-05-16 14:31:58 +02:00
Denys Vlasenko 0ee0b658b3 hush: small speedup in handle_changed_special_names()
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-05-16 11:32:26 +02:00
Denys Vlasenko 25393fb55e udhcpd: code shrink
function                                             old     new   delta
send_packet_verbose                                    -      35     +35
send_offer                                           443     423     -20
send_ACK                                             152     131     -21
------------------------------------------------------------------------------
(add/remove: 1/0 grow/shrink: 0/2 up/down: 35/-41)             Total: -6 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-05-16 11:27:28 +02:00
Denys Vlasenko a840884531 udhcpd: support per-client hostnames in static leases
function                                             old     new   delta
read_staticlease                                     222     299     +77
add_server_options                                    92     154     +62
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 2/0 up/down: 139/0)             Total: 139 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-05-16 11:18:49 +02:00
Denys Vlasenko 9bf6780c28 shell: add TODO comment about BASE#nnn literals
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-05-16 09:56:45 +02:00
Denys Vlasenko 1113961dde dc: make 4 % 0 emit error messgaes and set result to 0
function                                             old     new   delta
mod                                                  105     136     +31

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-05-16 09:40:36 +02:00
Denys Vlasenko abe248b208 udhcpc6: unbreak
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-05-15 14:20:32 +02:00
Denys Vlasenko 9e0adb9b09 hush: fix quoted "${notexist-}" expansion to not disappear
function                                             old     new   delta
expand_one_var                                      2296    2311     +15

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-05-15 13:39:19 +02:00
Denys Vlasenko 8402969d48 udhcpd: code shrink - do not fetch requested IP twice
function                                             old     new   delta
send_offer                                           444     443      -1
udhcpd_main                                         1454    1442     -12
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 0/2 up/down: 0/-13)             Total: -13 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-05-15 13:08:48 +02:00
Denys Vlasenko 63d765e666 shells: add tests for backslashes in export VAR=VAL
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-05-14 19:15:20 +02:00
Denys Vlasenko d8bd7012a3 hush: fix "export PS1=xyz" and "local PS1=xyz" messing up prompt
function                                             old     new   delta
helper_export_local                                  215     253     +38
leave_var_nest_level                                 107     127     +20
run_pipe                                            1840    1857     +17
handle_changed_special_names                         101     105      +4
shell_builtin_read                                  1399    1398      -1
done_word                                            767     766      -1
parse_stream                                        2249    2245      -4
set_local_var                                        437     430      -7
is_well_formed_var_name                               66       -     -66
------------------------------------------------------------------------------
(add/remove: 0/1 grow/shrink: 4/4 up/down: 79/-79)              Total: 0 bytes
   text	   data	    bss	    dec	    hex	filename
 952376	    485	   7296	 960157	  ea69d	busybox_old
 952400	    485	   7296	 960181	  ea6b5	busybox_unstripped

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-05-14 18:56:04 +02:00
Denys Vlasenko 875ce094cf dd: fix handling of short result of full_write(), closes 11711
$ dd bs=1G <sda1 of=/dev/sda1
dd: error writing '/dev/sda1': No space left on device
1+0 records in
0+0 records out
999292928 bytes (953.0MB) copied, 0.784617 seconds, 1.2GB/s

function                                             old     new   delta
write_and_stats                                       99     102      +3

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-05-14 17:49:14 +02:00
Denys Vlasenko 8c317f03f6 style fix, no code changes
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-05-14 17:26:47 +02:00
Denys Vlasenko 0545bfa841 sed: fix /regex/,+N match triggering only once, closes 11871
function                                             old     new   delta
process_files                                       2235    2246     +11

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-05-13 16:30:39 +02:00
Denys Vlasenko 15021f393d udhcpd: code shrink
function                                             old     new   delta
is_nip_reserved_as_static                              -      28     +28
get_static_nip_by_mac                                 43      47      +4
udhcpd_main                                         1459    1454      -5
send_offer                                           449     444      -5
read_leases                                          309     299     -10
is_nip_reserved                                       20       -     -20
packed_usage                                       33283   33243     -40
------------------------------------------------------------------------------
(add/remove: 1/1 grow/shrink: 1/4 up/down: 32/-80)            Total: -48 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-05-10 15:55:12 +02:00
John L. Hammond 94f607a904 ln: correct 'ln -T' usage message
Signed-off-by: John L. Hammond <jhammond@indeed.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-05-09 16:29:29 +02:00
Denys Vlasenko 89023b167f dc: code shrink
function                                             old     new   delta
check_under                                           20      21      +1
print_no_pop                                          32      27      -5
pop                                                   24      18      -6
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 1/2 up/down: 1/-11)             Total: -10 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-05-09 15:58:46 +02:00
Denys Vlasenko 3106784e65 ps: ensure fields are separated by at least one space, closes 11826
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-05-03 09:49:56 +02:00
Denys Vlasenko b052dbea54 login: remove extra IF(), no code changes
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-05-02 17:13:20 +02:00
James Byrne 253c4e787a Optionally re-introduce bb_info_msg()
Between Busybox 1.24.2 and 1.25.0 the bb_info_msg() function was
eliminated and calls to it changed to be bb_error_msg(). The downside of
this is that daemons now log all messages to syslog at the LOG_ERR level
which makes it hard to filter errors from informational messages.

This change optionally re-introduces bb_info_msg(), controlled by a new
option FEATURE_SYSLOG_INFO, restores all the calls to bb_info_msg() that
were removed (only in applets that set logmode to LOGMODE_SYSLOG or
LOGMODE_BOTH), and also changes informational messages in ifplugd and
ntpd.

The code size change of this is as follows (using 'defconfig' on x86_64
with gcc 7.3.0-27ubuntu1~18.04)

function                                             old     new   delta
bb_info_msg                                            -     182    +182
bb_vinfo_msg                                           -      27     +27
static.log7                                          194     198      +4
log8                                                 190     191      +1
log5                                                 190     191      +1
crondlog                                              45       -     -45
------------------------------------------------------------------------------
(add/remove: 2/1 grow/shrink: 3/0 up/down: 215/-45)           Total: 170 bytes

If you don't care about everything being logged at LOG_ERR level
then when FEATURE_SYSLOG_INFO is disabled Busybox actually gets smaller:

function                                             old     new   delta
static.log7                                          194     200      +6
log8                                                 190     193      +3
log5                                                 190     193      +3
syslog_level                                           1       -      -1
bb_verror_msg                                        583     581      -2
crondlog                                              45       -     -45
------------------------------------------------------------------------------
(add/remove: 0/2 grow/shrink: 3/1 up/down: 12/-48)            Total: -36 bytes

Signed-off-by: James Byrne <james.byrne@origamienergy.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-04-30 10:51:27 +02:00
Denys Vlasenko f3a064f495 libbbb: find_mount_point() too eager to stat mounted devices
None of the below "devices" (first word on the line) are real.

sysfs /sys sysfs rw,nosuid,nodev,noexec,relatime 0 0
proc /proc proc rw,nosuid,nodev,noexec,relatime 0 0
devtmpfs /dev devtmpfs rw,nosuid,size=7917900k,nr_inodes=1979475,mode=755 0 0
tmpfs /dev/shm tmpfs rw,nosuid,nodev 0 0
devpts /dev/pts devpts rw,nosuid,noexec,relatime,gid=5,mode=620,ptmxmode=000 0 0
tmpfs /run tmpfs rw,nosuid,nodev,mode=755 0 0
pstore /sys/fs/pstore pstore rw,nosuid,nodev,noexec,relatime 0 0
configfs /sys/kernel/config configfs rw,relatime 0 0
tmpfs /tmp tmpfs rw,relatime 0 0

function                                             old     new   delta
find_mount_point                                     297     302      +5

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-04-29 17:59:08 +02:00
Denys Vlasenko fa8878bf1f start-stop-daemon: do try to close fds > 2
sh -c 'exec 3>&1; exec start-stop-daemon -S -b -x /bin/sleep -- 123'

now closes fd 3.

function                                             old     new   delta
bb_daemonize_or_rexec                                183     192      +9
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 1/0 up/down: 9/0)                 Total: 9 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-04-29 14:24:07 +02:00
Denys Vlasenko 13f4204561 ip: fix comment placement
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-04-29 00:34:07 +02:00
Denys Vlasenko 405095d84b ifupdown: close memory leak
function                                             old     new   delta
execute_all                                           80      91     +11

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-04-28 17:55:27 +02:00
Ron Yorston 7b93e317c1 vi: enable 'dG' command. Closes 11801
The 'G' command was omitted from the list of commands that change or
delete whole lines.  Add it in the appropriate places so the 'dG',
'cG' and 'yG' commands work, including in cases where an explicit
line number has been supplied.

function                                             old     new   delta
find_range                                           534     596     +62
.rodata                                           175166  175167      +1
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 2/0 up/down: 63/0)               Total: 63 bytes

Reported-by: David Kelly <david.kelly@liberica.ch>
Signed-off-by: Ron Yorston <rmy@pobox.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-04-28 17:16:46 +02:00
Ron Yorston 4b49422a08 vi: fix changes to word at end of line. Closes 11796
As reported in bug 11796 BusyBox vi incorrectly handles changes
to a word at the end of a line.  If the following line starts
with whitespace changing or deleting the last word of a line
with the 'cw' or 'dw' commands causes the lines to be joined.

This happens because the range for the change returned by
find_range() covers all whitespace after the word, including
newlines.  The problem can be fixed by setting 'ml' to zero
to indicate to yank_delete() that processing should stop at
the end of the current line.

However, this results in a new problem.  'dw' correctly deletes
all whitespace following the word but so does 'cw', which should
preserve the trailing whitespace.  To fix this the code to omit
whitespace from the change is modified to include all whitespace
not just blanks.

function                                             old     new   delta
do_cmd                                              5034    5069     +35
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 1/0 up/down: 35/0)               Total: 35 bytes

Reported-by: David Kelly <david.kelly@liberica.ch>
Signed-off-by: Ron Yorston <rmy@pobox.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-04-28 17:16:46 +02:00
Denys Vlasenko 93f0b39a07 ash,hush: ulimit: add -i RLIMIT_SIGPENDING, -q RLIMIT_MSGQUEUE
function                                             old     new   delta
limits_tbl                                           104     120     +16
ulimit_opt_string                                     44      50      +6
limit_chars                                           14      16      +2
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 3/0 up/down: 24/0)               Total: 24 bytes
   text	   data	    bss	    dec	    hex	filename
 981996	    485	   7296	 989777	  f1a51	busybox_old
 982065	    485	   7296	 989846	  f1a96	busybox_unstripped

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-04-28 11:25:11 +02:00
Denys Vlasenko 57e1b0ad5e ash,hush: bash compat for ulimit: reorder to match
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-04-28 11:20:09 +02:00
Denys Vlasenko a92a9601f8 ash,hush: bash compat for ulimit: -w => -x, -p => -u
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-04-27 21:24:33 +02:00
Denys Vlasenko a4d76ea137 ash,hush: fix ulimit to be more bash-compat, closes 11791
function                                             old     new   delta
shell_builtin_ulimit                                 486     651    +165
limit_chars                                            -      14     +14
------------------------------------------------------------------------------
(add/remove: 1/0 grow/shrink: 1/0 up/down: 179/0)             Total: 179 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-04-27 21:01:35 +02:00
Alexander Vickberg 100fa20c68 start-stop-daemon: Fix -x is not required for -K
Commit 088fec36fe made -x required for
all. However it isn't for -K.

function                                             old     new   delta
start_stop_daemon_main                              1084    1105     +21
packed_usage                                       33343   33326     -17
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 1/1 up/down: 21/-17)              Total: 4 bytes

Signed-off-by: Alexander Vickberg <wickbergster@gmail.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-04-27 15:43:43 +02:00
Denys Vlasenko 1e9a4f56f5 examples/var_service: use "exec sleep 5" instead of "{ sleep 5; exit; }"
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-04-21 14:30:19 +02:00
Denys Vlasenko e49a572b52 httpd: do disable header reading timeout even if proxying
function                                             old     new   delta
handle_incoming_and_exit                            2362    2369      +7

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-04-19 14:24:57 +02:00
Denys Vlasenko 1c356948f1 httpd: use full size of iobuf[] when piping CGI data
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-04-19 14:19:41 +02:00
Denys Vlasenko af6012a1a7 httpd: do not set alarm() timeout if we read cached header
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-04-19 14:03:37 +02:00
Denys Vlasenko bca888a73e httpd: deindent code block, no code changes
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-04-19 14:02:51 +02:00
Denys Vlasenko ad29ba73ee httpd: require "HTTP/xyz" at the end of request line
function                                             old     new   delta
handle_incoming_and_exit                            2379    2362     -17
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 0/1 up/down: 0/-17)             Total: -17 bytes
   text	   data	    bss	    dec	    hex	filename
 981787	    485	   7296	 989568	  f1980	busybox_old
 981779	    485	   7296	 989560	  f1978	busybox_unstripped

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-04-19 13:59:58 +02:00
Ron Yorston d1a2fa2a4e ash: catch error in arithmetic expansion in PS1
Setting PS1 to:

   PS1='$((123+))'

causes the shell to enter an infinite error loop:

   sh: arithmetic syntax error

Catch any exception raised by expandarg() in expandstr() and allow
processing to continue.

function                                             old     new   delta
expandstr                                            262     344     +82
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 1/0 up/down: 82/0)               Total: 82 bytes

Signed-off-by: Ron Yorston <rmy@pobox.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-04-19 13:21:34 +02:00
Ron Yorston 48645b8350 ash: prevent error in backquotes in PS1 from exiting shell
Setting PS1 to:

   PS1='`xxx(`'

causes the shell to terminate with the error:

   sh: syntax error: unexpected end of file (expecting ")")

This happens because old-style backquotes require the input to be reread
and thus call setinputstring() a second time.  Prevent the problem by
unwinding all recently opened files in expandstr().

function                                             old     new   delta
unwindfiles                                            -      22     +22
expandstr                                            247     262     +15
forkchild                                            631     625      -6
evalcommand                                         1694    1685      -9
ash_main                                            1346    1336     -10
------------------------------------------------------------------------------
(add/remove: 1/0 grow/shrink: 1/3 up/down: 37/-25)             Total: 12 bytes

Signed-off-by: Ron Yorston <rmy@pobox.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-04-19 13:21:34 +02:00
Chen Qi 32c8ce4def dc.tests: fix two test case to also depend on DC_BIG
Signed-off-by: Chen Qi <Qi.Chen@windriver.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-04-19 12:30:11 +02:00
Alexander Vickberg 049670fbbe httpd: pass authorization header to CGI if not Basic
Pass the Authorization header to CGI if not of type Basic. This will
make it possible for CGI to verify authorization headers of type
Bearer <token>.

function                                             old     new   delta
handle_incoming_and_exit                            2370    2379      +9

Signed-off-by: Alexander Vickberg <wickbergster@gmail.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-04-18 10:06:39 +02:00
Alexander Vickberg 210b52476c httpd: When sending gzipped content use content-length header
Today for gzipped content httpd is using a header with name
Transfer-Length. However I can't find a header with that name in the
standards. Instead use Content-Length.

function                                             old     new   delta
.rodata                                           157940  157936      -4
send_headers                                         980     939     -41
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 0/2 up/down: 0/-45)             Total: -45 bytes

Signed-off-by: Alexander Vickberg <wickbergster@gmail.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-04-17 11:34:49 +02:00
Ron Yorston 1d37186fe2 ash: add bash-compatible EPOCH variables
Bash 5.0 added the dynamic variable EPOCHSECONDS and EPOCHREALTIME
which return the number of seconds since the Unix Epoch as an
integer or float.  These are useful for logging or tracing.

function                                             old     new   delta
change_epoch                                           -      78     +78
.rodata                                           175167  175235     +68
varinit_data                                         264     312     +48
change_seconds                                         -      24     +24
change_realtime                                        -      24     +24
------------------------------------------------------------------------------
(add/remove: 3/0 grow/shrink: 2/0 up/down: 242/0)             Total: 242 bytes
   text	   data	    bss	    dec	    hex	filename
 938508	   4203	   1888	 944599	  e69d7	busybox_old
 938702	   4203	   1888	 944793	  e6a99	busybox_unstripped

v2: Cast tv_sec and tv_usec to unsigned quantities.
    Add brackets to macros.

Signed-off-by: Ron Yorston <rmy@pobox.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-04-16 18:29:52 +02:00
Ron Yorston d96c69d876 ash: an unset dynamic variable should not be dynamic
Commit b28d4c346 (ash: [VAR] Move unsetvar functionality into setvareq)
dropped the code that caused dynamic variables to lose their special
properties when unset.  Add it back again.

function                                             old     new   delta
setvareq                                             346     360     +14
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 1/0 up/down: 14/0)               Total: 14 bytes

Signed-off-by: Ron Yorston <rmy@pobox.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-04-16 18:29:52 +02:00
Ron Yorston a81700bc08 hush: add bash-compatible EPOCH variables
Bash 5.0 added the dynamic variable EPOCHSECONDS and EPOCHREALTIME
which return the number of seconds since the Unix Epoch as an
integer or float.  These are useful for logging or tracing.

function                                             old     new   delta
get_local_var_value                                  207     302     +95
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 1/0 up/down: 95/0)               Total: 95 bytes
   text	   data	    bss	    dec	    hex	filename
 938702	   4203	   1888	 944793	  e6a99	busybox_old
 938797	   4203	   1888	 944888	  e6af8	busybox_unstripped

Signed-off-by: Ron Yorston <rmy@pobox.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-04-16 18:29:52 +02:00
Denys Vlasenko 2efa726b22 httpd: extract query string only after proxying check
function                                             old     new   delta
handle_incoming_and_exit                            2398    2370     -28

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-04-16 13:35:56 +02:00
Denys Vlasenko 62ba9e5ac3 httpd: make rmt_ip variable local
function                                             old     new   delta
handle_incoming_and_exit                            2385    2398     +13
if_ip_denied_send_HTTP_FORBIDDEN_and_exit             51      54      +3
get_line                                             110     106      -4
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 2/1 up/down: 16/-4)              Total: 12 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-04-16 13:18:12 +02:00
Denys Vlasenko 44f5b6a1cb httpd: check denied IPs even before reading 1st query line
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-04-16 12:59:20 +02:00
Denys Vlasenko c69f648457 httpd: do not decode URL and headers if proxying - send all verbatim
function                                             old     new   delta
handle_incoming_and_exit                            2566    2385    -181

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-04-16 12:45:26 +02:00
Denys Vlasenko cf695976c7 httpd: remove duplicate "decode URL escape sequences" code
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-04-16 11:58:28 +02:00
Denys Vlasenko fba665a888 httpd: put all headers into environment as HTTP_UPPERCASED_HEADER=val
Set up environment variables before running the CGI script.
The variables will be named HTTP_<filtered_name> where the <filtered_name>
is the header name capitalized and all characters not matching
[a-z] | [A-Z] | [0-9] replaced with '_'.

function                                             old     new   delta
http_response                                         80      88      +8
http_response_type                                    20      22      +2
send_headers                                         718     715      -3
parse_conf                                          1481    1478      -3
get_line                                             128     110     -18
cgi_io_loop_and_exit                                 599     569     -30
send_cgi_and_exit                                    882     738    -144
handle_incoming_and_exit                            2793    2592    -201
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 2/6 up/down: 10/-399)          Total: -389 bytes
   text	   data	    bss	    dec	    hex	filename
 982178	    485	   7296	 989959	  f1b07	busybox_old
 981675	    485	   7296	 989456	  f1910	busybox_unstripped

Signed-off-by: Alexander Vickberg <wickbergster@gmail.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-04-16 11:37:02 +02:00
Denys Vlasenko d0ae4103dd httpd: fix handling of EOF in get_line()
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-04-16 11:07:37 +02:00
Denys Vlasenko ff36bec49b httpd: add missing {}
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-04-16 10:14:50 +02:00
Denys Vlasenko bae8f7eaf2 httpd: do not percent-decode URI if proxying
The proxying is documented as follows:

P:/url:[http://]hostname[:port]/new/path

Howeverm urlcopy is not a true copy anymore when it is fdprint'ed
to proxy_fd, this is because percent_decode_in_place() is called
after the copy is created.

This breaks reverse proxying all URIs containing percent
encoded spaces, e.g. - because a decoded URI will be printed out
to proxy_fd instead of the original.

The fix keeps the logic in place to canonicalize the uri first,
before reverse proxying (one could argue that the uri
should be proxied completely unaltered, except for the prefix
rewrite).

function                                             old     new   delta
handle_incoming_and_exit                            2752    2792     +40

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-04-16 10:07:33 +02:00
Denys Vlasenko 02d650e159 httpd: fix proxy headers passing - full_write() instead of write()
function                                             old     new   delta
handle_incoming_and_exit                            2763    2752     -11

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-04-14 20:46:57 +02:00
Denys Vlasenko 51792e126b httpd: if remote IP is denied, send FORBIDDEN reply earlier
While at it, fix sighup_handler to not clobber errno.

function                                             old     new   delta
send_HTTP_FORBIDDEN_and_exit_if_denied_ip              -      47     +47
sighup_handler                                        15      30     +15
handle_incoming_and_exit                            2791    2763     -28
checkPermIP                                           48       -     -48
------------------------------------------------------------------------------
(add/remove: 1/1 grow/shrink: 1/1 up/down: 62/-76)            Total: -14 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-04-14 19:57:13 +02:00
Denys Vlasenko 60bf77f7e7 udhcpc6: code shrink
function                                             old     new   delta
d6_read_interface                                    593     582     -11

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-04-14 17:01:10 +02:00
Denys Vlasenko 0d75e8b797 udhcpc6: add a few comments, no code changes.
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-04-13 19:43:15 +02:00
Denys Vlasenko cc45cbcca4 udhcpc6: make it enabled in defconfig
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-04-13 17:32:40 +02:00
Rolf Eike Beer 7180d9ed86 examples/udhcp/simple.script: fix resolv.conf update if it is a dangling symlink
If /etc/resolv.conf is a symlink to a tmpfs and the actual file does not
already exist, "readlink -f" will not detect it as symlink. Explicitely check
for that condition before and touch the file, making the other code work as
intended.

Signed-off-by: Rolf Eike Beer <eb@emlix.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-04-13 16:58:00 +02:00
Antoine Girard-Vallée 0e7bd69bb5 udhcp: add 100 and 101 dhcp options for ipv4
Support for the IEEE timezone string and timezone database strings (100
and 101 options respectively) is added for ipv4, conforming to RFC-4833.

The two options are passed to hook scripts in the variables tzstr and
tzdbstr.

function                                             old     new   delta
dhcp_option_strings                                  280     294     +14
dhcp_optflags                                         76      80      +4
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 2/0 up/down: 18/0)               Total: 18 bytes

Signed-off-by: Antoine Girard-Vallée <antoine.girard-vallee@savoirfairelinux.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-04-13 16:27:26 +02:00
Denys Vlasenko 2945822f86 brctl: add TODO: "showmacs BR"
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-04-13 15:48:31 +02:00
Denys Vlasenko 9435608804 brctl: simplify str_to_jiffies()
function                                             old     new   delta
write_uint                                             -      96     +96
brctl_main                                           721     678     -43
write_ulong                                           96       -     -96
------------------------------------------------------------------------------
(add/remove: 1/1 grow/shrink: 0/1 up/down: 96/-139)           Total: -43 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-04-13 14:17:55 +02:00
Denys Vlasenko dc1b2d4356 brctl: convert remaining commands to work via /sys
function                                             old     new   delta
write_ulong                                            -      96     +96
show_bridge                                          310     338     +28
static.ops                                             3       -      -3
arm_ioctl                                             20       -     -20
packed_usage                                       33344   33315     -29
brctl_main                                           885     721    -164
------------------------------------------------------------------------------
(add/remove: 1/2 grow/shrink: 1/2 up/down: 124/-216)          Total: -92 bytes
   text	   data	    bss	    dec	    hex	filename
 982112	    485	   7296	 989893	  f1ac5	busybox_old
 982157	    485	   7296	 989938	  f1af2	busybox_unstripped

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-04-13 13:58:06 +02:00
Denys Vlasenko c5150e9ce7 brctl: make "show" command retrieve data from /sys
ioctl interface is obsolete and has no 32/64 compat shim,
making "brctl show" fail for 32-bit userspace and 64-bit kernel.

function                                             old     new   delta
show_bridge                                            -     310    +310
read_file                                              -      64     +64
if_indextoname                                       117       -    -117
brctl_main                                          1183     885    -298
------------------------------------------------------------------------------
(add/remove: 2/1 grow/shrink: 0/1 up/down: 374/-415)          Total: -41 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-04-12 18:52:31 +02:00
Ron Yorston e2026381be stat: reduce storage for human-readable filesystem names
function                                             old     new   delta
static.humanname                                       -     236    +236
static.fstype                                          -     140    +140
print_statfs                                         339     341      +2
static.humantypes                                    288       -    -288
------------------------------------------------------------------------------
(add/remove: 2/1 grow/shrink: 1/0 up/down: 378/-288)           Total: 90 bytes
   text	   data	    bss	    dec	    hex	filename
 982183	    485	   7296	 989964	  f1b0c	busybox_old
 982152	    485	   7296	 989933	  f1aed	busybox_unstripped

Signed-off-by: Ron Yorston <rmy@pobox.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-04-12 12:00:38 +02:00
Bernhard Reutner-Fischer c6c19c31c1 ipaddress: remove unused variable no_link
ipaddress.c: In function ‘ipaddr_list_or_flush’:
ipaddress.c:427:6: warning: variable ‘no_link’ set but not used [-Wunused-but-set-variable]

Signed-off-by: Bernhard Reutner-Fischer <rep.dot.nop@gmail.com>
2019-04-07 18:09:37 +02:00
Denys Vlasenko 1e474d3d93 service examples: if iface do not exist, retry upping it
I've had a case of a machine where eth0 was appearing a bit later
after the boot, and appearing _downed_. ifplugd then fails to detect
"link up". Thus, depending on how service startup
("ip link set dev eth0 up") races with driver initialization,
ethernet randomly fails to initialize on boot.

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-04-05 18:41:48 +02:00
Denys Vlasenko 43d09e79db chrt: fix for SCHED_RESET_ON_FORK bit
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-04-05 16:59:07 +02:00
Denys Vlasenko ae5ca6fc41 chrt: do not segfault if policy number is unknown
While at it, improve help text

function                                             old     new   delta
packed_usage                                       33319   33344     +25
policy_name                                            -      22     +22
show_min_max                                          59      64      +5
chrt_main                                            432     429      -3
policies                                              72       -     -72
------------------------------------------------------------------------------
(add/remove: 1/1 grow/shrink: 2/1 up/down: 52/-75)            Total: -23 bytes
   text	   data	    bss	    dec	    hex	filename
 982150	    485	   7296	 989931	  f1aeb	busybox_old
 982183	    485	   7296	 989964	  f1b0c	busybox_unstripped

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-04-05 12:03:48 +02:00
Denys Vlasenko 29c2dcfe1c telnetd: whitespace fix
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-04-04 16:54:14 +02:00
Denys Vlasenko c6a8965297 telnetd: better AYT handling
function                                             old     new   delta
telnetd_main                                        1792    1837     +45

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-04-04 16:00:23 +02:00
Martin Lewis 93594b1197 telnetd: Added support for AYT IAC command.
Fixed a TODO in AYT IAC handling by replying back with a NOP.

Signed-off-by: Martin Lewis <martin.lewis.x84@gmail.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-04-04 15:44:36 +02:00
Thomas De Schampheleire 2b6282117f top: provide cmdline argument '-H' to enable thread scanning by default
In particular useful when you want to evaluate the threads in batch mode:
    top -Hbn1

function                                             old     new   delta
top_main                                             928     941     +13
packed_usage                                       33317   33319      +2
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 2/0 up/down: 15/0)               Total: 15 bytes

Signed-off-by: Philippe Belet <philippe.belet@nokia.com>
Signed-off-by: Thomas De Schampheleire <thomas.de_schampheleire@nokia.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-04-04 14:14:24 +02:00
Denys Vlasenko a3ce161363 vi: revert change in how "end of file list" is deteced - fixes 'q' in bare "vi"
function                                             old     new   delta
vi_main                                              273     272      -1
colon                                               2853    2852      -1
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 0/2 up/down: 0/-2)               Total: -2 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-04-03 16:35:23 +02:00
Denys Vlasenko e1a1b64f43 vi: code shrink
function                                             old     new   delta
new_screen                                            84      75      -9

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-04-03 16:30:50 +02:00
Ron Yorston 3e61b59ef3 vi: avoid build failure in non-default case
If vi is built with FEATURE_VI_USE_SIGNALS disabled and
FEATURE_VI_WIN_RESIZE enabled new_screen() is used without a
declaration.  Move the function to avoid this.

Signed-off-by: Ron Yorston <rmy@pobox.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-04-03 16:20:13 +02:00
Denys Vlasenko 2f28b2bdbb fsync,sync: merge into one source module
With FEATURE_SYNC_FANCY not set:

function                                             old     new   delta
fsync_main                                           130     123      -7

With FEATURE_SYNC_FANCY set, should be much larger code size savings.

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-04-02 14:55:29 +02:00
Denys Vlasenko 4f74bb6059 fsync,sync: make them similar
sync: add O_NOCTTY
fsync: drop O_NOATIME, add O_NONBLOCK, set exitcode to 1 if fsync() fails,
    update --help message to be similar to sync.
both: reformat code to minimize "diff -u sync.c fsync.c":
    in particular, they use same open() flags now

function                                             old     new   delta
fsync_main                                           126     130      +4
packed_usage                                       33316   33317      +1
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 2/0 up/down: 5/0)                 Total: 5 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-04-02 14:39:56 +02:00
Ron Yorston e48559eae3 ash: distinguish 'wait -n' from other bashisms
Add a specific define to indicate which bash compatibility code
implements 'wait -n'.

Signed-off-by: Ron Yorston <rmy@pobox.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-04-02 13:43:40 +02:00
Denys Vlasenko 8939359180 vi: rename save_argc -> cmdline_filecnt
function                                             old     new   delta
vi_main                                              272     273      +1
colon                                               2852    2853      +1

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-04-02 12:45:30 +02:00
Denys Vlasenko bbacd03ccc vi: restore capability to remember insertion cmds for "."
function                                             old     new   delta
modifying_cmds                                        17      22      +5
get_one_char                                         103      98      -5
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 1/1 up/down: 5/-5)                Total: 0 bytes
   text	   data	    bss	    dec	    hex	filename
 982121	    485	   7296	 989902	  f1ace	busybox_old
 982094	    485	   7296	 989875	  f1ab3	busybox_unstripped

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-04-02 11:50:25 +02:00
Denys Vlasenko b29dce4bc2 vi: code shrink
function                                             old     new   delta
get_input_line                                       172     175      +3
char_insert                                          444     447      +3
rawmode                                               36      24     -12
edit_file                                            644     626     -18
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 2/2 up/down: 6/-30)             Total: -24 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-04-01 17:17:02 +02:00
Denys Vlasenko 26f5e9d21c vi: convert more /**/ comments to //
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-04-01 16:42:30 +02:00
Denys Vlasenko 2a57608f67 vi: code shrink
function                                             old     new   delta
get_one_char                                         108     103      -5
edit_file                                            651     644      -7
do_cmd                                              4696    4688      -8
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 0/3 up/down: 0/-20)             Total: -20 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-04-01 16:15:51 +02:00
Denys Vlasenko 6ce60b9cca vi: use vsnprintf to format status line
This is the last use of "vsprintf" in busybox:

function                                             old     new   delta
status_line_bold                                      72      77      +5
status_line                                           40      45      +5
vsprintf                                              23       -     -23
------------------------------------------------------------------------------
(add/remove: 0/2 grow/shrink: 2/0 up/down: 10/-23)            Total: -13 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-04-01 15:41:05 +02:00
Denys Vlasenko d4f2e7ff71 vi: rearrange functions, no logic changes
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-04-01 14:18:02 +02:00
Denys Vlasenko de69775838 vi: rearrange functions, no logic changes
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-04-01 14:16:53 +02:00
Denys Vlasenko 616e4699d2 vi: rearrange functions, no logic changes
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-04-01 14:02:37 +02:00
Denys Vlasenko 363a2bc9b1 vi: rearrange functions, no logic changes
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-04-01 13:59:38 +02:00
Denys Vlasenko 24bd350aaa vi: rearrange functions, no logic changes
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-04-01 13:55:27 +02:00
Denys Vlasenko c319310404 vi: fix ^Z not always working as intended
function                                             old     new   delta
tstp_handler                                          64      71      +7
text_yank                                             54      56      +2
vi_main                                              280     272      -8
do_cmd                                              4705    4696      -9
colon                                               2861    2852      -9
cont_handler                                          66       -     -66
------------------------------------------------------------------------------
(add/remove: 0/1 grow/shrink: 2/3 up/down: 9/-92)             Total: -83 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-04-01 12:29:27 +02:00
Denys Vlasenko 6ed94aa9b2 vi: install SIGINT handler _after_ restart setjmp is initialized
While at it, sanitized comment style, deleted wrong ones, renamed signal
handlers to <sig>_handler(), slightly optimized "cursor home+clear screen".

function                                             old     new   delta
cont_handler                                           -      66     +66
tstp_handler                                           -      64     +64
winch_handler                                          -      60     +60
int_handler                                            -      32     +32
edit_file                                            648     651      +3
redraw                                                52      43      -9
catch_sig                                             32       -     -32
winch_sig                                             60       -     -60
suspend_sig                                           64       -     -64
cont_sig                                              66       -     -66
------------------------------------------------------------------------------
(add/remove: 4/4 grow/shrink: 1/1 up/down: 225/-231)           Total: -6 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-04-01 11:58:11 +02:00
Denys Vlasenko 35082fc2c1 blockdev: code shrink
function                                             old     new   delta
bdcmd_names                                            -      82     +82
bdcmd_ioctl                                            -      44     +44
bdcmd_flags                                            -      11     +11
blockdev_main                                        273     258     -15
bdcommands                                           176       -    -176
------------------------------------------------------------------------------
(add/remove: 3/1 grow/shrink: 0/1 up/down: 137/-191)          Total: -54 bytes
   text	   data	    bss	    dec	    hex	filename
 982326	    485	   7296	 990107	  f1b9b	busybox_old
 982272	    485	   7296	 990053	  f1b65	busybox_unstripped

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-03-30 20:07:21 +01:00
Stefan Sørensen bb3a9531b2 ip: Fix ip -o link
Commit db169f2538 breaks the "ip -o link"
command, no output is displayed.. Fix by only excluding the link info if
in oneline mode and if the address family is not AF_PACKET.

function                                             old     new   delta
ipaddr_list_or_flush                                1232    1202     -30

Signed-off-by: Stefan Sørensen <stefan.sorensen@spectralink.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-03-30 18:24:46 +01:00
Ron Yorston a2fd1aaf86 vi: allow manual screen update if SIGWINCH isn't supported
On platforms that don't support SIGWINCH vi can be configured
with FEATURE_VI_USE_SIGNALS disabled and FEATURE_VI_WIN_RESIZE
enabled.  This allows the user to force an update with ^L when
the screen is resized.

However, because the SIGWINCH handler hasn't run the virtual
screen buffer won't have been updated and the display becomes
corrupted.  Fix this by calling new_screen() if necessary.

Signed-off-by: Ron Yorston <rmy@pobox.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-03-30 18:03:37 +01:00
Denys Vlasenko 0f5a7f3520 man: add "/usr/share/man" as another default MANPATH, fix col override
function                                             old     new   delta
static.mpl                                             -      12     +12
packed_usage                                       33307   33316      +9
man_main                                             857     851      -6
add_MANPATH                                          148     138     -10
------------------------------------------------------------------------------
(add/remove: 1/0 grow/shrink: 1/2 up/down: 21/-16)              Total: 5 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-03-30 17:27:09 +01:00
Ron Yorston 3193cb56d6 libbb: mark scripted_main() as externally visible
Building with individual binaries enabled fails when embedded
script applets are included:

   /tmp/ccIvMFZg.o: In function `main':
   applet.c:(.text.main+0x20): undefined reference to `scripted_main'

Mark scripted_main() as externally visible.

Reported-by: Yann E. MORIN <yann.morin.1998@free.fr>
Signed-off-by: Ron Yorston <rmy@pobox.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-03-30 16:46:27 +01:00
Denys Vlasenko eabf4b2b57 vi: code shrink, proper printf formatting for strlen()
function                                             old     new   delta
yank_delete                                           98      99      +1
what_reg                                              34      33      -1
text_yank                                             56      54      -2
end_cmd_q                                             17      14      -3
do_cmd                                              4718    4705     -13
colon                                               2875    2861     -14
edit_file                                            668     648     -20
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 1/6 up/down: 1/-53)             Total: -52 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-03-29 14:40:01 +01:00
Denys Vlasenko e6f51ac697 hush: fix "wait -n" to wait for a _job_, not a _process_
function                                             old     new   delta
checkjobs                                            163     183     +20
process_wait_result                                  449     463     +14
leave_var_nest_level                                  98     107      +9
enter_var_nest_level                                  32      38      +6
set_vars_and_save_old                                147     150      +3
builtin_local                                         53      56      +3
builtin_wait                                         322     323      +1
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 7/0 up/down: 56/0)               Total: 56 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-03-27 18:35:19 +01:00
Denys Vlasenko 966f087ab4 ash: add "wait -n" bashism
function                                             old     new   delta
waitcmd                                              205     288     +83
dowait                                               405     444     +39
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 2/0 up/down: 122/0)             Total: 122 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-03-27 15:52:17 +01:00
Denys Vlasenko da996c5d2a ntpd: do not create pid file if not backgrounded
function                                             old     new   delta
ntp_init                                             995    1021     +26
ntpd_main                                           1267    1257     -10
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 1/1 up/down: 26/-10)             Total: 16 bytes

Reported by Alfonso Ranieri <alforan@tin.it>

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-03-27 13:47:38 +01:00
Denys Vlasenko 4d1c5149a0 hush: add "wait -n" bashism
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-03-26 18:34:06 +01:00
Ron Yorston 3c6f3336e1 man: don't skip default path which appears in config file
If the MANPATH environment variable isn't set a provisional default
path of /usr/man is placed in man_path_list.  This is only used if a
configuration file doesn't contain an alternative path.

If a configuration file lists the default path first:

   MANPATH /usr/man:/usr/share/man

add_MANPATH() sees that the default entry is already present and skips
it.  As a result man_path_list only contains the second and subsequent
components of the configured MANPATH.

In such cases the path should not be skipped.

function                                             old     new   delta
add_MANPATH                                          170     183     +13
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 1/0 up/down: 13/0)               Total: 13 bytes

Signed-off-by: Ron Yorston <rmy@pobox.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-03-26 17:46:21 +01:00
Denys Vlasenko fe78c9a8b7 ts: do call localtime() when neither -s nor -i specified
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-03-26 11:51:21 +01:00
Denys Vlasenko 973698d7b1 ts: use gettimeofday - we don't use nanoseconds here
function                                             old     new   delta
ts_main                                              398     376     -22

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-03-26 11:44:48 +01:00
Denys Vlasenko 3395e2a8ef ts: replace overlapping strcpy with shorter code
function                                             old     new   delta
ts_main                                              401     398      -3

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-03-26 11:41:35 +01:00
Denys Vlasenko f370a66b26 ts: fix incorrect (copy-pasted) copyright attribution
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-03-26 11:12:53 +01:00
Denys Vlasenko 16df5e8e6d ts: new applet
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-03-26 11:02:31 +01:00
Denys Vlasenko 5059653882 do not duplicate CONFIG_PID_FILE_PATH and ".pid" strings
text	   data	    bss	    dec	    hex	filename
 981737	    485	   7296	 989518	  f194e	busybox_old
 981704	    485	   7296	 989485	  f192d	busybox_unstripped

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-03-17 19:48:39 +01:00
Thomas Frauendorfer 2bbd1e1e8a Fix off by one error in FAT16 <=> FAT32 detection
cluster_count is compared against FAT16_MAX, which is defined as 0xfff4
That is the maximum number of cluster a FAT16 can have.

For reference also check the  hardware whitepaper from Microsoft
FAT: General Overview of On-Disk Format, version 1.03 page 15

Signed-off-by: Thomas Frauendorfer <tf@miray.de>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-03-15 09:57:24 +01:00
Denys Vlasenko 0ddc742c04 watch: support fractional -n SEC
function                                             old     new   delta
watch_main                                           212     232     +20

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-03-12 18:56:51 +01:00
Denys Vlasenko 2452247ea3 xargs: mention -E STR in --help
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-03-10 14:29:03 +01:00
Nicolas Hüppelshäuser b096ce0fdd scripts/echo.c: resolve implicit declaration of function 'dup2'
Signed-off-by: Nicolas Hüppelshäuser <nicolas.hueppelshaeuser@emlix.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-03-05 16:57:04 +01:00
Denys Vlasenko 4a6748662a top: tweak --help
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-02-27 16:45:39 +01:00
Andrey Mazo 87e216294a udhcpc: don't exit after backgrounding on -n -b
Currently, running "udhcpc -n -b" causes udhcpc to go to background and
then exit after some time unless a lease is obtained.

It's not very useful to do so
as the calling process doesn't know
if the lease was obtained or not anyway.

The code actually tries to favor "-b" over "-n",
but doesn't clear "-n" flag while clearing "-b" after backgrounding.

So, clear "-n" flag after going into background.
This effectively makes "-b" override "-n" completely
and "-n -b" behave the same as "-b".

This allows to override default "-n" option, passed to udhcpc by ifupdown,
without recompiling busybox.

URL: https://bugs.busybox.net/11691

Signed-off-by: Andrey Mazo <ahippo@yandex.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-02-27 08:27:47 +01:00
Denys Vlasenko 544143da0c udhcpc: tweak --help
function                                             old     new   delta
packed_usage                                       33324   33315      -9

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-02-27 08:17:07 +01:00
Ron Yorston f55161ad27 ash: eval: avoid leaking memory associated with redirections. Closes 7748
The following constructs result in ever-increasing memory usage:

   while true; do { true; } </dev/null; done
   while true; do ( true; ) </dev/null; done

For comparison, bash displays static memory usage in both cases.

This has been fixed in dash by commit 2bc6caa.  The maintainer
writes:

   I have simplified evaltree so that it simply sets the stack mark
   unconditionally.  This allows us to remove the stack marks in the
   functions called by evaltree.

Closes BusyBox bug 7748.

function                                             old     new   delta
evaltree                                             606     632     +26
evalcommand                                         1724    1696     -28
evalcase                                             382     351     -31
evalfor                                              230     196     -34
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 1/3 up/down: 26/-93)            Total: -67 bytes

Signed-off-by: Ron Yorston <rmy@pobox.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-02-25 18:57:59 +01:00
Ron Yorston e563f9e851 du: don't count duplicate arguments. Closes 5288
Since coreutils 8.6 (2010-10-15) du no longer counts duplicate arguments.

Revert the relevant part of commit 618a3027ed (du: fix "du /dir /dir"
case).

function                                             old     new   delta
du_main                                              302     297      -5
reset_ino_dev_hashtable                               78       -     -78
------------------------------------------------------------------------------
(add/remove: 0/1 grow/shrink: 0/1 up/down: 0/-83)             Total: -83 bytes

Signed-off-by: Ron Yorston <rmy@pobox.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-02-19 17:08:39 +01:00
Denys Vlasenko 8502fa8747 ntpd: increase SLEW_THRESHOLD from 0.125 to 0.5
Linux kernel supports it since ~2006

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-02-15 14:32:08 +01:00
Rostislav Skudnov d712edc6d8 dd: add 'oflag=append'
Signed-off-by: Rostislav Skudnov <rostislav@tuxera.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-02-14 13:01:46 +01:00
Nikolaus Voss f81e0120f4 i2c_tools.c: i2ctransfer
Call i2c_set_slave_addr() unconditionally as busy checking
is skipped depending on force argument.
Clarify usage texts for -f and -a flags.

Signed-off-by: Nikolaus Voss <nv@vosn.de>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-02-11 12:34:13 +01:00
Ron Yorston 61052d1bb8 vi: further fixes to undo after autoindent
Commit bb983f30e (vi: fix faulty undo after autoinsert) has a
number of problems:

- The commit message refers to 'autoinsert' when it really means
  'autoindent'.

- The indentation of undo_push_insert() was incorrect.

- Most seriously the commit only fixed the problem for cases where
  the indentation was exactly one character.  This is because undo_push()
  only allows single characters to be queued for UNDO_INS_QUEUED.

  Lifting this restriction allows the example given in the previous
  commit message (with a three character indent) to work.

function                                             old     new   delta
undo_push                                            406     435     +29
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 1/0 up/down: 29/0)               Total: 29 bytes

Signed-off-by: Ron Yorston <rmy@pobox.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-02-11 11:47:20 +01:00
Nikolaus Voss dac8f5ea38 i2ctransfer: new applet
i2ctransfer sends and receives user defined i2c messages

v2: apply Xabier's comments: add -a option, don't decrement argc,
    use bb_show_usage() and xzalloc()
v3: fix possible out of bound access to msgs[nmsgs]

Reviewed-by: Xabier Oneca -- xOneca <xoneca@gmail.com>
Signed-off-by: Nikolaus Voss <nikolaus.voss@loewensteinmedical.de>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-02-10 19:59:07 +01:00
Aaro Koskinen c89764c063 sysctl: fix compatibility with procps sysctl
Busybox sysctl is incompatible with procps when '.' appears in
directory name, mostly happens with VLANs.

        busybox syntax (since 2008): net.ipv4.conf.eth0.100.mc_forwarding
         procps syntax (since 2002): net.ipv4.conf.eth0/100.mc_forwarding
                 (supported by both: net/ipv4/conf/eth0.100/mc_forwarding)

Use procps syntax for output; for input, allow both.

function                                             old     new   delta
sysctl_dots_to_slashes                                86     143     +57
sysctl_act_on_setting                                443     453     +10
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 2/0 up/down: 67/0)               Total: 67 bytes

Signed-off-by: Aaro Koskinen <aaro.koskinen@nokia.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-02-08 16:52:51 +01:00
Denys Vlasenko 78301861ef sysctl: do slash/dot conversions only on name, not value part
function                                             old     new   delta
sysctl_dots_to_slashes                                71      86     +15

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-02-08 16:02:39 +01:00
Denys Vlasenko 1422ba6dea sysctl: on EIO ("sysctl net.ipv6.conf.all.stable_secret") set nonzero exitcode
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-02-08 14:59:06 +01:00
Denys Vlasenko 679c30e73e sysctl: avoid stat() on every item if in -w mode
function                                             old     new   delta
sysctl_act_recursive                                 163     167      +4

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-02-08 14:27:21 +01:00
Denys Vlasenko 317498f3b3 sysctl: allow setting empty values
function                                             old     new   delta
sysctl_act_on_setting                                451     445      -6

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-02-08 14:02:59 +01:00
Ron Yorston df4e3af9f7 vi: fix replacement of single character with CR
Currently if the 'r' command is followed by a carriage return a
literal CR replaces the current character.

Fix this so that:

- a new line is inserted
- the autoindent setting is respected
- the cursor is placed at the start of the new line

function                                             old     new   delta
do_cmd                                              5052    5060      +8
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 1/0 up/down: 8/0)                 Total: 8 bytes

Signed-off-by: Ron Yorston <rmy@pobox.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-02-08 13:03:06 +01:00
Ron Yorston bb983f30e7 vi: fix faulty undo after autoinsert
Enable autoinsert and enter the following with an indent of three
spaces:

   line 1
   line 2

Using 'u' to undo the last insert results in:

   line1e 2

The insertion of the indent hasn't been properly recorded.

Since recording insertions is a common operation add a convenience
function, undo_push_insert(), to handle this and use it to record
the autoindent correctly.

function                                             old     new   delta
undo_push_insert                                       -      36     +36
string_insert                                        133     129      -4
char_insert                                          518     473     -45
------------------------------------------------------------------------------
(add/remove: 1/0 grow/shrink: 0/2 up/down: 36/-49)            Total: -13 bytes

Signed-off-by: Ron Yorston <rmy@pobox.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-02-08 12:57:58 +01:00
Rostislav Skudnov e6503f2f09 chcon: Fix typo in ACTION_RECURSE
Signed-off-by: Rostislav Skudnov <rostislav@tuxera.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-02-08 12:24:46 +01:00
Denys Vlasenko 5a387e26c2 dhcp service example: rewrite "private network to mask" as case statement
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-02-08 10:37:05 +01:00
Denys Vlasenko 2feaba1d8d dhcp service example: cater for servers hot giving subnet and/or router
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-02-05 17:48:24 +01:00
Denys Vlasenko 779f96a24c lineedit: fix SEGV in isk, hexedit, ed, closes 11661
fdisk, hexedit and ed calls read_line_edit in libbb/lineedit.c with NULL
as first argument. On line 2373 of lineedit.c of busybox version 1.29.3,
state->hist_file is referenced without checking the state->flag.

This causes segmentation fault on fdisk, hexedit and ed on ARM Cortex-A9.
It somehow works on x86_64.

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-02-04 16:16:30 +01:00
Denys Vlasenko e17e8d4b7d service examples: do not respawn supplicant too often
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-02-02 19:06:19 +01:00
Ari Sundholm d4b568c108 grep: short-circuit -v to bail out on first match
A small optimization. There is no need to try matching the current
input line against any further patterns if a match was already
found and -v is specified.

function                                             old     new   delta
grep_file                                           1463    1440     -23

Signed-off-by: Ari Sundholm <ari@tuxera.com>
Signed-off-by: Niko Vähäsarja <niko@tuxera.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-01-29 14:53:22 +01:00
Ari Sundholm 9a9c6e39ba grep: fix -x -v with certain pattern orders
We found out that busybox -x -v is a bit broken:

ari@ari-thinkpad:~/busybox$ echo '  aa bb cc' | ./busybox grep -x -e 'aa.*' -e '.*bb.*'
  aa bb cc
ari@ari-thinkpad:~/busybox$ echo '  aa bb cc' | ./busybox grep -x -v -e 'aa.*' -e '.*bb.*'
ari@ari-thinkpad:~/busybox$ echo '  aa bb cc' | ./busybox grep -x -e '.*aa.*' -e 'bb.*'
  aa bb cc
ari@ari-thinkpad:~/busybox$ echo '  aa bb cc' | ./busybox grep -x -v -e '.*aa.*' -e 'bb.*'
  aa bb cc

Last one is wrong.

This patch fixes the issue by making sure that the variable 'found'
never makes a transition from 1 to 0, as this would mean that
grep previously found a match on this input line.

Signed-off-by: Ari Sundholm <ari@tuxera.com>
Signed-off-by: Niko Vähäsarja <niko@tuxera.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-01-29 14:42:57 +01:00
Denys Vlasenko 53799506ac bc: implement pass-by-reference code from upstream
function                                             old     new   delta
zxc_program_popResultAndCopyToVar                    298     493    +195
bc_vec_pushIndex                                       -      75     +75
zxc_vm_process                                       859     928     +69
xc_program_dereference                                 -      66     +66
bc_vec_npush                                           -      65     +65
zbc_num_s                                            239     249     +10
zxc_program_num                                     1024    1032      +8
zbc_num_divmod                                       150     156      +6
xc_program_search                                    143     146      +3
zxc_program_assign                                   392     389      -3
zdc_program_execStr                                  520     517      -3
xc_program_pushVar                                   198     195      -3
zxc_program_exec                                    4101    4092      -9
zbc_program_call                                     318     308     -10
zbc_func_insert                                      120     104     -16
zbc_parse_stmt_possibly_auto                        1460    1439     -21
bc_vec_push                                           53      12     -41
xc_parse_pushIndex                                    61      18     -43
------------------------------------------------------------------------------
(add/remove: 3/0 grow/shrink: 6/9 up/down: 497/-149)          Total: 348 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-01-25 16:22:15 +01:00
Denys Vlasenko db5a6daa7f login: close PAM session on errors as well, not only on success
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-01-22 17:04:16 +01:00
Bernhard Reutner-Fischer 414be6c111 ip link: Fix vlan proto, closes 8261 and 11638
The proto has to be passed in network byte-order.
While at it allow for
 ip link add link eth0 name eth0.2.24 type vlan proto 802.1ad id 24
 ip link del link eth0 name eth0.2.24 type vlan proto 802.1ad id 24
The del was lacking a dev_str and thus errored out. Fix by using
name/dev counterpart as fallback.

The proto identifier 802.1Q was not recognized, just it's lowercase
variant, fix that too.

function                                             old     new   delta
do_add_or_delete                                    1275    1376    +101
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 1/0 up/down: 101/0)             Total: 101 bytes

Signed-off-by: Bernhard Reutner-Fischer <rep.dot.nop@gmail.com>
2019-01-22 15:22:05 +01:00
Denys Vlasenko f50faf8408 ip link: fix mismatched enums in vlan_parse_opt(), closes 11631
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-01-22 10:07:50 +01:00
Denys Vlasenko 9b313ddcd8 wget: detect when the length of received file is less than advertised
function                                             old     new   delta
retrieve_file_data                                   579     596     +17

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-01-21 13:53:26 +01:00
Denys Vlasenko 4906faafab sed: code shrink
function                                             old     new   delta
parse_file_cmd                                       115      94     -21

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-01-21 13:49:28 +01:00
Brian Foley b7928e18b1 sed: Fix backslash parsing for 'w' command arg
If there's any whitespace between w and the filename, parse_file_cmd
writes to the wrong offset when trying to fix up backslashes.

This can be seen in the asan build with busybox sed -e 'w 0\\'

Signed-off-by: Brian Foley <bpfoley@google.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-01-21 13:22:31 +01:00
Brian Foley 1c42c18e96 awk: Fix overly permissive func arg list parsing
It allows things like 'func f(a b)' and 'func f(a,)' which GNU awk forbids.

function                                             old     new   delta
parse_program                                        327     367     +40
chain_expr                                            40      67     +27
parse_expr                                           891     915     +24
EMSG_TOO_FEW_ARGS                                     30      18     -12
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 3/1 up/down: 91/-12)             Total: 79 bytes

Signed-off-by: Brian Foley <bpfoley@google.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-01-21 12:59:19 +01:00
Brian Foley 08a514c097 awk: Syntax error if delete isn't given an arg.
Unlike exit and return, delete strictly requires an arg, and derefs a
null pointer if executed without one.

Signed-off-by: Brian Foley <bpfoley@google.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-01-21 12:55:49 +01:00
Brian Foley dac15a10ac awk: Guard pointer chasing when parsing ternary expressions.
Avoids an uninit pointer deref for some malformed ternary exprs.

Add a test that would crash in busybox before this fix.

Signed-off-by: Brian Foley <bpfoley@google.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-01-21 12:55:49 +01:00
Mark Marshall 11cb9eeffe capability: fix string comparison in cap_name_to_number
The result of strcasecmp was being used incorrectly.  This function
returns 0 if the strings match.

Signed-off-by: Mark Marshall <mark.marshall@omicronenergy.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-01-21 12:50:37 +01:00
Denys Vlasenko fc472ea187 wget: remove empty if/endif preprocessor directive pair
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-01-18 23:15:20 +01:00
Denys Vlasenko f7235cc89f service examples: ifplugd -M to prevents frequent respawning
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-01-18 14:17:02 +01:00
Bernhard Reutner-Fischer 774879c4e1 checkstack.pl: tweak bfin re
Signed-off-by: Bernhard Reutner-Fischer <rep.dot.nop@gmail.com>
2019-01-18 09:56:19 +01:00
Bernhard Reutner-Fischer f59739a663 checkstack: pull from upstream
merge upstream changes

Signed-off-by: Bernhard Reutner-Fischer <rep.dot.nop@gmail.com>
2019-01-17 22:59:45 +01:00
Bernhard Reutner-Fischer fe7ae562e5 checkstack.pl: fix arch autodetection
chomp trailing newlines

Signed-off-by: Bernhard Reutner-Fischer <rep.dot.nop@gmail.com>
2019-01-17 22:59:45 +01:00
Martin Lewis 94e748d027 wget: don't notify on download begin and end if quiet
When printing notification on download start and end,
mistakenly, it didn't respect the quiet option

function                                             old     new   delta
retrieve_file_data                                   561     579     +18
wget_main                                           2432    2437      +5
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 2/0 up/down: 23/0)               Total: 23 bytes

Signed-off-by: Martin Lewis <martin.lewis.x84@gmail.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-01-17 13:46:14 +01:00
Denys Vlasenko edb74f4019 Update examples/udhcp/udhcpd.conf
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-01-15 13:19:01 +01:00
Denys Vlasenko 77524a311a start-stop-daemon: fix "both -x and -a" case: -a does override argv[0]
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-01-14 15:00:49 +01:00
Denys Vlasenko 088fec36fe start-stop-daemon: create pidfile before parent exits, closes 8596
This removes DAEMON_DOUBLE_FORK flag from bb_daemonize_or_rexec(),
as SSD was the only user.

Also includes fix for -S: now works without -a and -x,
does not print pids
(compat with "start-stop-daemon (OpenRC) 0.34.11 (Gentoo Linux)").

function                                             old     new   delta
start_stop_daemon_main                              1018    1084     +66
add_interface                                         99     103      +4
fail_hunk                                            139     136      -3
bb_daemonize_or_rexec                                205     183     -22
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 2/2 up/down: 70/-25)             Total: 45 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-01-14 14:47:21 +01:00
Denys Vlasenko b67d900395 adduser: fix a bug of getpwnam() overwriting shell name, closes 8586
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-01-12 11:51:58 +01:00
Denys Vlasenko 3109d1f965 tls: code shrink
function                                             old     new   delta
lm_add                                                82      78      -4
curve25519                                           793     786      -7
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 0/2 up/down: 0/-11)             Total: -11 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-01-10 20:18:02 +01:00
Denys Vlasenko 6ca8e347fe nslookup: return exitcode 1 on resolution errors
function                                             old     new   delta
nslookup_main                                        757     760      +3
send_queries                                        1690    1677     -13

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-01-09 13:38:57 +01:00
Denys Vlasenko 8419123112 telnet: placate compiler's warning
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-01-09 13:12:58 +01:00
Denys Vlasenko ecf02e8b83 date: improve help text for -D
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-01-09 12:58:52 +01:00
Denys Vlasenko cfc2546ea4 bc: code shrink
function                                             old     new   delta
xc_parse_pushInst_and_Index                            -      16     +16
zbc_parse_expr                                      1818    1816      -2
xc_parse_pushIndex                                    65      61      -4
zbc_parse_pushSTR                                     63      58      -5
zbc_parse_name                                       448     442      -6
xc_parse_pushNUM                                      74      67      -7
zdc_parse_expr                                       479     470      -9
bc_parse_pushJUMP_ZERO                                21      12      -9
bc_parse_pushJUMP                                     21      12      -9
------------------------------------------------------------------------------
(add/remove: 1/0 grow/shrink: 0/8 up/down: 16/-51)            Total: -35 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-01-09 11:17:19 +01:00
Denys Vlasenko a1698a15dc bc: remove "empty expression" check/message, parsing fails in these cases anyway
function                                             old     new   delta
zbc_parse_expr                                      1848    1818     -30

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-01-08 19:32:38 +01:00
Denys Vlasenko 132d7c098b bc: zbc_parse_expr_empty_ok() is unused except by zbc_parse_expr(), fold it in
function                                             old     new   delta
zbc_parse_expr                                      1865    1848     -17

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-01-08 19:29:35 +01:00
Denys Vlasenko fc7aa7a296 bc: disallow invalid syntax like "{ print 1 print 2 }"
statement parsing must NOT eat the terminator: caller needs to know
what it was, to correctly decide whether it is a valid one.

function                                             old     new   delta
zxc_program_read                                       -     234    +234
zdc_program_printStream                                -     144    +144
zbc_parse_stmt_possibly_auto                        1413    1460     +47
zxc_vm_process                                       869     859     -10
zxc_program_exec                                    4116    4101     -15
zdc_program_asciify                                  368       -    -368
------------------------------------------------------------------------------
(add/remove: 2/1 grow/shrink: 1/2 up/down: 425/-393)           Total: 32 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-01-08 18:10:00 +01:00
Einar Jón ce51140664 passwd: initialize pointers correctly
Fix for running passwd as root (or sudo passwd $USER).
Crashed on call to free(orig) during cleanup.

Fix regression from commit 17058a06c4
Root user never changes the orig pointer, so when cleaning up, passwd tried to
free orig=(char*)""
Example: sudo passwd $USER
Changing password for xxx
New password:
Bad password: too short
Retype password:
Passwords don't match
free(): invalid pointer
Aborted

function                                             old     new   delta
passwd_main                                          958     961      +3

Signed-off-by: Einar Jón <tolvupostur@gmail.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-01-08 16:32:25 +01:00
Denys Vlasenko 959b04bc0e tls: add comment about dl.fedoraproject.org needing secp256r1 ECC curve
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-01-08 16:09:41 +01:00
Denys Vlasenko 74d9f1ba37 udhcpc: when decoding DHCP_SUBNET, ensure it is 4 bytes long
function                                             old     new   delta
udhcp_run_script                                     795     801      +6

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-01-07 15:33:42 +01:00
Denys Vlasenko b80bdeba02 udhcp: code shrink
function                                             old     new   delta
attach_option                                        406     349     -57

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-01-07 15:23:18 +01:00
Denys Vlasenko edca770d11 sleep: support "inf"
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-01-07 15:20:56 +01:00
Denys Vlasenko 4bdc914ff9 build system: fix compiler warnings
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-01-06 20:12:16 +01:00
Denys Vlasenko 2d9e097963 find: handle leading -- argument
function                                             old     new   delta
find_main                                            464     478     +14

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-01-06 19:58:18 +01:00
Danijel Tasov 3f4fac577a telnet: provide feedback after successful connect
The real telnet provides some feedback:

Trying 127.0.0.1...
Connected to localhost.localdomain.
Escape character is '^]'.

We should do this to, because people are sitting there and think
a firewall is dropping packets.

function                                             old     new   delta
telnet_main                                         1270    1279      +9

Signed-off-by: Danijel Tasov <m@rbfh.de>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-01-06 19:20:05 +01:00
Denys Vlasenko 39b18196f8 telnetd: fix bad interaction with vhangup() from login
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-01-06 19:06:01 +01:00
Denys Vlasenko 935afafcf3 telnet: code shrink
function                                             old     new   delta
put_iac3_IAC_x_y_merged                                -      21     +21
put_iac4_msb_lsb                                       -      19     +19
put_iac2_msb_lsb                                       -      19     +19
put_iac                                               20      34     +14
iac_flush                                             32      36      +4
put_iac2_merged                                       46       -     -46
telnet_main                                         1492    1270    -222
------------------------------------------------------------------------------
(add/remove: 3/1 grow/shrink: 2/1 up/down: 77/-268)          Total: -191 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-01-06 18:45:38 +01:00
Denys Vlasenko 5bfc4a32fd telnet: speed up processing of network input
function                                             old     new   delta
telnet_main                                         1482    1492     +10

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-01-06 18:41:11 +01:00
Kaarle Ritvanen 1c952ba206 ip: print dadfailed flag
Signed-off-by: Kaarle Ritvanen <kaarle.ritvanen@datakunkku.fi>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-01-04 19:00:23 +01:00
Martijn Dekker f83292cfc4 ls: make -i compatible with coreutils: don't follow symlink by default
Signed-off-by: Martijn Dekker <martijn@inlv.org>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-01-04 18:55:53 +01:00
Martin Lewis 46fc3290c2 wget: notify on download begin and end
When using -o to file the progress meter is not displayed, so write that
we started the download and that we finished it.

function                                             old     new   delta
retrieve_file_data                                   465     561     +96
wget_main                                           2412    2432     +20
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 2/0 up/down: 116/0)             Total: 116 bytes
   text	   data	    bss	    dec	    hex	filename
 979022	    485	   7296	 986803	  f0eb3	busybox_old
 979224	    485	   7296	 987005	  f0f7d	busybox_unstripped

Signed-off-by: Martin Lewis <martin.lewis.x84@gmail.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-01-04 18:27:28 +01:00
Martin Lewis 64f35361f4 wget: add -o flag
function                                             old     new   delta
wget_main                                           2348    2412     +64
packed_usage                                       33062   33093     +31
static.wget_longopts                                 252     266     +14
progress_meter                                       158     159      +1
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 4/0 up/down: 110/0)             Total: 110 bytes

Signed-off-by: Martin Lewis <martin.lewis.x84@gmail.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-01-04 18:17:09 +01:00
Denys Vlasenko e05ec6ed3e bc: shorten "limits" output
text	   data	    bss	    dec	    hex	filename
 979016	    485	   7296	 986797	  f0ead	busybox_old
 978959	    485	   7296	 986740	  f0e74	busybox_unstripped

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-01-04 16:26:19 +01:00
Denys Vlasenko f11b5b9864 bc: formatting changes, added a FIXME comment, no logic changes
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-01-04 15:54:40 +01:00
Denys Vlasenko 54f5c1d600 bc: support void functions (GNU compat)
function                                             old     new   delta
xc_program_print                                       -     689    +689
zxc_vm_process                                       814     869     +55
zxc_program_exec                                    4098    4116     +18
zxc_program_assign                                   385     392      +7
bc_result_free                                        43      46      +3
zxc_program_binOpPrep                                243     245      +2
zdc_program_execStr                                  518     520      +2
zxc_program_print                                    683       -    -683
------------------------------------------------------------------------------
(add/remove: 1/1 grow/shrink: 6/0 up/down: 776/-683)           Total: 93 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-01-04 13:58:46 +01:00
Denys Vlasenko 1db367a8e6 dc: fit returning of string
function                                             old     new   delta
zxc_program_exec                                    4087    4098     +11

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-01-04 06:18:00 +01:00
Denys Vlasenko 6842c6062a dc: fix '?'
function                                             old     new   delta
zdc_parse_expr                                       470     479      +9
zxc_vm_process                                       839     814     -25
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 1/1 up/down: 9/-25)             Total: -16 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-01-04 05:41:47 +01:00
Denys Vlasenko 377cc97b19 bc: eliminate struct BcInstPtr::results_len_before_call, it is redundant
function                                             old     new   delta
zbc_program_call                                     332     318     -14
zxc_program_exec                                    4147    4087     -60
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 0/2 up/down: 0/-74)             Total: -74 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-01-04 00:35:31 +01:00
Denys Vlasenko 02c3d7a1c9 bc: add a palceholder comment for "void" return
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-01-04 00:21:29 +01:00
Denys Vlasenko 19c3eb0b04 bc: remove extra div/0 test, remove test for string function parameter
function                                             old     new   delta
zbc_program_call                                     354     332     -22
zxc_program_assign                                   426     385     -41
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 0/2 up/down: 0/-63)             Total: -63 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-01-04 00:05:07 +01:00
Denys Vlasenko 96b5ec10fb bc: fix "...; return}" to work, disallow "return ()"
function                                             old     new   delta
zbc_parse_expr                                        24    1865   +1841
zbc_parse_stmt_possibly_auto                        1425    1413     -12
bc_parse_expr_empty_ok                              1843       -   -1843
------------------------------------------------------------------------------
(add/remove: 0/1 grow/shrink: 1/1 up/down: 1841/-1855)        Total: -14 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-01-03 23:34:36 +01:00
Denys Vlasenko ae6c44ea15 bc: make error line number also size_t, like everything else
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-01-02 16:30:24 +01:00
Denys Vlasenko cb7c955aeb bc: generate large bc tests on the fly, -5 mbytes in the git tree
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-01-02 14:00:20 +01:00
Denys Vlasenko 266bec8ba7 bc: speed up string printing, fix print ""
function                                             old     new   delta
static.esc                                             -       9      +9
zxc_program_print                                    681     683      +2
------------------------------------------------------------------------------
(add/remove: 1/0 grow/shrink: 1/0 up/down: 11/0)               Total: 11 bytes
   text	   data	    bss	    dec	    hex	filename
 979144	    485	   7296	 986925	  f0f2d	busybox_old
 979062	    485	   7296	 986843	  f0edb	busybox_unstripped

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-01-02 05:03:53 +01:00
Denys Vlasenko 2231468a2f bc: upstream fixes
function                                             old     new   delta
bc_parse_expr_empty_ok                              1764    1843     +79
bc_error_at                                            -      62     +62
bc_parse_inst_isLeaf                                   -      30     +30
zbc_func_insert                                      100     120     +20
bc_error_bad_function_definition                       -      10     +10
bc_error_bad_assignment                                -      10     +10
zxc_lex_next                                        1608    1614      +6
ok_in_expr                                            30       -     -30
zxc_vm_process                                       874     839     -35
------------------------------------------------------------------------------
(add/remove: 4/1 grow/shrink: 3/1 up/down: 217/-65)           Total: 152 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-01-01 21:50:14 +01:00
Denys Vlasenko ff65355b8a single-applet build --help had extra \n, remove
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-01-01 16:54:30 +01:00
Denys Vlasenko 37bdd8f8cb tls: pstm code shrink
Optimize ABI calling convention and "dead code" cases where return value
is known to be always "success".

function                                             old     new   delta
pstm_mod                                             113    1227   +1114
pstm_exptmod                                        1463    1532     +69
pstm_montgomery_reduce                               381     393     +12
pstm_sqr_comba                                       478     487      +9
pstm_mul_comba                                       447     452      +5
der_binary_to_pstm                                    42      45      +3
pstm_count_bits                                       48      46      -2
pstm_clear                                            72      70      -2
pstm_clamp                                            57      55      -2
pstm_zero                                             38      34      -4
pstm_init_size                                        46      42      -4
pstm_init_for_read_unsigned_bin                       24      20      -4
pstm_grow                                             72      68      -4
pstm_unsigned_bin_size                                37      32      -5
pstm_cmp_mag                                          78      72      -6
pstm_copy                                             92      84      -8
pstm_mul_d                                           224     215      -9
pstm_rshd                                            104      94     -10
pstm_mul_2                                           156     146     -10
tls_handshake                                       2085    2072     -13
psRsaEncryptPub                                      421     408     -13
pstm_lshd                                            109      95     -14
pstm_cmp                                              54      39     -15
s_pstm_sub                                           228     212     -16
pstm_init_copy                                        72      52     -20
pstm_read_unsigned_bin                               109      88     -21
pstm_mulmod                                          120      99     -21
s_pstm_add                                           337     314     -23
pstm_add                                             108      84     -24
pstm_mul_2d                                          186     161     -25
pstm_sub                                             102      74     -28
pstm_to_unsigned_bin                                 151     120     -31
pstm_set                                              34       -     -34
pstm_div_2d                                          409     373     -36
pstm_init                                             42       -     -42
pstm_exch                                             50       -     -50
pstm_montgomery_setup                                 89       -     -89
pstm_2expt                                            96       -     -96
pstm_montgomery_calc_normalization                   140       -    -140
pstm_div                                            1522       -   -1522
------------------------------------------------------------------------------
(add/remove: 0/7 grow/shrink: 6/27 up/down: 1212/-2343)     Total: -1131 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-01-01 15:40:43 +01:00
Denys Vlasenko 51b510a480 bc: in xc_read_line(), check ^C on NUL input bytes too
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-01-01 02:19:02 +01:00
Denys Vlasenko 8797adc1c6 bc: remove superfluous assigment
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2018-12-31 19:50:06 +01:00
Denys Vlasenko 680ccd3573 bc: support ibase up to 36 (GNU compat)
function                                             old     new   delta
zxc_program_num                                      995    1018     +23

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2018-12-31 19:42:13 +01:00
Denys Vlasenko 2747f6195b bc: fold xc_lex_more_input() into peek_inbuf()
function                                             old     new   delta
peek_inbuf                                            69      56     -13

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2018-12-31 18:48:59 +01:00
Denys Vlasenko aad76968cd pmap: make 32-bit version work better on 64-bit kernels
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2018-12-31 15:18:45 +01:00
Denys Vlasenko 8b710ef000 make_single_applets.sh: fix for BSS trick
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2018-12-31 15:18:45 +01:00
Denys Vlasenko 29bc59312f Start 1.31.0 development cycle
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2018-12-30 16:32:00 +01:00
159 changed files with 7172 additions and 5196 deletions

No files matched your search

+10 -1
View File
@@ -12,7 +12,7 @@ config HAVE_DOT_CONFIG
menu "Settings"
config DESKTOP
bool "Enable compatibility for full-blown desktop systems"
bool "Enable compatibility for full-blown desktop systems (8kb)"
default y
help
Enable applet options and features which are not essential.
@@ -339,6 +339,15 @@ config FEATURE_CLEAN_UP
Don't enable this unless you have a really good reason to clean
things up manually.
config FEATURE_SYSLOG_INFO
bool "Support LOG_INFO level syslog messages"
default y
depends on FEATURE_SYSLOG
help
Applets which send their output to syslog use either LOG_INFO or
LOG_ERR log levels, but by disabling this option all messages will
be logged at the LOG_ERR level, saving just under 200 bytes.
# These are auto-selected by other options
config FEATURE_SYSLOG
+2 -2
View File
@@ -1,6 +1,6 @@
VERSION = 1
PATCHLEVEL = 30
SUBLEVEL = 0
PATCHLEVEL = 31
SUBLEVEL = 1
EXTRAVERSION =
NAME = Unnamed
+1 -1
View File
@@ -235,9 +235,9 @@ static int get_next_block(bunzip_data *bd)
/* Get next value */
int n = 0;
while (get_bits(bd, 1)) {
n++;
if (n >= groupCount)
return RETVAL_DATA_ERROR;
n++;
}
/* Decode MTF to get the next selector */
tmp_byte = mtfSymbol[n];
+19 -1
View File
@@ -96,6 +96,24 @@ unpack_xz_stream(transformer_state_t *xstate)
*/
do {
if (membuf[iobuf.in_pos] != 0) {
/* There is more data, but is it XZ data?
* Example: dpkg-deb -f busybox_1.30.1-4_amd64.deb
* reads control.tar.xz "control" file
* inside the ar archive, but tar.xz
* extraction code reaches end of xz data,
* reached this code and reads the beginning
* of data.tar.xz's ar header, which isn't xz data,
* and prints "corrupted data".
* The correct solution is to not read
* past nested archive (to simulate EOF).
* This is a workaround:
*/
if (membuf[iobuf.in_pos] != 0xfd) {
/* It's definitely not a xz signature
* (which is 0xfd,"7zXZ",0x00).
*/
goto end;
}
xz_dec_reset(state);
goto do_run;
}
@@ -128,7 +146,7 @@ unpack_xz_stream(transformer_state_t *xstate)
break;
}
}
end:
xz_dec_end(state);
free(membuf);
+27 -17
View File
@@ -159,47 +159,44 @@ void FAST_FUNC fork_transformer(int fd, const char *transform_prog)
*/
static transformer_state_t *setup_transformer_on_fd(int fd, int fail_if_not_compressed)
{
union {
uint8_t b[4];
uint16_t b16[2];
uint32_t b32[1];
} magic;
transformer_state_t *xstate;
xstate = xzalloc(sizeof(*xstate));
xstate->src_fd = fd;
xstate->signature_skipped = 2;
/* .gz and .bz2 both have 2-byte signature, and their
* unpack_XXX_stream wants this header skipped. */
xread(fd, magic.b16, sizeof(magic.b16[0]));
xstate->signature_skipped = 2;
xread(fd, xstate->magic.b16, 2);
if (ENABLE_FEATURE_SEAMLESS_GZ
&& magic.b16[0] == GZIP_MAGIC
&& xstate->magic.b16[0] == GZIP_MAGIC
) {
xstate->xformer = unpack_gz_stream;
USE_FOR_NOMMU(xstate->xformer_prog = "gunzip";)
goto found_magic;
}
if (ENABLE_FEATURE_SEAMLESS_Z
&& magic.b16[0] == COMPRESS_MAGIC
&& xstate->magic.b16[0] == COMPRESS_MAGIC
) {
xstate->xformer = unpack_Z_stream;
USE_FOR_NOMMU(xstate->xformer_prog = "uncompress";)
goto found_magic;
}
if (ENABLE_FEATURE_SEAMLESS_BZ2
&& magic.b16[0] == BZIP2_MAGIC
&& xstate->magic.b16[0] == BZIP2_MAGIC
) {
xstate->xformer = unpack_bz2_stream;
USE_FOR_NOMMU(xstate->xformer_prog = "bunzip2";)
goto found_magic;
}
if (ENABLE_FEATURE_SEAMLESS_XZ
&& magic.b16[0] == XZ_MAGIC1
&& xstate->magic.b16[0] == XZ_MAGIC1
) {
uint32_t v32;
xstate->signature_skipped = 6;
xread(fd, magic.b32, sizeof(magic.b32[0]));
if (magic.b32[0] == XZ_MAGIC2) {
xread(fd, &xstate->magic.b16[1], 4);
move_from_unaligned32(v32, &xstate->magic.b16[1]);
if (v32 == XZ_MAGIC2) {
xstate->xformer = unpack_xz_stream;
USE_FOR_NOMMU(xstate->xformer_prog = "unxz";)
goto found_magic;
@@ -344,11 +341,24 @@ void* FAST_FUNC xmalloc_open_zipped_read_close(const char *fname, size_t *maxsz_
*maxsz_p = xstate->mem_output_size;
}
} else {
/* File is not compressed */
//FIXME: avoid seek
xlseek(xstate->src_fd, - xstate->signature_skipped, SEEK_CUR);
/* File is not compressed.
* We already read first few bytes, account for that.
* Example where it happens:
* "modinfo MODULE.ko" (not compressed)
* open("MODULE.ko", O_RDONLY|O_LARGEFILE) = 4
* read(4, "\177E", 2) = 2
* fstat64(4, ...)
* mmap(...)
* read(4, "LF\2\1\1\0\0\0\0"...
* ...and we avoided seeking on the fd! :)
*/
image = xmalloc_read_with_initial_buf(
xstate->src_fd,
maxsz_p,
xmemdup(&xstate->magic, xstate->signature_skipped),
xstate->signature_skipped
);
xstate->signature_skipped = 0;
image = xmalloc_read(xstate->src_fd, maxsz_p);
}
if (!image)
+1 -1
View File
@@ -25,7 +25,7 @@
#define STREAM_HEADER_SIZE 12
#define HEADER_MAGIC "\3757zXZ"
#define HEADER_MAGIC "\375""7zXZ"
#define HEADER_MAGIC_SIZE 6
#define FOOTER_MAGIC "YZ"
+2 -2
View File
@@ -54,7 +54,7 @@
//config: date -s (and other commands like touch -d) use more sensible
//config: formats (for one, ISO format YYYY-MM-DD hh:mm:ss.ssssss).
//config:
//config: With this option off, 'date DATE' is 'date -s DATE' support
//config: With this option off, 'date DATE' and 'date -s DATE' support
//config: the same format. With it on, 'date DATE' additionally supports
//config: MMDDhhmm[[YY]YY][.ss] format.
@@ -121,7 +121,7 @@
//usage: "\n -d,--date TIME Display TIME, not 'now'"
//usage: )
//usage: IF_FEATURE_DATE_ISOFMT(
//usage: "\n -D FMT Use FMT for -d TIME conversion"
//usage: "\n -D FMT Use FMT (strptime format) for -d TIME conversion"
//usage: )
//usage: "\n"
//usage: "\nRecognized TIME formats:"
+23 -19
View File
@@ -59,7 +59,7 @@
//usage: "[if=FILE] [of=FILE] [" IF_FEATURE_DD_IBS_OBS("ibs=N obs=N/") "bs=N] [count=N] [skip=N] [seek=N]\n"
//usage: IF_FEATURE_DD_IBS_OBS(
//usage: " [conv=notrunc|noerror|sync|fsync]\n"
//usage: " [iflag=skip_bytes|fullblock] [oflag=seek_bytes]"
//usage: " [iflag=skip_bytes|fullblock] [oflag=seek_bytes|append]"
//usage: )
//usage:#define dd_full_usage "\n\n"
//usage: "Copy a file with converting and formatting\n"
@@ -84,6 +84,7 @@
//usage: "\n iflag=skip_bytes skip=N is in bytes"
//usage: "\n iflag=fullblock Read full blocks"
//usage: "\n oflag=seek_bytes seek=N is in bytes"
//usage: "\n oflag=append Open output file in append mode"
//usage: )
//usage: IF_FEATURE_DD_STATUS(
//usage: "\n status=noxfer Suppress rate output"
@@ -140,11 +141,12 @@ enum {
/* start of output flags */
FLAG_OFLAG_SHIFT = 7,
FLAG_SEEK_BYTES = (1 << 7) * ENABLE_FEATURE_DD_IBS_OBS,
FLAG_APPEND = (1 << 8) * ENABLE_FEATURE_DD_IBS_OBS,
/* end of output flags */
FLAG_TWOBUFS = (1 << 8) * ENABLE_FEATURE_DD_IBS_OBS,
FLAG_COUNT = 1 << 9,
FLAG_STATUS_NONE = 1 << 10,
FLAG_STATUS_NOXFER = 1 << 11,
FLAG_TWOBUFS = (1 << 9) * ENABLE_FEATURE_DD_IBS_OBS,
FLAG_COUNT = 1 << 10,
FLAG_STATUS_NONE = 1 << 11,
FLAG_STATUS_NOXFER = 1 << 12,
};
static void dd_output_status(int UNUSED_PARAM cur_signal)
@@ -190,23 +192,15 @@ static void dd_output_status(int UNUSED_PARAM cur_signal)
#endif
}
static ssize_t full_write_or_warn(const void *buf, size_t len,
const char *const filename)
{
ssize_t n = full_write(ofd, buf, len);
if (n < 0)
bb_perror_msg("writing '%s'", filename);
return n;
}
static bool write_and_stats(const void *buf, size_t len, size_t obs,
const char *filename)
{
ssize_t n = full_write_or_warn(buf, len, filename);
if (n < 0)
return 1;
ssize_t n;
n = full_write(ofd, buf, len);
#if ENABLE_FEATURE_DD_THIRD_STATUS_LINE
G.total_bytes += n;
if (n > 0)
G.total_bytes += n;
#endif
if ((size_t)n == obs) {
G.out_full++;
@@ -216,6 +210,14 @@ static bool write_and_stats(const void *buf, size_t len, size_t obs,
G.out_part++;
return 0;
}
/* n is < len (and possibly is -1).
* Even if n >= 0, errno is usually set correctly.
* For example, if writing to block device and getting ENOSPC,
* full_write() first sees a short write, then tries to write
* the remainder and gets errno set to ENOSPC.
* It returns n > 0 (the amount which it did write).
*/
bb_perror_msg("error writing '%s'", filename);
return 1;
}
@@ -267,7 +269,7 @@ int dd_main(int argc UNUSED_PARAM, char **argv)
static const char iflag_words[] ALIGN1 =
"skip_bytes\0""fullblock\0";
static const char oflag_words[] ALIGN1 =
"seek_bytes\0";
"seek_bytes\0append\0";
#endif
#if ENABLE_FEATURE_DD_STATUS
static const char status_words[] ALIGN1 =
@@ -451,6 +453,8 @@ int dd_main(int argc UNUSED_PARAM, char **argv)
if (!seek && !(G.flags & FLAG_NOTRUNC))
oflag |= O_TRUNC;
if (G.flags & FLAG_APPEND)
oflag |= O_APPEND;
xmove_fd(xopen(outfile, oflag), ofd);
+2 -2
View File
@@ -290,11 +290,11 @@ int du_main(int argc UNUSED_PARAM, char **argv)
total = 0;
do {
total += du(*argv);
/* otherwise du /dir /dir won't show /dir twice: */
reset_ino_dev_hashtable();
G.slink_depth = slink_depth_save;
} while (*++argv);
if (ENABLE_FEATURE_CLEAN_UP)
reset_ino_dev_hashtable();
if (opt & OPT_c_total)
print(total, "total");
+36 -7
View File
@@ -63,33 +63,62 @@ enum {
OPT_ALL = 1 << 2,
};
//FIXME: does not work properly with input containing NULs
//coreutils 8.30 preserves NULs but treats them as chars of width zero:
//AB<nul><tab>C will expand <tab> to 6 spaces, not 5.
#if ENABLE_EXPAND
static void expand(FILE *file, unsigned tab_size, unsigned opt)
{
char *line;
while ((line = xmalloc_fgets(file)) != NULL) {
unsigned char c;
for (;;) {
char *line;
char *ptr;
char *ptr_strbeg;
//commented-out code handles NULs, +90 bytes of code, not tested much
// size_t linelen;
// unsigned len = 0;
// linelen = 1024 * 1024;
// line = xmalloc_fgets_str_len(file, "\n", &linelen);
line = xmalloc_fgets(file); //
if (!line)
break;
ptr = ptr_strbeg = line;
while ((c = *ptr) != '\0') {
for (;;) {
unsigned char c = *ptr;
if (c == '\0') {
// size_t rem = line + linelen - ptr;
// if (rem > 0) {
//# if ENABLE_UNICODE_SUPPORT
// len += unicode_strwidth(ptr_strbeg);
//# else
// len += ptr - ptr_strbeg;
//# endif
// printf("%s%c", ptr_strbeg, '\0');
// memmove(ptr, ptr + 1, rem + 1);
// ptr_strbeg = ptr;
// linelen--;
// continue;
// }
break;
}
if ((opt & OPT_INITIAL) && !isblank(c)) {
/* not space or tab */
break;
}
if (c == '\t') {
unsigned len;
unsigned len = 0; //
*ptr = '\0';
# if ENABLE_UNICODE_SUPPORT
len = unicode_strwidth(ptr_strbeg);
len += unicode_strwidth(ptr_strbeg);
# else
len = ptr - ptr_strbeg;
len += ptr - ptr_strbeg;
# endif
len = tab_size - (len % tab_size);
/*while (ptr[1] == '\t') { ptr++; len += tab_size; } - can handle many tabs at once */
printf("%s%*s", ptr_strbeg, len, "");
// len = 0;
ptr_strbeg = ptr + 1;
}
ptr++;
-60
View File
@@ -1,60 +0,0 @@
/* vi: set sw=4 ts=4: */
/*
* Mini fsync implementation for busybox
*
* Copyright (C) 2008 Nokia Corporation. All rights reserved.
*
* Licensed under GPLv2 or later, see file LICENSE in this source tree.
*/
//config:config FSYNC
//config: bool "fsync (3.6 kb)"
//config: default y
//config: help
//config: fsync is used to flush file-related cached blocks to disk.
//applet:IF_FSYNC(APPLET_NOFORK(fsync, fsync, BB_DIR_BIN, BB_SUID_DROP, fsync))
//kbuild:lib-$(CONFIG_FSYNC) += fsync.o
//usage:#define fsync_trivial_usage
//usage: "[-d] FILE..."
//usage:#define fsync_full_usage "\n\n"
//usage: "Write files' buffered blocks to disk\n"
//usage: "\n -d Avoid syncing metadata"
#include "libbb.h"
#ifndef O_NOATIME
# define O_NOATIME 0
#endif
/* This is a NOFORK applet. Be very careful! */
int fsync_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
int fsync_main(int argc UNUSED_PARAM, char **argv)
{
int status;
int opts;
opts = getopt32(argv, "d"); /* fdatasync */
argv += optind;
if (!*argv) {
bb_show_usage();
}
status = EXIT_SUCCESS;
do {
int fd = open_or_warn(*argv, O_NOATIME | O_NOCTTY | O_RDONLY);
if (fd == -1) {
status = EXIT_FAILURE;
continue;
}
if ((opts ? fdatasync(fd) : fsync(fd))) {
//status = EXIT_FAILURE; - do we want this?
bb_simple_perror_msg(*argv);
}
close(fd);
} while (*++argv);
return status;
}
+1 -1
View File
@@ -29,7 +29,7 @@
//usage: "\n -n Don't dereference symlinks - treat like normal file"
//usage: "\n -b Make a backup of the target (if exists) before link operation"
//usage: "\n -S suf Use suffix instead of ~ when making backup files"
//usage: "\n -T 2nd arg must be a DIR"
//usage: "\n -T Treat LINK as a file, not DIR"
//usage: "\n -v Verbose"
//usage:
//usage:#define ln_example_usage
+3 -3
View File
@@ -1086,7 +1086,7 @@ int ls_main(int argc UNUSED_PARAM, char **argv)
static const char ls_longopts[] ALIGN1 =
"full-time\0" No_argument "\xff"
"group-directories-first\0" No_argument "\xfe"
"color\0" Optional_argument "\xfd"
IF_FEATURE_LS_COLOR("color\0" Optional_argument "\xfd")
;
#endif
@@ -1204,8 +1204,8 @@ int ls_main(int argc UNUSED_PARAM, char **argv)
nfiles = 0;
do {
cur = my_stat(*argv, *argv,
/* follow links on command line unless -l, -s or -F: */
!(option_mask32 & (OPT_l|OPT_s|OPT_F))
/* follow links on command line unless -l, -i, -s or -F: */
!(option_mask32 & (OPT_l|OPT_i|OPT_s|OPT_F))
/* ... or if -H: */
|| (option_mask32 & OPT_H)
/* ... or if -L, but my_stat always follows links if -L */
+5
View File
@@ -68,6 +68,11 @@ int sleep_main(int argc UNUSED_PARAM, char **argv)
if (!*argv)
bb_show_usage();
/* GNU sleep accepts "inf", "INF", "infinity" and "INFINITY" */
if (strncasecmp(argv[0], "inf", 3) == 0)
for (;;)
sleep(INT_MAX);
#if ENABLE_FEATURE_FANCY_SLEEP
# if ENABLE_FLOAT_DURATION
/* undo busybox.c setlocale */
+48 -44
View File
@@ -169,6 +169,42 @@ static const char *human_time(time_t t)
}
#if ENABLE_FEATURE_STAT_FILESYSTEM
#define FS_TYPE_LIST \
FS_TYPE(0xADFF, "affs") \
FS_TYPE(0x1CD1, "devpts") \
FS_TYPE(0x137D, "ext") \
FS_TYPE(0xEF51, "ext2") \
FS_TYPE(0xEF53, "ext2/ext3") \
FS_TYPE(0x3153464a, "jfs") \
FS_TYPE(0x58465342, "xfs") \
FS_TYPE(0xF995E849, "hpfs") \
FS_TYPE(0x9660, "isofs") \
FS_TYPE(0x4000, "isofs") \
FS_TYPE(0x4004, "isofs") \
FS_TYPE(0x137F, "minix") \
FS_TYPE(0x138F, "minix (30 char.)") \
FS_TYPE(0x2468, "minix v2") \
FS_TYPE(0x2478, "minix v2 (30 char.)") \
FS_TYPE(0x4d44, "msdos") \
FS_TYPE(0x4006, "fat") \
FS_TYPE(0x564c, "novell") \
FS_TYPE(0x6969, "nfs") \
FS_TYPE(0x9fa0, "proc") \
FS_TYPE(0x517B, "smb") \
FS_TYPE(0x012FF7B4, "xenix") \
FS_TYPE(0x012FF7B5, "sysv4") \
FS_TYPE(0x012FF7B6, "sysv2") \
FS_TYPE(0x012FF7B7, "coh") \
FS_TYPE(0x00011954, "ufs") \
FS_TYPE(0x012FD16D, "xia") \
FS_TYPE(0x5346544e, "ntfs") \
FS_TYPE(0x1021994, "tmpfs") \
FS_TYPE(0x52654973, "reiserfs") \
FS_TYPE(0x28cd3d45, "cramfs") \
FS_TYPE(0x7275, "romfs") \
FS_TYPE(0x858458f6, "ramfs") \
FS_TYPE(0x73717368, "squashfs") \
FS_TYPE(0x62656572, "sysfs")
/* Return the type of the specified file system.
* Some systems have statfvs.f_basetype[FSTYPSZ]. (AIX, HP-UX, and Solaris)
* Others have statfs.f_fstypename[MFSNAMELEN]. (NetBSD 1.5.2)
@@ -176,54 +212,22 @@ static const char *human_time(time_t t)
*/
static const char *human_fstype(uint32_t f_type)
{
static const struct types {
uint32_t type;
const char *const fs;
} humantypes[] = {
{ 0xADFF, "affs" },
{ 0x1Cd1, "devpts" },
{ 0x137D, "ext" },
{ 0xEF51, "ext2" },
{ 0xEF53, "ext2/ext3" },
{ 0x3153464a, "jfs" },
{ 0x58465342, "xfs" },
{ 0xF995E849, "hpfs" },
{ 0x9660, "isofs" },
{ 0x4000, "isofs" },
{ 0x4004, "isofs" },
{ 0x137F, "minix" },
{ 0x138F, "minix (30 char.)" },
{ 0x2468, "minix v2" },
{ 0x2478, "minix v2 (30 char.)" },
{ 0x4d44, "msdos" },
{ 0x4006, "fat" },
{ 0x564c, "novell" },
{ 0x6969, "nfs" },
{ 0x9fa0, "proc" },
{ 0x517B, "smb" },
{ 0x012FF7B4, "xenix" },
{ 0x012FF7B5, "sysv4" },
{ 0x012FF7B6, "sysv2" },
{ 0x012FF7B7, "coh" },
{ 0x00011954, "ufs" },
{ 0x012FD16D, "xia" },
{ 0x5346544e, "ntfs" },
{ 0x1021994, "tmpfs" },
{ 0x52654973, "reiserfs" },
{ 0x28cd3d45, "cramfs" },
{ 0x7275, "romfs" },
{ 0x858458f6, "ramfs" },
{ 0x73717368, "squashfs" },
{ 0x62656572, "sysfs" },
{ 0, "UNKNOWN" }
# define FS_TYPE(type, name) type,
static const uint32_t fstype[] = {
FS_TYPE_LIST
};
# undef FS_TYPE
# define FS_TYPE(type, name) name"\0"
static const char humanname[] ALIGN1 =
FS_TYPE_LIST
"UNKNOWN";
# undef FS_TYPE
int i;
for (i = 0; humantypes[i].type; ++i)
if (humantypes[i].type == f_type)
for (i = 0; i < ARRAY_SIZE(fstype); ++i)
if (fstype[i] == f_type)
break;
return humantypes[i].fs;
return nth_string(humanname, i);
}
/* "man statfs" says that statfsbuf->f_fsid is a mess */
+6 -12
View File
@@ -5,18 +5,7 @@
*
* Licensed under GPLv2 or later, see file LICENSE in this source tree.
*/
/* Usage: stty [-ag] [-F device] [setting...]
*
* Options:
* -a Write all current settings to stdout in human-readable form.
* -g Write all current settings to stdout in stty-readable form.
* -F Open and use the specified device instead of stdin
*
* If no args are given, write to stdout the baud rate and settings that
* have been changed from their defaults. Mode reading and changes
* are done on the specified device, or stdin if none was specified.
*
* David MacKenzie <djm@gnu.ai.mit.edu>
/* David MacKenzie <djm@gnu.ai.mit.edu>
*
* Special for busybox ported by Vladimir Oleynik <dzo@simtreas.ru> 2001
*/
@@ -40,6 +29,11 @@
//usage: "\n -g Print in stty-readable form"
//usage: "\n [SETTING] See manpage"
/* If no args are given, write to stdout the baud rate and settings that
* have been changed from their defaults. Mode reading and changes
* are done on the specified device, or stdin if none was specified.
*/
#include "libbb.h"
#include "common_bufsiz.h"
+71 -33
View File
@@ -20,6 +20,7 @@
//config: sync -d FILE... executes fdatasync() on each FILE.
//config: sync -f FILE... executes syncfs() on each FILE.
// APPLET_NOFORK:name main location suid_type help
//applet:IF_SYNC(APPLET_NOFORK(sync, sync, BB_DIR_BIN, BB_SUID_DROP, sync))
//kbuild:lib-$(CONFIG_SYNC) += sync.o
@@ -42,61 +43,98 @@
/* This is a NOFORK applet. Be very careful! */
int sync_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
int sync_main(int argc UNUSED_PARAM, char **argv IF_NOT_DESKTOP(UNUSED_PARAM))
#if ENABLE_FEATURE_SYNC_FANCY || ENABLE_FSYNC
static int sync_common(int opts, char **argv)
{
#if !ENABLE_FEATURE_SYNC_FANCY
/* coreutils-6.9 compat */
bb_warn_ignoring_args(argv[1]);
sync();
return EXIT_SUCCESS;
#else
unsigned opts;
int ret = EXIT_SUCCESS;
int ret;
enum {
OPT_DATASYNC = (1 << 0),
OPT_SYNCFS = (1 << 1),
};
opts = getopt32(argv, "^" "df" "\0" "d--f:f--d");
argv += optind;
/* Handle the no-argument case. */
if (!argv[0])
sync();
while (*argv) {
int fd = open_or_warn(*argv, O_RDONLY);
ret = EXIT_SUCCESS;
do {
/* GNU "sync FILE" uses O_NONBLOCK open */
int fd = open_or_warn(*argv, /*O_NOATIME |*/ O_NOCTTY | O_RDONLY | O_NONBLOCK);
/* open(NOATIME) can only be used by owner or root, don't use NOATIME here */
if (fd < 0) {
ret = EXIT_FAILURE;
goto next;
}
if (opts & OPT_DATASYNC) {
if (fdatasync(fd))
goto err;
goto do_close;
}
# if ENABLE_FEATURE_SYNC_FANCY
if (opts & OPT_SYNCFS) {
/*
* syncfs is documented to only fail with EBADF,
* which can't happen here. So, no error checks.
*/
syncfs(fd);
goto do_close;
}
if (fsync(fd)) {
err:
} else
# endif
if (((opts & OPT_DATASYNC) ? fdatasync(fd) : fsync(fd)) != 0) {
bb_simple_perror_msg(*argv);
ret = EXIT_FAILURE;
}
do_close:
close(fd);
next:
++argv;
}
argv++;
} while (*argv);
return ret;
#endif
}
#endif
#if ENABLE_SYNC
int sync_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
int sync_main(int argc UNUSED_PARAM, char **argv IF_NOT_DESKTOP(UNUSED_PARAM))
{
# if !ENABLE_FEATURE_SYNC_FANCY
/* coreutils-6.9 compat */
bb_warn_ignoring_args(argv[1]);
sync();
return EXIT_SUCCESS;
# else
unsigned opts = getopt32(argv, "^" "df" "\0" "d--f:f--d");
argv += optind;
if (!argv[0]) {
sync();
return EXIT_SUCCESS;
}
return sync_common(opts, argv);
# endif
}
#endif
/*
* Mini fsync implementation for busybox
*
* Copyright (C) 2008 Nokia Corporation. All rights reserved.
*
* Licensed under GPLv2 or later, see file LICENSE in this source tree.
*/
//config:config FSYNC
//config: bool "fsync (3.6 kb)"
//config: default y
//config: help
//config: fsync is used to flush file-related cached blocks to disk.
// APPLET_NOFORK:name main location suid_type help
//applet:IF_FSYNC(APPLET_NOFORK(fsync, fsync, BB_DIR_BIN, BB_SUID_DROP, fsync))
//kbuild:lib-$(CONFIG_FSYNC) += sync.o
//usage:#define fsync_trivial_usage
//usage: "[-d] FILE..."
//usage:#define fsync_full_usage "\n\n"
//usage: "Write all buffered blocks in FILEs to disk\n"
//usage: "\n -d Avoid syncing metadata"
#if ENABLE_FSYNC
int fsync_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
int fsync_main(int argc UNUSED_PARAM, char **argv)
{
int opts = getopt32(argv, "^" "d" "\0" "-1"/*min 1 arg*/);
argv += optind;
return sync_common(opts, argv);
}
#endif
+62 -32
View File
@@ -94,7 +94,7 @@ Misc options:
//usage: "\n -n NAME Match processes with NAME"
//usage: "\n in comm field in /proc/PID/stat"
//usage: "\n -x EXECUTABLE Match processes with this command"
//usage: "\n command in /proc/PID/cmdline"
//usage: "\n in /proc/PID/cmdline"
//usage: "\n -p FILE Match a process with PID from FILE"
//usage: "\n All specified conditions must match"
//usage: "\n-S only:"
@@ -409,7 +409,7 @@ int start_stop_daemon_main(int argc UNUSED_PARAM, char **argv)
{
unsigned opt;
char *signame;
char *startas;
char *startas = NULL;
char *chuid;
#if ENABLE_FEATURE_START_STOP_DAEMON_FANCY
// char *retry_arg = NULL;
@@ -425,10 +425,11 @@ int start_stop_daemon_main(int argc UNUSED_PARAM, char **argv)
/* -K or -S is required; they are mutually exclusive */
/* -p is required if -m is given */
/* -xpun (at least one) is required if -K is given */
/* -xa (at least one) is required if -S is given */
// /* -xa (at least one) is required if -S is given */
//WRONG: "start-stop-daemon -S -- sleep 5" is a valid invocation
/* -q turns off -v */
"\0"
"K:S:K--S:S--K:m?p:K?xpun:S?xa"
"K:S:K--S:S--K:m?p:K?xpun"
IF_FEATURE_START_STOP_DAEMON_FANCY("q-v"),
LONGOPTS
&startas, &cmdname, &signame, &userspec, &chuid, &execname, &pidfile
@@ -442,27 +443,43 @@ int start_stop_daemon_main(int argc UNUSED_PARAM, char **argv)
if (signal_nr < 0) bb_show_usage();
}
if (!(opt & OPT_a))
startas = execname;
if (!execname) /* in case -a is given and -x is not */
execname = startas;
//argc -= optind;
argv += optind;
// ARGS contains zeroth arg if -x/-a is not given, else it starts with 1st arg.
// These will try to execute "[/bin/]sleep 5":
// "start-stop-daemon -S -- sleep 5"
// "start-stop-daemon -S -x /bin/sleep -- 5"
// "start-stop-daemon -S -a sleep -- 5"
// NB: -n option does _not_ behave in this way: this will try to execute "5":
// "start-stop-daemon -S -n sleep -- 5"
if (opt & CTX_START) {
if (!execname) { /* -x is not given */
execname = startas;
if (!execname) { /* neither -x nor -a is given */
execname = argv[0];
if (!execname)
bb_show_usage();
argv++;
}
}
if (!startas) /* -a is not given: use -x EXECUTABLE or argv[0] */
startas = execname;
*--argv = startas;
}
if (execname) {
G.execname_sizeof = strlen(execname) + 1;
G.execname_cmpbuf = xmalloc(G.execname_sizeof + 1);
}
// IF_FEATURE_START_STOP_DAEMON_FANCY(
// if (retry_arg)
// retries = xatoi_positive(retry_arg);
// )
//argc -= optind;
argv += optind;
if (userspec) {
user_id = bb_strtou(userspec, NULL, 10);
if (errno)
user_id = xuname2uid(userspec);
}
/* Both start and stop need to know current processes */
do_procinit();
@@ -471,9 +488,11 @@ int start_stop_daemon_main(int argc UNUSED_PARAM, char **argv)
return (opt & OPT_OKNODO) ? 0 : (i <= 0);
}
/* else: CTX_START (-S). execname can't be NULL. */
if (G.found_procs) {
if (!QUIET)
printf("%s is already running\n%u\n", execname, (unsigned)G.found_procs->pid);
printf("%s is already running\n", execname);
return !(opt & OPT_OKNODO);
}
@@ -482,35 +501,51 @@ int start_stop_daemon_main(int argc UNUSED_PARAM, char **argv)
xstat(execname, &G.execstat);
#endif
*--argv = startas;
if (opt & OPT_BACKGROUND) {
#if BB_MMU
bb_daemonize(DAEMON_DEVNULL_STDIO + DAEMON_CLOSE_EXTRA_FDS + DAEMON_DOUBLE_FORK);
/* DAEMON_DEVNULL_STDIO is superfluous -
* it's always done by bb_daemonize() */
#else
/* Daemons usually call bb_daemonize_or_rexec(), but SSD can do
* without: SSD is not itself a daemon, it _execs_ a daemon.
* The usual NOMMU problem of "child can't run indefinitely,
* it must exec" does not bite us: we exec anyway.
*
* bb_daemonize(DAEMON_DEVNULL_STDIO | DAEMON_CLOSE_EXTRA_FDS | DAEMON_DOUBLE_FORK)
* can be used on MMU systems, but use of vfork()
* is preferable since we want to create pidfile
* _before_ parent returns, and vfork() on Linux
* ensures that (by blocking parent until exec in the child).
*/
pid_t pid = xvfork();
if (pid != 0) {
/* parent */
/* Parent */
/* why _exit? the child may have changed the stack,
* so "return 0" may do bad things */
* so "return 0" may do bad things
*/
_exit(EXIT_SUCCESS);
}
/* Child */
setsid(); /* detach from controlling tty */
/* Redirect stdio to /dev/null, close extra FDs */
bb_daemon_helper(DAEMON_DEVNULL_STDIO + DAEMON_CLOSE_EXTRA_FDS);
#endif
/* On Linux, session leader can acquire ctty
* unknowingly, by opening a tty.
* Prevent this: stop being a session leader.
*/
pid = xvfork();
if (pid != 0)
_exit(EXIT_SUCCESS); /* Parent */
}
if (opt & OPT_MAKEPID) {
/* User wants _us_ to make the pidfile */
write_pidfile(pidfile);
}
#if ENABLE_FEATURE_START_STOP_DAEMON_FANCY
if (opt & OPT_NICELEVEL) {
/* Set process priority (must be before OPT_c) */
int prio = getpriority(PRIO_PROCESS, 0) + xatoi_range(opt_N, INT_MIN/2, INT_MAX/2);
if (setpriority(PRIO_PROCESS, 0, prio) < 0) {
bb_perror_msg_and_die("setpriority(%d)", prio);
}
}
#endif
if (opt & OPT_c) {
struct bb_uidgid_t ugid;
parse_chown_usergroup_or_die(&ugid, chuid);
@@ -525,15 +560,10 @@ int start_stop_daemon_main(int argc UNUSED_PARAM, char **argv)
setgroups(1, &ugid.gid);
}
}
#if ENABLE_FEATURE_START_STOP_DAEMON_FANCY
if (opt & OPT_NICELEVEL) {
/* Set process priority */
int prio = getpriority(PRIO_PROCESS, 0) + xatoi_range(opt_N, INT_MIN/2, INT_MAX/2);
if (setpriority(PRIO_PROCESS, 0, prio) < 0) {
bb_perror_msg_and_die("setpriority(%d)", prio);
}
}
#endif
execvp(startas, argv);
/* Try:
* strace -oLOG start-stop-daemon -S -x /bin/usleep -a qwerty 500000
* should exec "/bin/usleep", but argv[0] should be "qwerty":
*/
execvp(execname, argv);
bb_perror_msg_and_die("can't execute '%s'", startas);
}
+1
View File
@@ -183,6 +183,7 @@ dd compatibility options:
iflag=skip_bytes| yes | |
iflag=fullblock | yes | |
oflag=seek_bytes| yes | |
oflag=append | yes | |
df POSIX options
option | exists | compliant | remarks
+31 -10
View File
@@ -275,18 +275,21 @@ typedef struct tsplitter_s {
| TC_STRING | TC_NUMBER | TC_UOPPOST)
#define TC_CONCAT2 (TC_OPERAND | TC_UOPPRE)
#define OF_RES1 0x010000
#define OF_RES2 0x020000
#define OF_STR1 0x040000
#define OF_STR2 0x080000
#define OF_NUM1 0x100000
#define OF_CHECKED 0x200000
#define OF_RES1 0x010000
#define OF_RES2 0x020000
#define OF_STR1 0x040000
#define OF_STR2 0x080000
#define OF_NUM1 0x100000
#define OF_CHECKED 0x200000
#define OF_REQUIRED 0x400000
/* combined operator flags */
#define xx 0
#define xV OF_RES2
#define xS (OF_RES2 | OF_STR2)
#define Vx OF_RES1
#define Rx (OF_RES1 | OF_NUM1 | OF_REQUIRED)
#define VV (OF_RES1 | OF_RES2)
#define Nx (OF_RES1 | OF_NUM1)
#define NV (OF_RES1 | OF_NUM1 | OF_RES2)
@@ -425,7 +428,7 @@ static const uint32_t tokeninfo[] = {
0,
0, /* \n */
ST_IF, ST_DO, ST_FOR, OC_BREAK,
OC_CONTINUE, OC_DELETE|Vx, OC_PRINT,
OC_CONTINUE, OC_DELETE|Rx, OC_PRINT,
OC_PRINTF, OC_NEXT, OC_NEXTFILE,
OC_RETURN|Vx, OC_EXIT|Nx,
ST_WHILE,
@@ -593,7 +596,7 @@ static const char EMSG_UNEXP_EOS[] ALIGN1 = "Unexpected end of string";
static const char EMSG_UNEXP_TOKEN[] ALIGN1 = "Unexpected token";
static const char EMSG_DIV_BY_ZERO[] ALIGN1 = "Division by zero";
static const char EMSG_INV_FMT[] ALIGN1 = "Invalid format specifier";
static const char EMSG_TOO_FEW_ARGS[] ALIGN1 = "Too few arguments for builtin";
static const char EMSG_TOO_FEW_ARGS[] ALIGN1 = "Too few arguments";
static const char EMSG_NOT_ARRAY[] ALIGN1 = "Not an array";
static const char EMSG_POSSIBLE_ERROR[] ALIGN1 = "Possible syntax error";
static const char EMSG_UNDEF_FUNC[] ALIGN1 = "Call to undefined function";
@@ -1265,7 +1268,7 @@ static node *parse_expr(uint32_t iexp)
debug_printf_parse("%s(%x)\n", __func__, iexp);
sn.info = PRIMASK;
sn.r.n = glptr = NULL;
sn.r.n = sn.a.n = glptr = NULL;
xtc = TC_OPERAND | TC_UOPPRE | TC_REGEXP | iexp;
while (!((tc = next_token(xtc)) & iexp)) {
@@ -1287,6 +1290,7 @@ static node *parse_expr(uint32_t iexp)
|| ((t_info == vn->info) && ((t_info & OPCLSMASK) == OC_COLON))
) {
vn = vn->a.n;
if (!vn->a.n) syntax_error(EMSG_UNEXP_TOKEN);
}
if ((t_info & OPCLSMASK) == OC_TERNARY)
t_info += P(6);
@@ -1425,7 +1429,11 @@ static void chain_expr(uint32_t info)
node *n;
n = chain_node(info);
n->l.n = parse_expr(TC_OPTERM | TC_GRPTERM);
if ((info & OF_REQUIRED) && !n->l.n)
syntax_error(EMSG_TOO_FEW_ARGS);
if (t_tclass & TC_GRPTERM)
rollback_token();
}
@@ -1605,12 +1613,25 @@ static void parse_program(char *p)
f = newfunc(t_string);
f->body.first = NULL;
f->nargs = 0;
while (next_token(TC_VARIABLE | TC_SEQTERM) & TC_VARIABLE) {
/* Match func arg list: a comma sep list of >= 0 args, and a close paren */
while (next_token(TC_VARIABLE | TC_SEQTERM | TC_COMMA)) {
/* Either an empty arg list, or trailing comma from prev iter
* must be followed by an arg */
if (f->nargs == 0 && t_tclass == TC_SEQTERM)
break;
/* TC_SEQSTART/TC_COMMA must be followed by TC_VARIABLE */
if (t_tclass != TC_VARIABLE)
syntax_error(EMSG_UNEXP_TOKEN);
v = findvar(ahash, t_string);
v->x.aidx = f->nargs++;
/* Arg followed either by end of arg list or 1 comma */
if (next_token(TC_COMMA | TC_SEQTERM) & TC_SEQTERM)
break;
if (t_tclass != TC_COMMA)
syntax_error(EMSG_UNEXP_TOKEN);
}
seq = &f->body;
chain_group();
+17 -15
View File
@@ -371,25 +371,25 @@ static int get_address(const char *my_str, int *linenum, regex_t ** regex)
/* Grab a filename. Whitespace at start is skipped, then goes to EOL. */
static int parse_file_cmd(/*sed_cmd_t *sed_cmd,*/ const char *filecmdstr, char **retval)
{
int start = 0, idx, hack = 0;
const char *start;
const char *eol;
/* Skip whitespace, then grab filename to end of line */
while (isspace(filecmdstr[start]))
start++;
idx = start;
while (filecmdstr[idx] && filecmdstr[idx] != '\n')
idx++;
/* If lines glued together, put backslash back. */
if (filecmdstr[idx] == '\n')
hack = 1;
if (idx == start)
start = skip_whitespace(filecmdstr);
eol = strchrnul(start, '\n');
if (eol == start)
bb_error_msg_and_die("empty filename");
*retval = xstrndup(filecmdstr+start, idx-start+hack+1);
if (hack)
(*retval)[idx] = '\\';
return idx;
if (*eol) {
/* If lines glued together, put backslash back. */
*retval = xstrndup(start, eol-start + 1);
(*retval)[eol-start] = '\\';
} else {
/* eol is NUL */
*retval = xstrdup(start);
}
return eol - filecmdstr;
}
static int parse_subst_cmd(sed_cmd_t *sed_cmd, const char *substr)
@@ -1097,6 +1097,8 @@ static void process_files(void)
int old_matched, matched;
old_matched = sed_cmd->in_match;
if (!old_matched)
sed_cmd->end_line = sed_cmd->end_line_orig;
/* Determine if this command matches this line: */
+2123 -2250
View File
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -4,7 +4,7 @@
# Repeat.
umountcnt=2
writeout=0 # increase if your kernel doesn ot guarantee writes to complete
writeout=0 # increase if your kernel does not guarantee writes to complete
# No /usr - we are expecting all binaries to be accessible
# from root fs alone
+4
View File
@@ -55,6 +55,10 @@ case "$1" in
echo "Recreating $RESOLV_CONF"
# If the file is a symlink somewhere (like /etc/resolv.conf
# pointing to /run/resolv.conf), make sure things work.
if test -L "$RESOLV_CONF"; then
# If it's a dangling symlink, try to create the target.
test -e "$RESOLV_CONF" || touch "$RESOLV_CONF"
fi
realconf=$(readlink -f "$RESOLV_CONF" 2>/dev/null || echo "$RESOLV_CONF")
tmpfile="$realconf-$$"
> "$tmpfile"
+49 -38
View File
@@ -44,7 +44,7 @@ interface eth0
#notify_file # default: no script
#notify_file dumpleases # useful for debugging
# The following are bootp specific options
# The following are BOOTP specific options
# next server to use in bootstrap
#siaddr 192.168.0.22 # default: 0.0.0.0 (none)
# tftp server name
@@ -52,9 +52,14 @@ interface eth0
# tftp file to download (e.g. kernel image)
#boot_file /var/nfs_root # default: none
# NOTE: "boot_file FILE" and "opt bootfile FILE" are conceptually the same,
# but "boot_file" goes into BOOTP-defined fixed-size field in the packet,
# whereas "opt bootfile" goes into DHCP option 0x43.
# Same for "sname HOST" and "opt tftp HOST".
# Static leases map
#static_lease 00:60:08:11:CE:4E 192.168.0.54
#static_lease 00:60:08:11:CE:3E 192.168.0.44
#static_lease 00:60:08:11:CE:3E 192.168.0.44 optional_hostname
# The remainder of options are DHCP options and can be specified with the
# keyword 'opt' or 'option'. If an option can take multiple items, such
@@ -74,43 +79,49 @@ option staticroutes 10.0.0.0/8 10.127.0.1, 10.11.12.0/24 10.11.12.1
option 0x08 01020304 # option 8: "cookie server IP addr: 1.2.3.4"
option 14 "dumpfile"
# Currently supported options (for more info, see options.c):
#opt lease NUM
#opt subnet IP
#opt broadcast IP
#opt router IP_LIST
#opt ipttl NUM
#opt mtu NUM
#opt hostname STRING # client's hostname
#opt domain STRING # client's domain suffix
#opt search STRING_LIST # search domains
#opt nisdomain STRING
#opt timezone NUM # (localtime - UTC_time) in seconds. signed
#opt tftp STRING # tftp server name
#opt bootfile STRING # tftp file to download (e.g. kernel image)
#opt bootsize NUM # size of that file
#opt rootpath STRING # (NFS) path to mount as root fs
#opt wpad STRING
#opt serverid IP # default: server's IP
#opt message STRING # error message (udhcpd sends it on success too)
#opt vlanid NUM # 802.1P VLAN ID
#opt vlanpriority NUM # 802.1Q VLAN priority
# Currently supported options [hex option value] (for more info, see options.c):
#opt lease NUM # [0x33]
#opt subnet IP # [0x01]
#opt broadcast IP # [0x1c]
#opt router IP_LIST # [0x03]
#opt ipttl NUM # [0x17]
#opt mtu NUM # [0x1a]
#opt hostname STRING # [0x0c] client's hostname
#opt domain STRING # [0x0f] client's domain suffix
#opt search STRING_LIST # [0x77] search domains
#opt nisdomain STRING # [0x28]
#opt timezone NUM # [0x02] (localtime - UTC_time) in seconds. signed
#opt tftp STRING # [0x42] tftp server name
#opt bootfile STRING # [0x43] tftp file to download (e.g. kernel image)
#opt bootsize NUM # [0x0d] size of that file
#opt rootpath STRING # [0x11] (NFS) path to mount as root fs
#opt wpad STRING # [0xfc] Web Proxy Auto Discovery Protocol
#opt serverid IP # [0x36] default: server's IP
#opt message STRING # [0x38] error message (udhcpd sends it on success too)
#opt vlanid NUM # [0x84] 802.1P VLAN ID
#opt vlanpriority NUM # [0x85] 802.1Q VLAN priority
# RFC 5071: PXELINUX Options
#opt 0xd0 F100747E # [0xd0] magic
#opt pxeconffile STRING # [0xd1]
#opt pxepathprefix STRING # [0xd2]
#opt reboottime NUM # [0xd3] bootstrap timeout
# Options specifying server(s)
#opt dns IP_LIST
#opt wins IP_LIST
#opt nissrv IP_LIST
#opt ntpsrv IP_LIST
#opt lprsrv IP_LIST
#opt swapsrv IP
#opt dns IP_LIST # [0x06]
#opt wins IP_LIST # [0x2c]
#opt nissrv IP_LIST # [0x29]
#opt ntpsrv IP_LIST # [0x2a]
#opt lprsrv IP_LIST # [0x09]
#opt swapsrv IP # [0x10]
# Options specifying routes
#opt routes IP_PAIR_LIST
#opt staticroutes STATIC_ROUTES # RFC 3442 classless static route option
#opt msstaticroutes STATIC_ROUTES # same, using MS option number
#opt routes IP_PAIR_LIST # [0x21]
#opt staticroutes STATIC_ROUTES # [0x79] RFC 3442 classless static route option
#opt msstaticroutes STATIC_ROUTES # [0xf9] same, using MS option number
# Obsolete options, no longer supported
#opt logsrv IP_LIST # 704/UDP log server (not syslog!)
#opt namesrv IP_LIST # IEN 116 name server, obsolete (August 1979!!!)
#opt cookiesrv IP_LIST # RFC 865 "quote of the day" server, rarely (never?) used
#opt timesrv IP_LIST # RFC 868 time server, rarely (never?) used
#opt logsrv IP_LIST # [0x07] 704/UDP log server (not syslog!)
#opt namesrv IP_LIST # [0x05] IEN 116 name server, obsolete (August 1979!!!)
#opt cookiesrv IP_LIST # [0x08] RFC 865 "quote of the day" server, rarely (never?) used
#opt timesrv IP_LIST # [0x04] RFC 868 time server, rarely (never?) used
# TODO: in development
#opt userclass STRING # RFC 3004. set of LASCII strings. "I am a printer" etc
#opt sipserv STRING LIST # RFC 3361. flag byte, then: 0: domain names, 1: IP addrs
#opt userclass STRING # [0x4d] RFC 3004. set of LASCII strings. "I am a printer" etc
#opt sipsrv STRING LIST # [0x78] RFC 3361. flag byte, then: 0: domain names, 1: IP addrs
#opt ip6rd .... # [0xd4] IPv6 rapid deployment
@@ -26,6 +26,30 @@ exec 2>&1
test "$interface" || exit 1
test "$ip" || exit 1
# some servers do not return subnet option.
# guess it for standard private networks.
if ! test "$mask"; then
case "$ip" in
10.*)
mask=8;;
192.168.*)
mask=16;;
#172.16-31.x.x
172.1[6789].*)
mask=12;;
172.2[0123456789].*)
mask=12;;
172.3[01].*)
mask=12;;
esac
fi
# some servers do not return router option.
# assume DHCP server is the router.
if ! test "$router"; then
test "$serverid" && router="$serverid"
fi
{
echo "let cfg=cfg+1"
test "$interface" && echo "if[\$cfg]='$interface'"
+2 -2
View File
@@ -8,9 +8,9 @@ pwd="$PWD"
if="${PWD##*/dhcp_}"
echo "* Upping iface $if"
ip link set dev "$if" up
ip link set dev "$if" up || exec sleep 5
echo "* Starting udhcpc"
echo "* Starting udhcpc on $if [$$]"
exec \
env - PATH="$PATH" \
softlimit \
+2 -2
View File
@@ -8,12 +8,12 @@ pwd="$PWD"
if="${PWD##*/dhcpd_}"
echo "* Upping iface $if"
ip link set dev $if up
ip link set dev $if up || exec sleep 5
>>udhcpd.leases
sed 's/^interface.*$/interface '"$if/" -i udhcpd.conf
echo "* Starting udhcpd"
echo "* Starting udhcpd on $if [$$]"
exec \
env - PATH="$PATH" \
softlimit \
+3 -2
View File
@@ -9,14 +9,14 @@ pwd="$PWD"
if="${PWD##*/ifplugd_}"
echo "* Upping iface $if"
ip link set dev "$if" up
ip link set dev "$if" up || exec sleep 5
echo "* Starting ifplugd on $if [$$]"
exec \
env - PATH="$PATH" \
softlimit \
setuidgid root \
ifplugd -aqlns -t3 -u8 -d8 -i "$if" -r "$pwd/ifplugd_handler"
ifplugd -aqlMns -t3 -u8 -d8 -i "$if" -r "$pwd/ifplugd_handler"
# We use -t3 to wake ifplugd up less often.
# If after three tests (3*3=9 > 8) link state seen to be different,
@@ -29,6 +29,7 @@ ifplugd -aqlns -t3 -u8 -d8 -i "$if" -r "$pwd/ifplugd_handler"
# from pointlessly trying to get a lease.
# -q means that stopping monitoring does not stop dhcp/zcip/etc:
# presumably, admin decided to control them manually.
# -M prevents frequent respawning if device does not exist (yet?)
#-a Don't up interface automatically
#-p Don't run "up" script on startup
+3 -2
View File
@@ -8,12 +8,13 @@ pwd="$PWD"
if="${PWD##*/dhcp_}"
echo "* Upping iface $if"
ip link set dev "$if" up
# "or sleep" idiom prevents rapid respawning if iface does not exist
ip link set dev "$if" up || exec sleep 5
##echo "* Powersave disable on $if"
##iw dev "$if" set power_save off
echo "* Starting wpa_supplicant"
echo "* Starting wpa_supplicant on $if [$$]"
exec \
env - PATH="$PATH" \
softlimit \
+2 -2
View File
@@ -8,9 +8,9 @@ pwd="$PWD"
if="${PWD##*/zcip_}"
echo "* Upping iface $if"
ip link set dev "$if" up
ip link set dev "$if" up || exec sleep 5
echo "* Starting zcip"
echo "* Starting zcip on $if [$$]"
exec \
env - PATH="$PATH" \
softlimit \
+6
View File
@@ -1467,6 +1467,12 @@ int find_main(int argc UNUSED_PARAM, char **argv)
break;
if (!saved[1])
break; /* it is "-" */
if (saved[1] == '-' && !saved[2]) {
/* it is "--" */
/* Try: find -- /dev/null */
saved = *++past_HLP;
break;
}
if ((saved+1)[strspn(saved+1, "HLP")] != '\0')
break;
}
+15 -6
View File
@@ -404,7 +404,7 @@ static int grep_file(FILE *file)
#endif
) {
if (option_mask32 & OPT_x) {
found = (gl->matched_range.rm_so == 0
found |= (gl->matched_range.rm_so == 0
&& match_at[gl->matched_range.rm_eo] == '\0');
} else
if (!(option_mask32 & OPT_w)) {
@@ -443,15 +443,23 @@ static int grep_file(FILE *file)
}
}
}
/* If it's non-inverted search, we can stop
* at first match */
if (found && !invert_search)
goto do_found;
/* If it's a non-inverted search, we can stop
* at first match and report it.
* If it's an inverted search, we can move on
* to the next line of input, ignoring the
* rest of the patterns.
*/
if (found) {
//if (invert_search)
// goto do_not_found;
//goto do_found;
break; // this accomplishes both
}
pattern_ptr = pattern_ptr->link;
} /* while (pattern_ptr) */
if (found ^ invert_search) {
do_found:
//do_found:
/* keep track of matches */
nmatches++;
@@ -552,6 +560,7 @@ static int grep_file(FILE *file)
}
#if ENABLE_FEATURE_GREP_CONTEXT
else { /* no match */
//do_not_found:
/* if we need to print some context lines after the last match, do so */
if (print_n_lines_after) {
print_line(line, strlen(line), linenum, '-');
+7 -7
View File
@@ -516,23 +516,23 @@ static int xargs_ask_confirmation(void)
//usage: "[OPTIONS] [PROG ARGS]"
//usage:#define xargs_full_usage "\n\n"
//usage: "Run PROG on every item given by stdin\n"
//usage: IF_FEATURE_XARGS_SUPPORT_CONFIRMATION(
//usage: "\n -p Ask user whether to run each command"
//usage: )
//usage: "\n -r Don't run command if input is empty"
//usage: IF_FEATURE_XARGS_SUPPORT_ZERO_TERM(
//usage: "\n -0 Input is separated by NULs"
//usage: )
//usage: IF_FEATURE_XARGS_SUPPORT_ARGS_FILE(
//usage: "\n -a FILE Read from FILE instead of stdin"
//usage: )
//usage: "\n -r Don't run command if input is empty"
//usage: "\n -t Print the command on stderr before execution"
//usage: "\n -e[STR] STR stops input processing"
//usage: "\n -n N Pass no more than N args to PROG"
//usage: "\n -s N Pass command line of no more than N bytes"
//usage: IF_FEATURE_XARGS_SUPPORT_CONFIRMATION(
//usage: "\n -p Ask user whether to run each command"
//usage: )
//usage: "\n -E STR,-e[STR] STR stops input processing"
//usage: IF_FEATURE_XARGS_SUPPORT_REPL_STR(
//usage: "\n -I STR Replace STR within PROG ARGS with input line"
//usage: )
//usage: "\n -n N Pass no more than N args to PROG"
//usage: "\n -s N Pass command line of no more than N bytes"
//usage: IF_FEATURE_XARGS_SUPPORT_PARALLEL(
//usage: "\n -P N Run up to N PROGs in parallel"
//usage: )
+6
View File
@@ -235,6 +235,12 @@ typedef struct transformer_state_t {
off_t bytes_in; /* used in unzip code only: needs to know packed size */
uint32_t crc32;
time_t mtime; /* gunzip code may set this on exit */
union { /* if we read magic, it's saved here */
uint8_t b[8];
uint16_t b16[4];
uint32_t b32[2];
} magic;
} transformer_state_t;
void init_transformer_state(transformer_state_t *xstate) FAST_FUNC;
+33 -11
View File
@@ -688,6 +688,7 @@ int xsocket_stream(len_and_sockaddr **lsap) FAST_FUNC;
/* NB: these set SO_REUSEADDR before bind */
int create_and_bind_stream_or_die(const char *bindaddr, int port) FAST_FUNC;
int create_and_bind_dgram_or_die(const char *bindaddr, int port) FAST_FUNC;
int create_and_bind_to_netlink(int proto, int grp, unsigned rcvbuf) FAST_FUNC;
/* Create client TCP socket connected to peer:port. Peer cannot be NULL.
* Peer can be numeric IP ("N.N.N.N"), numeric IPv6 address or hostname,
* and can have ":PORT" suffix (for IPv6 use "[X:X:...:X]:PORT").
@@ -881,6 +882,7 @@ extern ssize_t open_read_close(const char *filename, void *buf, size_t maxsz) FA
extern char *xmalloc_reads(int fd, size_t *maxsz_p) FAST_FUNC;
/* Reads block up to *maxsz_p (default: INT_MAX - 4095) */
extern void *xmalloc_read(int fd, size_t *maxsz_p) FAST_FUNC RETURNS_MALLOC;
extern void *xmalloc_read_with_initial_buf(int fd, size_t *maxsz_p, char *buf, size_t total) FAST_FUNC;
/* Returns NULL if file can't be opened (default max size: INT_MAX - 4095) */
extern void *xmalloc_open_read_close(const char *filename, size_t *maxsz_p) FAST_FUNC RETURNS_MALLOC;
/* Never returns NULL */
@@ -1040,9 +1042,11 @@ uint16_t xatou16(const char *numstr) FAST_FUNC;
#if ENABLE_FLOAT_DURATION
typedef double duration_t;
void sleep_for_duration(duration_t duration) FAST_FUNC;
#define DURATION_FMT "f"
#else
typedef unsigned duration_t;
#define sleep_for_duration(duration) sleep(duration)
#define DURATION_FMT "u"
#endif
duration_t parse_duration_str(char *str) FAST_FUNC;
@@ -1201,11 +1205,11 @@ void set_task_comm(const char *comm) FAST_FUNC;
* to /dev/null if they are not.
*/
enum {
DAEMON_CHDIR_ROOT = 1,
DAEMON_DEVNULL_STDIO = 2,
DAEMON_CLOSE_EXTRA_FDS = 4,
DAEMON_ONLY_SANITIZE = 8, /* internal use */
DAEMON_DOUBLE_FORK = 16, /* double fork to avoid controlling tty */
DAEMON_CHDIR_ROOT = 1 << 0,
DAEMON_DEVNULL_STDIO = 1 << 1,
DAEMON_CLOSE_EXTRA_FDS = 1 << 2,
DAEMON_ONLY_SANITIZE = 1 << 3, /* internal use */
//DAEMON_DOUBLE_FORK = 1 << 4, /* double fork to avoid controlling tty */
};
#if BB_MMU
enum { re_execed = 0 };
@@ -1296,9 +1300,13 @@ llist_t *llist_find_str(llist_t *first, const char *str) FAST_FUNC;
/* True only if we created pidfile which is *file*, not /dev/null etc */
extern smallint wrote_pidfile;
void write_pidfile(const char *path) FAST_FUNC;
void write_pidfile_std_path_and_ext(const char *path) FAST_FUNC;
void remove_pidfile_std_path_and_ext(const char *path) FAST_FUNC;
#define remove_pidfile(path) do { if (wrote_pidfile) unlink(path); } while (0)
#else
enum { wrote_pidfile = 0 };
#define write_pidfile_std_path_and_ext(path) ((void)0)
#define remove_pidfile_std_path_and_ext(path) ((void)0)
#define write_pidfile(path) ((void)0)
#define remove_pidfile(path) ((void)0)
#endif
@@ -1310,7 +1318,6 @@ enum {
LOGMODE_BOTH = LOGMODE_SYSLOG + LOGMODE_STDIO,
};
extern const char *msg_eol;
extern smallint syslog_level;
extern smallint logmode;
extern uint8_t xfunc_error_retval;
extern void (*die_func)(void);
@@ -1330,6 +1337,14 @@ void bb_verror_msg(const char *s, va_list p, const char *strerr) FAST_FUNC;
void bb_die_memory_exhausted(void) NORETURN FAST_FUNC;
void bb_logenv_override(void) FAST_FUNC;
#if ENABLE_FEATURE_SYSLOG_INFO
void bb_info_msg(const char *s, ...) __attribute__ ((format (printf, 1, 2))) FAST_FUNC;
void bb_vinfo_msg(const char *s, va_list p) FAST_FUNC;
#else
#define bb_info_msg bb_error_msg
#define bb_vinfo_msg(s,p) bb_verror_msg(s,p,NULL)
#endif
/* We need to export XXX_main from libbusybox
* only if we build "individual" binaries
*/
@@ -1341,7 +1356,7 @@ void bb_logenv_override(void) FAST_FUNC;
/* Embedded script support */
char *get_script_content(unsigned n) FAST_FUNC;
int scripted_main(int argc, char** argv);
int scripted_main(int argc, char** argv) MAIN_EXTERNALLY_VISIBLE;
/* Applets which are useful from another applets */
int bb_cat(char** argv) FAST_FUNC;
@@ -1446,17 +1461,19 @@ extern void bb_warn_ignoring_args(char *arg) FAST_FUNC;
extern int get_linux_version_code(void) FAST_FUNC;
extern char *query_loop(const char *device) FAST_FUNC;
extern int del_loop(const char *device) FAST_FUNC;
char *query_loop(const char *device) FAST_FUNC;
int get_free_loop(void) FAST_FUNC;
int del_loop(const char *device) FAST_FUNC;
/*
* If *devname is not NULL, use that name, otherwise try to find free one,
* malloc and return it in *devname.
* return value is the opened fd to the loop device, or < on error
*/
extern int set_loop(char **devname, const char *file, unsigned long long offset, unsigned flags) FAST_FUNC;
int set_loop(char **devname, const char *file, unsigned long long offset, unsigned flags) FAST_FUNC;
/* These constants match linux/loop.h (without BB_ prefix): */
#define BB_LO_FLAGS_READ_ONLY 1
#define BB_LO_FLAGS_AUTOCLEAR 4
#define BB_LO_FLAGS_PARTSCAN 8
/* Returns malloced str */
char *bb_ask_noecho(int fd, int timeout, const char *prompt) FAST_FUNC;
@@ -1828,7 +1845,12 @@ struct smaprec {
unsigned long stack;
unsigned long smap_pss, smap_swap;
unsigned long smap_size;
unsigned long smap_start;
// For mixed 32/64 userspace, 32-bit pmap still needs
// 64-bit field here to correctly show 64-bit processes:
unsigned long long smap_start;
// (strictly speaking, other fields need to be wider too,
// but they are in kbytes, not bytes, and they hold sizes,
// not start addresses, sizes tend to be less than 4 terabytes)
char smap_mode[5];
char *smap_name;
};
+6 -5
View File
@@ -123,16 +123,16 @@ void FAST_FUNC bb_show_usage(void)
{
if (ENABLE_SHOW_USAGE) {
#ifdef SINGLE_APPLET_STR
/* Imagine that this applet is "true". Dont suck in printf! */
/* Imagine that this applet is "true". Dont link in printf! */
const char *usage_string = unpack_usage_messages();
if (usage_string) {
if (*usage_string == '\b') {
full_write2_str("No help available.\n\n");
full_write2_str("No help available\n");
} else {
full_write2_str("Usage: "SINGLE_APPLET_STR" ");
full_write2_str(usage_string);
full_write2_str("\n\n");
full_write2_str("\n");
}
if (ENABLE_FEATURE_CLEAN_UP)
dealloc_usage_messages((char*)usage_string);
@@ -149,9 +149,9 @@ void FAST_FUNC bb_show_usage(void)
ap--;
}
full_write2_str(bb_banner);
full_write2_str(" multi-call binary.\n");
full_write2_str(" multi-call binary.\n"); /* common string */
if (*p == '\b')
full_write2_str("\nNo help available.\n\n");
full_write2_str("\nNo help available\n");
else {
full_write2_str("\nUsage: ");
full_write2_str(applet_name);
@@ -770,6 +770,7 @@ static int find_script_by_name(const char *name)
return -1;
}
int scripted_main(int argc UNUSED_PARAM, char **argv) MAIN_EXTERNALLY_VISIBLE;
int scripted_main(int argc UNUSED_PARAM, char **argv)
{
int script = find_script_by_name(applet_name);
+1 -1
View File
@@ -67,7 +67,7 @@ unsigned FAST_FUNC cap_name_to_number(const char *cap)
goto found;
}
for (i = 0; i < ARRAY_SIZE(capabilities); i++) {
if (strcasecmp(capabilities[i], cap) != 0)
if (strcasecmp(capabilities[i], cap) == 0)
goto found;
}
bb_error_msg_and_die("unknown capability '%s'", cap);
+8 -5
View File
@@ -18,7 +18,7 @@
* was seen to cause largish delays when user tries to ^C a file copy.
* Let's use a saner size.
* Note: needs to be >= max(CONFIG_FEATURE_COPYBUF_KB),
* or else "copy to eof" code will use neddlesly short reads.
* or else "copy to eof" code will use needlesly short reads.
*/
#define SENDFILE_BIGBUF (16*1024*1024)
@@ -60,10 +60,13 @@ static off_t bb_full_fd_action(int src_fd, int dst_fd, off_t size)
ssize_t rd;
if (sendfile_sz) {
rd = sendfile(dst_fd, src_fd, NULL,
size > sendfile_sz ? sendfile_sz : size);
if (rd >= 0)
goto read_ok;
/* dst_fd == -1 is a fake, else... */
if (dst_fd >= 0) {
rd = sendfile(dst_fd, src_fd, NULL,
size > sendfile_sz ? sendfile_sz : size);
if (rd >= 0)
goto read_ok;
}
sendfile_sz = 0; /* do not try sendfile anymore */
}
#if CONFIG_FEATURE_COPYBUF_KB > 4
+13 -2
View File
@@ -56,11 +56,22 @@ struct mntent* FAST_FUNC find_mount_point(const char *name, int subdir_too)
continue;
/* Is device's dev_t == name's dev_t? */
if (stat(mountEntry->mnt_fsname, &s) == 0 && s.st_rdev == devno_of_name)
if (mountEntry->mnt_fsname[0] == '/'
/* ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
* avoid stat'ing "sysfs", "proc", "none" and such,
* useless at best, can stat unrelated files at worst.
*/
&& stat(mountEntry->mnt_fsname, &s) == 0
&& s.st_rdev == devno_of_name
) {
break;
}
/* Match the directory's mount point. */
if (stat(mountEntry->mnt_dir, &s) == 0 && s.st_dev == devno_of_name)
if (stat(mountEntry->mnt_dir, &s) == 0
&& s.st_dev == devno_of_name
) {
break;
}
}
endmntent(mtab_fp);
+2 -1
View File
@@ -11,7 +11,8 @@
/*
* Write all of the supplied buffer out to a file.
* This does multiple writes as necessary.
* Returns the amount written, or -1 on an error.
* Returns the amount written, or -1 if error was seen
* on the very first write.
*/
ssize_t FAST_FUNC full_write(int fd, const void *buf, size_t len)
{
+1 -1
View File
@@ -77,7 +77,7 @@ void FAST_FUNC add_to_ino_dev_hashtable(const struct stat *statbuf, const char *
ino_dev_hashtable[i] = bucket;
}
#if ENABLE_DU || ENABLE_FEATURE_CLEAN_UP
#if ENABLE_FEATURE_CLEAN_UP
/* Clear statbuf hash table */
void FAST_FUNC reset_ino_dev_hashtable(void)
{
+15 -7
View File
@@ -70,13 +70,20 @@
#if ENABLE_UNICODE_SUPPORT
# define BB_NUL ((wchar_t)0)
# define CHAR_T wchar_t
static bool BB_isspace(CHAR_T c) { return ((unsigned)c < 256 && isspace(c)); }
static bool BB_isspace(CHAR_T c)
{
return ((unsigned)c < 256 && isspace(c));
}
# if ENABLE_FEATURE_EDITING_VI
static bool BB_isalnum_or_underscore(CHAR_T c) {
static bool BB_isalnum_or_underscore(CHAR_T c)
{
return ((unsigned)c < 256 && isalnum(c)) || c == '_';
}
# endif
static bool BB_ispunct(CHAR_T c) { return ((unsigned)c < 256 && ispunct(c)); }
static bool BB_ispunct(CHAR_T c)
{
return ((unsigned)c < 256 && ispunct(c));
}
# undef isspace
# undef isalnum
# undef ispunct
@@ -2383,13 +2390,14 @@ int FAST_FUNC read_line_input(line_input_t *st, const char *prompt, char *comman
timeout = st->timeout;
}
#if MAX_HISTORY > 0
if (state->flags & DO_HISTORY) {
# if ENABLE_FEATURE_EDITING_SAVEHISTORY
if (state->hist_file)
if (state->cnt_history == 0)
load_history(state);
if (state->hist_file)
if (state->cnt_history == 0)
load_history(state);
# endif
if (state->flags & DO_HISTORY)
state->cur_history = state->cnt_history;
}
#endif
/* prepare before init handlers */
+36 -6
View File
@@ -78,6 +78,24 @@ int FAST_FUNC del_loop(const char *device)
return rc;
}
/* Obtain an unused loop device number */
int FAST_FUNC get_free_loop(void)
{
int fd;
int loopdevno;
fd = open("/dev/loop-control", O_RDWR | O_CLOEXEC);
if (fd == -1)
return fd - 1; /* -2: "no /dev/loop-control" */
#ifndef LOOP_CTL_GET_FREE
# define LOOP_CTL_GET_FREE 0x4C82
#endif
loopdevno = ioctl(fd, LOOP_CTL_GET_FREE);
close(fd);
return loopdevno; /* can be -1 if error */
}
/* Returns opened fd to the loop device, <0 on error.
* *device is loop device to use, or if *device==NULL finds a loop device to
* mount it on and sets *device to a strdup of that loop device name. This
@@ -106,12 +124,24 @@ int FAST_FUNC set_loop(char **device, const char *file, unsigned long long offse
return -errno;
}
//TODO: use LOOP_CTL_GET_FREE instead of trying every loopN in sequence? a-la:
// fd = open("/dev/loop-control", O_RDWR);
// loopN = ioctl(fd, LOOP_CTL_GET_FREE);
//
try = *device;
if (!try) {
i = get_free_loop();
if (i == -2) { /* no /dev/loop-control */
i = 0;
try = dev;
goto old_style;
}
if (i == -1) {
close(ffd);
return -1; /* no free loop devices */
}
try = *device = xasprintf(LOOP_FORMAT, i);
goto try_to_open;
}
old_style:
/* Find a loop device. */
try = *device ? *device : dev;
/* 1048575 (0xfffff) is a max possible minor number in Linux circa 2010 */
for (i = 0; rc && i < 1048576; i++) {
sprintf(dev, LOOP_FORMAT, i);
@@ -170,7 +200,7 @@ int FAST_FUNC set_loop(char **device, const char *file, unsigned long long offse
rc = ioctl(dfd, BB_LOOP_SET_STATUS, &loopinfo);
}
if (rc != 0) {
ioctl(dfd, LOOP_CLR_FD, 0);
ioctl(dfd, LOOP_CLR_FD, 0); // actually, 0 param is unnecessary
}
}
} else {
+18
View File
@@ -38,3 +38,21 @@ void FAST_FUNC write_pidfile(const char *path)
}
close(pid_fd);
}
void FAST_FUNC write_pidfile_std_path_and_ext(const char *name)
{
char buf[sizeof(CONFIG_PID_FILE_PATH) + 64];
snprintf(buf, sizeof(buf), CONFIG_PID_FILE_PATH"/%s.pid", name);
write_pidfile(buf);
}
void FAST_FUNC remove_pidfile_std_path_and_ext(const char *name)
{
char buf[sizeof(CONFIG_PID_FILE_PATH) + 64];
if (!wrote_pidfile)
return;
snprintf(buf, sizeof(buf), CONFIG_PID_FILE_PATH"/%s.pid", name);
unlink(buf);
}
+4 -4
View File
@@ -120,11 +120,11 @@ void FAST_FUNC free_procps_scan(procps_status_t* sp)
}
#if ENABLE_FEATURE_TOPMEM || ENABLE_PMAP
static unsigned long fast_strtoul_16(char **endptr)
static unsigned long long fast_strtoull_16(char **endptr)
{
unsigned char c;
char *str = *endptr;
unsigned long n = 0;
unsigned long long n = 0;
/* Need to stop on both ' ' and '\n' */
while ((c = *str++) > ' ') {
@@ -238,8 +238,8 @@ int FAST_FUNC procps_read_smaps(pid_t pid, struct smaprec *total,
*tp = ' ';
tp = buf;
currec.smap_start = fast_strtoul_16(&tp);
currec.smap_size = (fast_strtoul_16(&tp) - currec.smap_start) >> 10;
currec.smap_start = fast_strtoull_16(&tp);
currec.smap_size = (fast_strtoull_16(&tp) - currec.smap_start) >> 10;
strncpy(currec.smap_mode, tp, sizeof(currec.smap_mode)-1);
+7 -5
View File
@@ -102,10 +102,9 @@ char* FAST_FUNC xmalloc_reads(int fd, size_t *maxsz_p)
// Read (potentially big) files in one go. File size is estimated
// by stat. Extra '\0' byte is appended.
void* FAST_FUNC xmalloc_read(int fd, size_t *maxsz_p)
void* FAST_FUNC xmalloc_read_with_initial_buf(int fd, size_t *maxsz_p, char *buf, size_t total)
{
char *buf;
size_t size, rd_size, total;
size_t size, rd_size;
size_t to_read;
struct stat st;
@@ -118,8 +117,6 @@ void* FAST_FUNC xmalloc_read(int fd, size_t *maxsz_p)
/* In order to make such files readable, we add small const */
size = (st.st_size | 0x3ff) + 1;
total = 0;
buf = NULL;
while (1) {
if (to_read < size)
size = to_read;
@@ -148,6 +145,11 @@ void* FAST_FUNC xmalloc_read(int fd, size_t *maxsz_p)
return buf;
}
void* FAST_FUNC xmalloc_read(int fd, size_t *maxsz_p)
{
return xmalloc_read_with_initial_buf(fd, maxsz_p, NULL, 0);
}
#ifdef USING_LSEEK_TO_GET_SIZE
/* Alternatively, file size can be obtained by lseek to the end.
* The code is slightly bigger. Retained in case fstat approach
+7 -1
View File
@@ -270,10 +270,16 @@ int FAST_FUNC update_passwd(const char *filename,
if (shadow && *cp == ':') {
/* /etc/shadow's field 3 (passwd change date) needs updating */
/* move past old change date */
unsigned time_days = (unsigned long)(time(NULL)) / (24*60*60);
if (time_days == 0) {
/* 0 as change date has special meaning, avoid it */
time_days = 1;
}
cp = strchrnul(cp + 1, ':');
/* "name:" + "new_passwd" + ":" + "change date" + ":rest of line" */
fprintf(new_fp, "%s%s:%u%s\n", name_colon, new_passwd,
(unsigned)(time(NULL)) / (24*60*60), cp);
time_days, cp);
} else {
/* "name:" + "new_passwd" + ":rest of line" */
fprintf(new_fp, "%s%s%s\n", name_colon, new_passwd, cp);
+20 -2
View File
@@ -12,7 +12,7 @@
#endif
#if ENABLE_FEATURE_SYSLOG
smallint syslog_level = LOG_ERR;
static smallint syslog_level = LOG_ERR;
#endif
smallint logmode = LOGMODE_STDIO;
const char *msg_eol = "\n";
@@ -154,7 +154,7 @@ void FAST_FUNC bb_verror_msg(const char *s, va_list p, const char* strerr)
}
# if ENABLE_FEATURE_SYSLOG
if (logmode & LOGMODE_SYSLOG) {
syslog(LOG_ERR, "%s", msgc);
syslog(syslog_level, "%s", msgc);
}
# endif
free(msgc);
@@ -180,3 +180,21 @@ void FAST_FUNC bb_error_msg(const char *s, ...)
bb_verror_msg(s, p, NULL);
va_end(p);
}
#if ENABLE_FEATURE_SYSLOG_INFO
void FAST_FUNC bb_vinfo_msg(const char *s, va_list p)
{
syslog_level = LOG_INFO;
bb_verror_msg(s, p, NULL);
syslog_level = LOG_ERR;
}
void FAST_FUNC bb_info_msg(const char *s, ...)
{
va_list p;
va_start(p, s);
bb_vinfo_msg(s, p);
va_end(p);
}
#endif
+17 -16
View File
@@ -263,12 +263,6 @@ void FAST_FUNC bb_daemonize_or_rexec(int flags, char **argv)
if (flags & DAEMON_CHDIR_ROOT)
xchdir("/");
if (flags & DAEMON_DEVNULL_STDIO) {
close(0);
close(1);
close(2);
}
fd = open(bb_dev_null, O_RDWR);
if (fd < 0) {
/* NB: we can be called as bb_sanitize_stdio() from init
@@ -278,8 +272,15 @@ void FAST_FUNC bb_daemonize_or_rexec(int flags, char **argv)
fd = xopen("/", O_RDONLY); /* don't believe this can fail */
}
while ((unsigned)fd < 2)
fd = dup(fd); /* have 0,1,2 open at least to /dev/null */
if (flags & DAEMON_DEVNULL_STDIO) {
xdup2(fd, 0);
xdup2(fd, 1);
xdup2(fd, 2);
} else {
/* have 0,1,2 open at least to /dev/null */
while ((unsigned)fd < 2)
fd = dup(fd);
}
if (!(flags & DAEMON_ONLY_SANITIZE)) {
@@ -292,14 +293,14 @@ void FAST_FUNC bb_daemonize_or_rexec(int flags, char **argv)
dup2(fd, 0);
dup2(fd, 1);
dup2(fd, 2);
if (flags & DAEMON_DOUBLE_FORK) {
/* On Linux, session leader can acquire ctty
* unknowingly, by opening a tty.
* Prevent this: stop being a session leader.
*/
if (fork_or_rexec(argv))
_exit(EXIT_SUCCESS); /* parent */
}
// if (flags & DAEMON_DOUBLE_FORK) {
// /* On Linux, session leader can acquire ctty
// * unknowingly, by opening a tty.
// * Prevent this: stop being a session leader.
// */
// if (fork_or_rexec(argv))
// _exit(EXIT_SUCCESS); /* parent */
// }
}
while (fd > 2) {
close(fd--);
+36
View File
@@ -11,6 +11,9 @@
#include <netinet/in.h>
#include <net/if.h>
#include <sys/un.h>
#if ENABLE_IFPLUGD || ENABLE_FEATURE_MDEV_DAEMON || ENABLE_UEVENT
# include <linux/netlink.h>
#endif
#include "libbb.h"
int FAST_FUNC setsockopt_int(int fd, int level, int optname, int optval)
@@ -130,6 +133,7 @@ unsigned FAST_FUNC bb_lookup_port(const char *port, const char *protocol, unsign
port_nr = default_port;
if (tserv)
port_nr = ntohs(tserv->s_port);
//FIXME: else: port string was garbage, but we don't report that???
}
errno = old_errno;
}
@@ -412,6 +416,38 @@ int FAST_FUNC create_and_bind_dgram_or_die(const char *bindaddr, int port)
}
#if ENABLE_IFPLUGD || ENABLE_FEATURE_MDEV_DAEMON || ENABLE_UEVENT
int FAST_FUNC create_and_bind_to_netlink(int proto, int grp, unsigned rcvbuf)
{
struct sockaddr_nl sa;
int fd;
memset(&sa, 0, sizeof(sa));
sa.nl_family = AF_NETLINK;
sa.nl_pid = getpid();
sa.nl_groups = grp;
fd = xsocket(AF_NETLINK, SOCK_DGRAM, proto);
xbind(fd, (struct sockaddr *) &sa, sizeof(sa));
close_on_exec_on(fd);
if (rcvbuf != 0) {
// SO_RCVBUFFORCE (root only) can go above net.core.rmem_max sysctl
setsockopt_SOL_SOCKET_int(fd, SO_RCVBUF, rcvbuf);
setsockopt_SOL_SOCKET_int(fd, SO_RCVBUFFORCE, rcvbuf);
# if 0
{
int z;
socklen_t zl = sizeof(z);
getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &z, &zl);
bb_error_msg("SO_RCVBUF:%d", z);
}
# endif
}
return fd;
}
#endif
int FAST_FUNC create_and_connect_stream_or_die(const char *peer, int port)
{
int fd;
+1 -1
View File
@@ -198,7 +198,7 @@ int adduser_main(int argc UNUSED_PARAM, char **argv)
pw.pw_gecos = (char *)"Linux User,,,";
/* We assume that newly created users "inherit" root's shell setting */
pw.pw_shell = (char *)get_shell_name();
pw.pw_shell = xstrdup(get_shell_name()); /* might come from getpwnam(), need to make a copy */
pw.pw_dir = NULL;
opts = getopt32long(argv, "^"
+1 -1
View File
@@ -114,7 +114,7 @@ int chpasswd_main(int argc UNUSED_PARAM, char **argv)
if (rc < 0)
bb_error_msg_and_die("an error occurred updating password for %s", name);
if (rc)
bb_error_msg("password for '%s' changed", name);
bb_info_msg("password for '%s' changed", name);
logmode = LOGMODE_STDIO;
free(name);
free(free_me);
+6 -4
View File
@@ -245,7 +245,9 @@ static void login_pam_end(pam_handle_t *pamh)
pam_strerror(pamh, pamret), pamret);
}
}
#endif /* ENABLE_PAM */
#else
# define login_pam_end(pamh) ((void)0)
#endif
static void get_username_or_die(char *buf, int size_buf)
{
@@ -471,6 +473,7 @@ int login_main(int argc UNUSED_PARAM, char **argv)
* to know _why_ login failed */
syslog(LOG_WARNING, "pam_%s call failed: %s (%d)", failed_msg,
pam_strerror(pamh, pamret), pamret);
login_pam_end(pamh);
safe_strncpy(username, "UNKNOWN", sizeof(username));
#else /* not PAM */
pw = getpwnam(username);
@@ -528,11 +531,10 @@ int login_main(int argc UNUSED_PARAM, char **argv)
if (child_pid < 0)
bb_perror_msg("vfork");
else {
if (safe_waitpid(child_pid, NULL, 0) == -1)
bb_perror_msg("waitpid");
wait_for_exitstatus(child_pid);
update_utmp_DEAD_PROCESS(child_pid);
}
IF_PAM(login_pam_end(pamh);)
login_pam_end(pamh);
return 0;
}
#endif
+5 -5
View File
@@ -43,7 +43,7 @@
static char* new_password(const struct passwd *pw, uid_t myuid, const char *algo)
{
char salt[MAX_PW_SALT_LEN];
char *orig = (char*)"";
char *orig = NULL;
char *newp = NULL;
char *cp = NULL;
char *ret = NULL; /* failure so far */
@@ -51,7 +51,7 @@ static char* new_password(const struct passwd *pw, uid_t myuid, const char *algo
if (myuid != 0 && pw->pw_passwd[0]) {
char *encrypted;
orig = bb_ask_noecho_stdin("Old password: "); /* returns ptr to static */
orig = bb_ask_noecho_stdin("Old password: "); /* returns malloced str */
if (!orig)
goto err_ret;
encrypted = pw_encrypt(orig, pw->pw_passwd, 1); /* returns malloced str */
@@ -64,11 +64,11 @@ static char* new_password(const struct passwd *pw, uid_t myuid, const char *algo
if (ENABLE_FEATURE_CLEAN_UP)
free(encrypted);
}
newp = bb_ask_noecho_stdin("New password: "); /* returns ptr to static */
newp = bb_ask_noecho_stdin("New password: "); /* returns malloced str */
if (!newp)
goto err_ret;
if (ENABLE_FEATURE_PASSWD_WEAK_CHECK
&& obscure(orig, newp, pw)
&& obscure(orig, newp, pw) /* NB: passing NULL orig is ok */
&& myuid != 0
) {
goto err_ret; /* non-root is not allowed to have weak passwd */
@@ -228,7 +228,7 @@ int passwd_main(int argc UNUSED_PARAM, char **argv)
/* LOGMODE_BOTH */
if (rc < 0)
bb_error_msg_and_die("can't update password file %s", filename);
bb_error_msg("password for %s changed by %s", name, myname);
bb_info_msg("password for %s changed by %s", name, myname);
/*if (ENABLE_FEATURE_CLEAN_UP) free(newp); - can't, it may be non-malloced */
skip:
+3 -3
View File
@@ -68,17 +68,17 @@ int sulogin_main(int argc UNUSED_PARAM, char **argv)
);
if (r < 0) {
/* ^D, ^C, timeout, or read error */
bb_error_msg("normal startup");
bb_info_msg("normal startup");
return 0;
}
if (r > 0) {
break;
}
bb_do_delay(LOGIN_FAIL_DELAY);
bb_error_msg("Login incorrect");
bb_info_msg("Login incorrect");
}
bb_error_msg("starting shell for system maintenance");
bb_info_msg("starting shell for system maintenance");
IF_SELINUX(renew_current_security_context());
+10
View File
@@ -72,6 +72,16 @@ for app; do
echo "NUM_APPLETS != 1 for ${app}: `cat include/NUM_APPLETS.h`"
mv .config busybox_config_${app}
else
if grep -q 'use larger COMMON_BUFSIZE' busybox_make_${app}.log; then
# FEATURE_USE_BSS_TAIL=y is selected, and build system
# recommends rebuilding. Do so, and print some
# debug info to see whether it works right:
tail -n1 busybox_make_${app}.log
nm busybox_unstripped | grep ' _end'
make >/dev/null 2>&1
nm busybox_unstripped | grep ' _end'
grep ^bb_common_bufsiz1 busybox_unstripped.map
fi
grep -i -e error: -e warning: busybox_make_${app}.log \
|| rm busybox_make_${app}.log
mv busybox busybox_${app}
+520 -393
View File
File diff suppressed because it is too large. Load diff
+3 -5
View File
@@ -181,9 +181,7 @@ static void crondlog(unsigned level, const char *msg, va_list va)
* need not touch syslog_level
* (they are ok with LOG_ERR default).
*/
syslog_level = LOG_INFO;
bb_verror_msg(msg, va, /* strerr: */ NULL);
syslog_level = LOG_ERR;
bb_vinfo_msg(msg, va);
}
}
@@ -1056,7 +1054,7 @@ int crond_main(int argc UNUSED_PARAM, char **argv)
log8("crond (busybox "BB_VER") started, log level %d", G.log_level);
rescan_crontab_dir();
write_pidfile(CONFIG_PID_FILE_PATH "/crond.pid");
write_pidfile_std_path_and_ext("crond");
#if ENABLE_FEATURE_CROND_SPECIAL_TIMES
if (touch_reboot_file())
start_jobs(START_ME_REBOOT); /* start @reboot entries, if any */
@@ -1108,7 +1106,7 @@ int crond_main(int argc UNUSED_PARAM, char **argv)
process_cron_update_file();
log5("wakeup dt=%ld", dt);
if (dt < -60 * 60 || dt > 60 * 60) {
bb_error_msg("time disparity of %ld minutes detected", dt / 60);
bb_info_msg("time disparity of %ld minutes detected", dt / 60);
/* and we do not run any jobs in this case */
} else if (dt > 0) {
/* Usual case: time advances forward, as expected */
+21 -6
View File
@@ -35,10 +35,12 @@ enum { STACK_SIZE = (COMMON_BUFSIZE - offsetof(struct globals, stack)) / sizeof(
base = 10; \
} while (0)
static void check_under(void)
static unsigned check_under(void)
{
if (pointer == 0)
unsigned p = pointer;
if (p == 0)
bb_error_msg_and_die("stack underflow");
return p - 1;
}
static void push(double a)
@@ -50,8 +52,9 @@ static void push(double a)
static double pop(void)
{
check_under();
return stack[--pointer];
unsigned p = check_under();
pointer = p;
return stack[p];
}
static void add(void)
@@ -91,6 +94,19 @@ static void mod(void)
{
data_t d = pop();
/* compat with dc (GNU bc 1.07.1) 1.4.1:
* $ dc -e '4 0 % p'
* dc: remainder by zero
* 0
*/
if (d == 0) {
bb_error_msg("remainder by zero");
pop();
push(0);
return;
}
/* ^^^^ without this, we simply get SIGFPE and die */
push((data_t) pop() % d);
}
@@ -171,8 +187,7 @@ static void print_stack_no_pop(void)
static void print_no_pop(void)
{
check_under();
print_base(stack[pointer-1]);
print_base(stack[check_under()]);
}
struct op {
+1 -1
View File
@@ -343,7 +343,7 @@ static const char bb_msg_variable_not_found[] ALIGN1 = "variable: %s not found";
/* Busybox stuff */
#if ENABLE_DEVFSD_VERBOSE || ENABLE_DEBUG
#define info_logger(p, fmt, args...) bb_error_msg(fmt, ## args)
#define info_logger(p, fmt, args...) bb_info_msg(fmt, ## args)
#define msg_logger(p, fmt, args...) bb_error_msg(fmt, ## args)
#define msg_logger_and_die(p, fmt, args...) bb_error_msg_and_die(fmt, ## args)
#define error_logger(p, fmt, args...) bb_perror_msg(fmt, ## args)
+175 -1
View File
@@ -36,17 +36,26 @@
//config: help
//config: Detect I2C chips.
//config:
//config:config I2CTRANSFER
//config: bool "i2ctransfer (4.0 kb)"
//config: default y
//config: select PLATFORM_LINUX
//config: help
//config: Send user-defined I2C messages in one transfer.
//config:
//applet:IF_I2CGET(APPLET(i2cget, BB_DIR_USR_SBIN, BB_SUID_DROP))
//applet:IF_I2CSET(APPLET(i2cset, BB_DIR_USR_SBIN, BB_SUID_DROP))
//applet:IF_I2CDUMP(APPLET(i2cdump, BB_DIR_USR_SBIN, BB_SUID_DROP))
//applet:IF_I2CDETECT(APPLET(i2cdetect, BB_DIR_USR_SBIN, BB_SUID_DROP))
//applet:IF_I2CTRANSFER(APPLET(i2ctransfer, BB_DIR_USR_SBIN, BB_SUID_DROP))
/* not NOEXEC: if hw operation stalls, use less memory in "hung" process */
//kbuild:lib-$(CONFIG_I2CGET) += i2c_tools.o
//kbuild:lib-$(CONFIG_I2CSET) += i2c_tools.o
//kbuild:lib-$(CONFIG_I2CDUMP) += i2c_tools.o
//kbuild:lib-$(CONFIG_I2CDETECT) += i2c_tools.o
//kbuild:lib-$(CONFIG_I2CTRANSFER) += i2c_tools.o
/*
* Unsupported stuff:
@@ -80,12 +89,19 @@
#define I2C_FUNCS 0x0705
#define I2C_PEC 0x0708
#define I2C_SMBUS 0x0720
#define I2C_RDWR 0x0707
#define I2C_RDWR_IOCTL_MAX_MSGS 42
#define I2C_RDWR_IOCTL_MAX_MSGS_STR "42"
struct i2c_smbus_ioctl_data {
__u8 read_write;
__u8 command;
__u32 size;
union i2c_smbus_data *data;
};
struct i2c_rdwr_ioctl_data {
struct i2c_msg *msgs; /* pointers to i2c_msgs */
__u32 nmsgs; /* number of i2c_msgs */
};
/* end linux/i2c-dev.h */
/*
@@ -262,7 +278,7 @@ static int i2c_bus_lookup(const char *bus_str)
return xstrtou_range(bus_str, 10, 0, 0xfffff);
}
#if ENABLE_I2CGET || ENABLE_I2CSET || ENABLE_I2CDUMP
#if ENABLE_I2CGET || ENABLE_I2CSET || ENABLE_I2CDUMP || ENABLE_I2CTRANSFER
static int i2c_parse_bus_addr(const char *addr_str)
{
/* Slave address must be in range 0x03 - 0x77. */
@@ -1373,3 +1389,161 @@ int i2cdetect_main(int argc UNUSED_PARAM, char **argv)
return 0;
}
#endif /* ENABLE_I2CDETECT */
#if ENABLE_I2CTRANSFER
static void check_i2c_func(int fd)
{
unsigned long funcs;
get_funcs_matrix(fd, &funcs);
if (!(funcs & I2C_FUNC_I2C))
bb_error_msg_and_die("adapter does not support I2C transfers");
}
//usage:#define i2ctransfer_trivial_usage
//usage: "[-fay] I2CBUS {rLENGTH[@ADDR] | wLENGTH[@ADDR] DATA...}..."
//usage:#define i2ctransfer_full_usage "\n\n"
//usage: "Read/write I2C data in one transfer"
//usage: "\n"
//usage: "\n -f Force access to busy addresses"
//usage: "\n -a Force access to non-regular addresses"
//usage: "\n -y Disable interactive mode"
int i2ctransfer_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
int i2ctransfer_main(int argc UNUSED_PARAM, char **argv)
{
enum {
opt_f = (1 << 0),
opt_y = (1 << 1),
opt_a = (1 << 2),
};
int bus_num, bus_addr;
int fd;
unsigned opts, first, last;
int nmsgs, nmsgs_sent, i;
struct i2c_msg msgs[I2C_RDWR_IOCTL_MAX_MSGS];
struct i2c_rdwr_ioctl_data rdwr;
memset(msgs, 0, sizeof(msgs));
opts = getopt32(argv, "^"
"fya"
"\0" "-2" /* minimum 2 args */
);
first = 0x03;
last = 0x77;
if (opts & opt_a) {
first = 0x00;
last = 0x7f;
}
argv += optind;
bus_num = i2c_bus_lookup(argv[0]);
fd = i2c_dev_open(bus_num);
check_i2c_func(fd);
bus_addr = -1;
nmsgs = 0;
while (*++argv) {
char *arg_ptr;
unsigned len;
uint16_t flags;
char *end;
if (nmsgs >= I2C_RDWR_IOCTL_MAX_MSGS)
bb_error_msg_and_die("too many messages, max: "I2C_RDWR_IOCTL_MAX_MSGS_STR);
flags = 0;
arg_ptr = *argv;
switch (*arg_ptr++) {
case 'r': flags |= I2C_M_RD; break;
case 'w': break;
default:
bb_show_usage();
}
end = strchr(arg_ptr, '@');
if (end) *end = '\0';
len = xstrtou_range(arg_ptr, 0, 0, 0xffff);
if (end) {
bus_addr = xstrtou_range(end + 1, 0, first, last);
i2c_set_slave_addr(fd, bus_addr, (opts & opt_f));
} else {
/* Reuse last address if possible */
if (bus_addr < 0)
bb_error_msg_and_die("no address given in '%s'", *argv);
}
msgs[nmsgs].addr = bus_addr;
msgs[nmsgs].flags = flags;
msgs[nmsgs].len = len;
if (len)
msgs[nmsgs].buf = xzalloc(len);
if (!(flags & I2C_M_RD)) {
/* Consume DATA arg(s) */
unsigned buf_idx = 0;
while (buf_idx < len) {
uint8_t data8;
unsigned long data;
arg_ptr = *++argv;
if (!arg_ptr)
bb_show_usage();
data = strtoul(arg_ptr, &end, 0);
if (data > 0xff || arg_ptr == end)
bb_error_msg_and_die("invalid data byte '%s'", *argv);
data8 = data;
while (buf_idx < len) {
msgs[nmsgs].buf[buf_idx++] = data8;
if (!*end)
break;
switch (*end) {
/* Pseudo randomness (8 bit AXR with a=13 and b=27) */
case 'p':
data8 = (data8 ^ 27) + 13;
data8 = (data8 << 1) | (data8 >> 7);
break;
case '+': data8++; break;
case '-': data8--; break;
case '=': break;
default:
bb_error_msg_and_die("invalid data byte suffix: '%s'",
*argv);
}
}
}
}
nmsgs++;
}
if (!(opts & opt_y))
confirm_action(bus_addr, 0, 0, 0);
rdwr.msgs = msgs;
rdwr.nmsgs = nmsgs;
nmsgs_sent = ioctl_or_perror_and_die(fd, I2C_RDWR, &rdwr, "I2C_RDWR");
if (nmsgs_sent < nmsgs)
bb_error_msg("warning: only %u/%u messages sent", nmsgs_sent, nmsgs);
for (i = 0; i < nmsgs_sent; i++) {
if (msgs[i].len != 0 && (msgs[i].flags & I2C_M_RD)) {
int j;
for (j = 0; j < msgs[i].len - 1; j++)
printf("0x%02x ", msgs[i].buf[j]);
/* Print final byte with newline */
printf("0x%02x\n", msgs[i].buf[j]);
}
}
# if ENABLE_FEATURE_CLEAN_UP
close(fd);
for (i = 0; i < nmsgs; i++)
free(msgs[i].buf);
# endif
return 0;
}
#endif /* ENABLE_I2CTRANSFER */
+15 -18
View File
@@ -13,9 +13,9 @@
//kbuild:lib-$(CONFIG_MAN) += man.o
//usage:#define man_trivial_usage
//usage: "[-aw] [MANPAGE]..."
//usage: "[-aw] MANPAGE..."
//usage:#define man_full_usage "\n\n"
//usage: "Format and display manual page\n"
//usage: "Display manual page\n"
//usage: "\n -a Display all pages"
//usage: "\n -w Show page locations"
//usage: "\n"
@@ -209,8 +209,9 @@ static char **add_MANPATH(char **man_path_list, int *count_mp, char *path)
/* Do we already have path? */
path_element = man_path_list;
if (path_element) while (*path_element) {
if (strcmp(*path_element, path) == 0)
if (strcmp(*path_element, path) == 0) {
goto skip;
}
path_element++;
}
man_path_list = xrealloc_vector(man_path_list, 4, *count_mp);
@@ -244,10 +245,8 @@ int man_main(int argc UNUSED_PARAM, char **argv)
{
parser_t *parser;
char *sec_list;
char *cur_path, *cur_sect;
char **man_path_list;
int count_mp;
int cur_mp;
int opt, not_found;
char *token[2];
@@ -262,16 +261,6 @@ int man_main(int argc UNUSED_PARAM, char **argv)
man_path_list = add_MANPATH(NULL, &count_mp,
getenv("MANDATORY_MANPATH"+10) /* "MANPATH" */
);
if (!man_path_list) {
/* default, may be overridden by /etc/man.conf */
man_path_list = xzalloc(2 * sizeof(man_path_list[0]));
man_path_list[0] = (char*)"/usr/man";
/* count_mp stays 0.
* Thus, man.conf will overwrite man_path_list[0]
* if a path is defined there.
*/
}
/* Parse man.conf[ig] or man_db.conf */
/* man version 1.6f uses man.config */
/* man-db implementation of man uses man_db.conf */
@@ -285,7 +274,7 @@ int man_main(int argc UNUSED_PARAM, char **argv)
if (!token[1])
continue;
if (strcmp("DEFINE", token[0]) == 0) {
G.col = if_redefined(G.tbl , "col", token[1]);
G.col = if_redefined(G.col , "col", token[1]);
G.tbl = if_redefined(G.tbl , "tbl", token[1]);
G.nroff = if_redefined(G.nroff, "nroff", token[1]);
G.pager = if_redefined(G.pager, "pager", token[1]);
@@ -302,6 +291,12 @@ int man_main(int argc UNUSED_PARAM, char **argv)
}
config_close(parser);
if (!man_path_list) {
static const char *const mpl[] = { "/usr/man", "/usr/share/man", NULL };
man_path_list = (char**)mpl;
/*count_mp = 2; - not used below anyway */
}
{
/* environment overrides setting from man.config */
char *env_pager = getenv("MANPAGER");
@@ -318,16 +313,18 @@ int man_main(int argc UNUSED_PARAM, char **argv)
not_found = 0;
do { /* for each argv[] */
const char *cur_path;
int cur_mp;
int found = 0;
cur_mp = 0;
if (strchr(*argv, '/')) {
found = show_manpage(*argv, /*man:*/ 1, 0);
goto check_found;
}
cur_mp = 0;
while ((cur_path = man_path_list[cur_mp++]) != NULL) {
/* for each MANPATH */
cur_sect = sec_list;
const char *cur_sect = sec_list;
do { /* for each section */
char *next_sect = strchrnul(cur_sect, ':');
int sect_len = next_sect - cur_sect;
+84
View File
@@ -0,0 +1,84 @@
/* vi: set sw=4 ts=4: */
/*
* Copyright (C) 2019 Denys Vlasenko <vda.linux@googlemail.com>
* Licensed under GPLv2, see file LICENSE in this source tree.
*/
//config:config TS
//config: bool "ts (450 bytes)"
//config: default y
//applet:IF_TS(APPLET(ts, BB_DIR_USR_BIN, BB_SUID_DROP))
//kbuild:lib-$(CONFIG_TS) += ts.o
//usage:#define ts_trivial_usage
//usage: "[-is] [STRFTIME]"
//usage:#define ts_full_usage ""
#include "libbb.h"
#include "common_bufsiz.h"
int ts_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
int ts_main(int argc UNUSED_PARAM, char **argv)
{
struct timeval base;
unsigned opt;
char *frac;
char *fmt_dt2str;
char *line;
opt = getopt32(argv, "^" "is" "\0" "?1" /*max one arg*/);
if (opt) {
putenv((char*)"TZ=UTC0");
tzset();
}
/*argc -= optind;*/
argv += optind;
fmt_dt2str = argv[0] ? argv[0]
: (char*)(opt ? "%b %d %H:%M:%S"+6 : "%b %d %H:%M:%S");
frac = is_suffixed_with(fmt_dt2str, "%.S");
if (!frac)
frac = is_suffixed_with(fmt_dt2str, "%.s");
if (frac) {
frac++;
frac[0] = frac[1];
frac[1] = '\0';
}
#define date_buf bb_common_bufsiz1
setup_common_bufsiz();
gettimeofday(&base, NULL);
while ((line = xmalloc_fgets(stdin)) != NULL) {
struct timeval ts;
struct tm tm_time;
gettimeofday(&ts, NULL);
if (opt) {
/* -i and/or -s */
struct timeval ts1 = ts1;
if (opt & 1) /* -i */
ts1 = ts;
//printf("%d %d\n", ts.tv_sec, base.tv_sec);
ts.tv_sec -= base.tv_sec;
//printf("%d %d\n", ts.tv_sec, base.tv_sec);
ts.tv_usec -= base.tv_usec;
if ((int32_t)(ts.tv_usec) < 0) {
ts.tv_sec--;
ts.tv_usec += 1000*1000;
}
if (opt & 1) /* -i */
base = ts1;
}
localtime_r(&ts.tv_sec, &tm_time);
strftime(date_buf, COMMON_BUFSIZE, fmt_dt2str, &tm_time);
if (!frac) {
printf("%s %s", date_buf, line);
} else {
printf("%s.%06u %s", date_buf, (unsigned)ts.tv_usec, line);
}
free(line);
}
return EXIT_SUCCESS;
}
+2 -2
View File
@@ -64,7 +64,7 @@ static void shutdown_watchdog(void)
static void shutdown_on_signal(int sig UNUSED_PARAM)
{
remove_pidfile(CONFIG_PID_FILE_PATH "/watchdog.pid");
remove_pidfile_std_path_and_ext("watchdog");
shutdown_watchdog();
_exit(EXIT_SUCCESS);
}
@@ -136,7 +136,7 @@ int watchdog_main(int argc UNUSED_PARAM, char **argv)
stimer_duration, htimer_duration * 1000);
#endif
write_pidfile(CONFIG_PID_FILE_PATH "/watchdog.pid");
write_pidfile_std_path_and_ext("watchdog");
while (1) {
/*
+4 -1
View File
@@ -66,7 +66,10 @@ static void check_tainted(void)
}
}
#else
static void check_tainted(void) { putchar('\n'); }
static ALWAYS_INLINE void check_tainted(void)
{
putchar('\n');
}
#endif
int lsmod_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
+268 -250
View File
@@ -9,9 +9,6 @@
*
* Licensed under GPLv2 or later, see file LICENSE in this source tree.
*/
/* This applet currently uses only the ioctl interface and no sysfs at all.
* At the time of this writing this was considered a feature.
*/
//config:config BRCTL
//config: bool "brctl (4.7 kb)"
//config: default y
@@ -44,29 +41,34 @@
//kbuild:lib-$(CONFIG_BRCTL) += brctl.o
//usage:#define brctl_trivial_usage
//usage: "COMMAND [BRIDGE [INTERFACE]]"
//usage: "COMMAND [BRIDGE [ARGS]]"
//usage:#define brctl_full_usage "\n\n"
//usage: "Manage ethernet bridges\n"
//usage: "Manage ethernet bridges"
//usage: "\nCommands:"
//usage: IF_FEATURE_BRCTL_SHOW(
//usage: "\n show Show a list of bridges"
//usage: "\n show [BRIDGE]... Show bridges"
//usage: )
//usage: "\n addbr BRIDGE Create BRIDGE"
//usage: "\n delbr BRIDGE Delete BRIDGE"
//usage: "\n addif BRIDGE IFACE Add IFACE to BRIDGE"
//usage: "\n delif BRIDGE IFACE Delete IFACE from BRIDGE"
//usage: IF_FEATURE_BRCTL_FANCY(
//usage: "\n setageing BRIDGE TIME Set ageing time"
//usage: "\n setfd BRIDGE TIME Set bridge forward delay"
//usage: "\n sethello BRIDGE TIME Set hello time"
//usage: "\n setmaxage BRIDGE TIME Set max message age"
//usage: "\n setpathcost BRIDGE COST Set path cost"
//usage: "\n setportprio BRIDGE PRIO Set port priority"
//usage: "\n stp BRIDGE 1/yes/on|0/no/off STP on/off"
//usage: "\n setageing BRIDGE SECONDS Set ageing time"
//usage: "\n setfd BRIDGE SECONDS Set bridge forward delay"
//usage: "\n sethello BRIDGE SECONDS Set hello time"
//usage: "\n setmaxage BRIDGE SECONDS Set max message age"
//usage: "\n setbridgeprio BRIDGE PRIO Set bridge priority"
//usage: "\n stp BRIDGE [1/yes/on|0/no/off] STP on/off"
//usage: "\n setportprio BRIDGE IFACE PRIO Set port priority"
//usage: "\n setpathcost BRIDGE IFACE COST Set path cost"
//usage: )
// Not yet implemented:
// hairpin BRIDGE IFACE on|off Hairpin on/off
// showmacs BRIDGE List mac addrs
// showstp BRIDGE Show stp info
#include "libbb.h"
#include "common_bufsiz.h"
#include <linux/sockios.h>
#include <net/if.h>
@@ -83,122 +85,119 @@
# define SIOCBRDELIF BRCTL_DEL_IF
#endif
#if ENABLE_FEATURE_BRCTL_FANCY
static unsigned str_to_jiffies(const char *time_str)
{
double dd;
char *endptr;
dd = /*bb_*/strtod(time_str, &endptr);
if (endptr == time_str || dd < 0)
bb_error_msg_and_die(bb_msg_invalid_arg_to, time_str, "timespec");
/* Maximum number of ports supported per bridge interface. */
#ifndef MAX_PORTS
# define MAX_PORTS 32
dd *= 100;
/* For purposes of brctl,
* capping SECONDS by ~20 million seconds is quite enough:
*/
if (dd > INT_MAX)
dd = INT_MAX;
return dd;
}
#endif
/* Use internal number parsing and not the "exact" conversion. */
/* #define BRCTL_USE_INTERNAL 0 */ /* use exact conversion */
#define BRCTL_USE_INTERNAL 1
#define filedata bb_common_bufsiz1
#if ENABLE_FEATURE_BRCTL_SHOW
static int read_file(const char *name)
{
int n = open_read_close(name, filedata, COMMON_BUFSIZE - 1);
if (n < 0) {
filedata[0] = '\0';
} else {
filedata[n] = '\0';
if (n != 0 && filedata[n - 1] == '\n')
filedata[--n] = '\0';
}
return n;
}
/* NB: we are in /sys/class/net
*/
static int show_bridge(const char *name, int need_hdr)
{
/* Output:
*bridge name bridge id STP enabled interfaces
*br0 8000.000000000000 no eth0
*/
char pathbuf[IFNAMSIZ + sizeof("/bridge/bridge_id") + 32];
int tabs;
DIR *ifaces;
struct dirent *ent;
char *sfx;
#if IFNAMSIZ == 16
sfx = pathbuf + sprintf(pathbuf, "%.16s/bridge/", name);
#else
sfx = pathbuf + sprintf(pathbuf, "%.*s/bridge/", (int)IFNAMSIZ, name);
#endif
strcpy(sfx, "bridge_id");
if (read_file(pathbuf) < 0)
return -1; /* this iface is not a bridge */
if (need_hdr)
puts("bridge name\tbridge id\t\tSTP enabled\tinterfaces");
printf("%s\t\t", name);
printf("%s\t", filedata);
strcpy(sfx, "stp_state");
read_file(pathbuf);
if (LONE_CHAR(filedata, '0'))
strcpy(filedata, "no");
else
if (LONE_CHAR(filedata, '1'))
strcpy(filedata, "yes");
fputs(filedata, stdout);
strcpy(sfx - (sizeof("bridge/")-1), "brif");
tabs = 0;
ifaces = opendir(pathbuf);
if (ifaces) {
while ((ent = readdir(ifaces)) != NULL) {
if (DOT_OR_DOTDOT(ent->d_name))
continue; /* . or .. */
if (tabs)
printf("\t\t\t\t\t");
else
tabs = 1;
printf("\t\t%s\n", ent->d_name);
}
closedir(ifaces);
}
if (!tabs) /* bridge has no interfaces */
bb_putchar('\n');
return 0;
}
#endif
#if ENABLE_FEATURE_BRCTL_FANCY
/* #include <linux/if_bridge.h>
* breaks on musl: we already included netinet/in.h in libbb.h,
* if we include <linux/if_bridge.h> here, we get this:
* In file included from /usr/include/linux/if_bridge.h:18,
* from networking/brctl.c:67:
* /usr/include/linux/in6.h:32: error: redefinition of 'struct in6_addr'
* /usr/include/linux/in6.h:49: error: redefinition of 'struct sockaddr_in6'
* /usr/include/linux/in6.h:59: error: redefinition of 'struct ipv6_mreq'
*/
/* From <linux/if_bridge.h> */
#define BRCTL_GET_VERSION 0
#define BRCTL_GET_BRIDGES 1
#define BRCTL_ADD_BRIDGE 2
#define BRCTL_DEL_BRIDGE 3
#define BRCTL_ADD_IF 4
#define BRCTL_DEL_IF 5
#define BRCTL_GET_BRIDGE_INFO 6
#define BRCTL_GET_PORT_LIST 7
#define BRCTL_SET_BRIDGE_FORWARD_DELAY 8
#define BRCTL_SET_BRIDGE_HELLO_TIME 9
#define BRCTL_SET_BRIDGE_MAX_AGE 10
#define BRCTL_SET_AGEING_TIME 11
#define BRCTL_SET_GC_INTERVAL 12
#define BRCTL_GET_PORT_INFO 13
#define BRCTL_SET_BRIDGE_STP_STATE 14
#define BRCTL_SET_BRIDGE_PRIORITY 15
#define BRCTL_SET_PORT_PRIORITY 16
#define BRCTL_SET_PATH_COST 17
#define BRCTL_GET_FDB_ENTRIES 18
struct __bridge_info {
uint64_t designated_root;
uint64_t bridge_id;
uint32_t root_path_cost;
uint32_t max_age;
uint32_t hello_time;
uint32_t forward_delay;
uint32_t bridge_max_age;
uint32_t bridge_hello_time;
uint32_t bridge_forward_delay;
uint8_t topology_change;
uint8_t topology_change_detected;
uint8_t root_port;
uint8_t stp_enabled;
uint32_t ageing_time;
uint32_t gc_interval;
uint32_t hello_timer_value;
uint32_t tcn_timer_value;
uint32_t topology_change_timer_value;
uint32_t gc_timer_value;
};
/* end <linux/if_bridge.h> */
/* FIXME: These 4 funcs are not really clean and could be improved */
static ALWAYS_INLINE void bb_strtotimeval(struct timeval *tv,
const char *time_str)
static void write_uint(const char *name, const char *leaf, unsigned val)
{
double secs;
# if BRCTL_USE_INTERNAL
char *endptr;
secs = /*bb_*/strtod(time_str, &endptr);
if (endptr == time_str)
# else
if (sscanf(time_str, "%lf", &secs) != 1)
# endif
bb_error_msg_and_die(bb_msg_invalid_arg_to, time_str, "timespec");
tv->tv_sec = secs;
tv->tv_usec = 1000000 * (secs - tv->tv_sec);
}
char pathbuf[IFNAMSIZ + sizeof("/bridge/bridge_id") + 32];
int fd, n;
static ALWAYS_INLINE unsigned long tv_to_jiffies(const struct timeval *tv)
{
unsigned long long jif;
jif = 1000000ULL * tv->tv_sec + tv->tv_usec;
return jif/10000;
}
# if 0
static void jiffies_to_tv(struct timeval *tv, unsigned long jiffies)
{
unsigned long long tvusec;
tvusec = 10000ULL*jiffies;
tv->tv_sec = tvusec/1000000;
tv->tv_usec = tvusec - 1000000 * tv->tv_sec;
}
# endif
static unsigned long str_to_jiffies(const char *time_str)
{
struct timeval tv;
bb_strtotimeval(&tv, time_str);
return tv_to_jiffies(&tv);
}
static void arm_ioctl(unsigned long *args,
unsigned long arg0, unsigned long arg1, unsigned long arg2)
{
args[0] = arg0;
args[1] = arg1;
args[2] = arg2;
args[3] = 0;
#if IFNAMSIZ == 16
sprintf(pathbuf, "%.16s/%s", name, leaf);
#else
sprintf(pathbuf, "%.*s/%s", (int)IFNAMSIZ, name, leaf);
#endif
fd = xopen(pathbuf, O_WRONLY);
n = sprintf(filedata, "%u\n", val);
if (write(fd, filedata, n) < 0)
bb_simple_perror_msg_and_die(name);
close(fd);
}
#endif
int brctl_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
int brctl_main(int argc UNUSED_PARAM, char **argv)
{
@@ -207,90 +206,71 @@ int brctl_main(int argc UNUSED_PARAM, char **argv)
IF_FEATURE_BRCTL_FANCY(
"stp\0"
"setageing\0" "setfd\0" "sethello\0" "setmaxage\0"
"setpathcost\0" "setportprio\0" "setbridgeprio\0"
"setpathcost\0" "setportprio\0"
"setbridgeprio\0"
)
IF_FEATURE_BRCTL_SHOW("show\0");
enum { ARG_addbr = 0, ARG_delbr, ARG_addif, ARG_delif
IF_FEATURE_BRCTL_FANCY(,
ARG_stp,
ARG_setageing, ARG_setfd, ARG_sethello, ARG_setmaxage,
ARG_setpathcost, ARG_setportprio, ARG_setbridgeprio
ARG_setpathcost, ARG_setportprio,
ARG_setbridgeprio
)
IF_FEATURE_BRCTL_SHOW(, ARG_show)
};
int fd;
smallint key;
struct ifreq ifr;
char *br, *brif;
argv++;
while (*argv) {
#if ENABLE_FEATURE_BRCTL_FANCY
int ifidx[MAX_PORTS];
unsigned long args[4];
ifr.ifr_data = (char *) &args;
#endif
if (!*argv) {
/* bare "brctl" shows --help */
bb_show_usage();
}
xchdir("/sys/class/net");
// while (*argv)
{
smallint key;
char *br;
key = index_in_strings(keywords, *argv);
if (key == -1) /* no match found in keywords array, bail out. */
bb_error_msg_and_die(bb_msg_invalid_arg_to, *argv, applet_name);
argv++;
fd = xsocket(AF_INET, SOCK_STREAM, 0);
#if ENABLE_FEATURE_BRCTL_SHOW
if (key == ARG_show) { /* show */
char buf[IFNAMSIZ];
int bridx[MAX_PORTS];
int i, num;
arm_ioctl(args, BRCTL_GET_BRIDGES,
(unsigned long) bridx, MAX_PORTS);
num = xioctl(fd, SIOCGIFBR, args);
puts("bridge name\tbridge id\t\tSTP enabled\tinterfaces");
for (i = 0; i < num; i++) {
int j, tabs;
struct __bridge_info bi;
unsigned char *x;
if (key == ARG_show) { /* show [BR]... */
DIR *net;
struct dirent *ent;
int need_hdr = 1;
int exitcode = EXIT_SUCCESS;
if (!if_indextoname(bridx[i], buf))
bb_perror_msg_and_die("can't get bridge name for index %d", i);
strncpy_IFNAMSIZ(ifr.ifr_name, buf);
arm_ioctl(args, BRCTL_GET_BRIDGE_INFO,
(unsigned long) &bi, 0);
xioctl(fd, SIOCDEVPRIVATE, &ifr);
printf("%s\t\t", buf);
/* print bridge id */
x = (unsigned char *) &bi.bridge_id;
for (j = 0; j < 8; j++) {
printf("%02x", x[j]);
if (j == 1)
bb_putchar('.');
}
printf(bi.stp_enabled ? "\tyes" : "\tno");
/* print interface list */
arm_ioctl(args, BRCTL_GET_PORT_LIST,
(unsigned long) ifidx, MAX_PORTS);
xioctl(fd, SIOCDEVPRIVATE, &ifr);
tabs = 0;
for (j = 0; j < MAX_PORTS; j++) {
if (!ifidx[j])
continue;
if (!if_indextoname(ifidx[j], buf))
bb_perror_msg_and_die("can't get interface name for index %d", j);
if (tabs)
printf("\t\t\t\t\t");
else
tabs = 1;
printf("\t\t%s\n", buf);
}
if (!tabs) /* bridge has no interfaces */
bb_putchar('\n');
if (*argv) {
/* "show BR1 BR2 BR3" */
do {
if (show_bridge(*argv, need_hdr) >= 0) {
need_hdr = 0;
} else {
bb_error_msg("bridge %s does not exist", *argv);
//TODO: if device exists, but is not a BR, brctl from bridge-utils 1.6
//says this instead: "device eth0 is not a bridge"
exitcode = EXIT_FAILURE;
}
} while (*++argv != NULL);
return exitcode;
}
goto done;
/* "show" (if no ifaces, shows nothing, not even header) */
net = xopendir(".");
while ((ent = readdir(net)) != NULL) {
if (DOT_OR_DOTDOT(ent->d_name))
continue; /* . or .. */
if (show_bridge(ent->d_name, need_hdr) >= 0)
need_hdr = 0;
}
if (ENABLE_FEATURE_CLEAN_UP)
closedir(net);
return exitcode;
}
#endif
@@ -299,28 +279,29 @@ int brctl_main(int argc UNUSED_PARAM, char **argv)
br = *argv++;
if (key == ARG_addbr || key == ARG_delbr) { /* addbr or delbr */
if (key == ARG_addbr || key == ARG_delbr) {
/* addbr or delbr */
/* brctl from bridge-utils 1.6 still uses ioctl
* for SIOCBRADDBR / SIOCBRDELBR, not /sys accesses
*/
int fd = xsocket(AF_INET, SOCK_STREAM, 0);
ioctl_or_perror_and_die(fd,
key == ARG_addbr ? SIOCBRADDBR : SIOCBRDELBR,
br, "bridge %s", br);
goto done;
key == ARG_addbr ? SIOCBRADDBR : SIOCBRDELBR,
br, "bridge %s", br
);
//close(fd);
//goto done;
/* bridge-utils 1.6 simply ignores trailing args:
* "brctl addbr BR1 ARGS" ignores ARGS
*/
if (ENABLE_FEATURE_CLEAN_UP)
close(fd);
return EXIT_SUCCESS;
}
if (!*argv) /* all but 'addbr/delbr' need at least two arguments */
bb_show_usage();
strncpy_IFNAMSIZ(ifr.ifr_name, br);
if (key == ARG_addif || key == ARG_delif) { /* addif or delif */
brif = *argv;
ifr.ifr_ifindex = if_nametoindex(brif);
if (!ifr.ifr_ifindex) {
bb_perror_msg_and_die("iface %s", brif);
}
ioctl_or_perror_and_die(fd,
key == ARG_addif ? SIOCBRADDIF : SIOCBRDELIF,
&ifr, "bridge %s", br);
goto done_next_argv;
}
#if ENABLE_FEATURE_BRCTL_FANCY
if (key == ARG_stp) { /* stp */
static const char no_yes[] ALIGN1 =
@@ -330,65 +311,102 @@ int brctl_main(int argc UNUSED_PARAM, char **argv)
if (onoff < 0)
bb_error_msg_and_die(bb_msg_invalid_arg_to, *argv, applet_name);
onoff = (unsigned)onoff / 4;
arm_ioctl(args, BRCTL_SET_BRIDGE_STP_STATE, onoff, 0);
goto fire;
write_uint(br, "bridge/stp_state", onoff);
//goto done_next_argv;
return EXIT_SUCCESS;
}
if ((unsigned)(key - ARG_setageing) < 4) { /* time related ops */
static const uint8_t ops[] ALIGN1 = {
BRCTL_SET_AGEING_TIME, /* ARG_setageing */
BRCTL_SET_BRIDGE_FORWARD_DELAY, /* ARG_setfd */
BRCTL_SET_BRIDGE_HELLO_TIME, /* ARG_sethello */
BRCTL_SET_BRIDGE_MAX_AGE /* ARG_setmaxage */
};
arm_ioctl(args, ops[key - ARG_setageing], str_to_jiffies(*argv), 0);
goto fire;
/* setageing BR N: "N*100\n" to /sys/class/net/BR/bridge/ageing_time
* setfd BR N: "N*100\n" to /sys/class/net/BR/bridge/forward_delay
* sethello BR N: "N*100\n" to /sys/class/net/BR/bridge/hello_time
* setmaxage BR N: "N*100\n" to /sys/class/net/BR/bridge/max_age
*/
write_uint(br,
nth_string(
"bridge/ageing_time" "\0" /* ARG_setageing */
"bridge/forward_delay""\0" /* ARG_setfd */
"bridge/hello_time" "\0" /* ARG_sethello */
"bridge/max_age", /* ARG_setmaxage */
key - ARG_setageing
),
str_to_jiffies(*argv)
);
//goto done_next_argv;
return EXIT_SUCCESS;
}
if (key == ARG_setbridgeprio) {
write_uint(br, "bridge/priority", xatoi_positive(*argv));
//goto done_next_argv;
return EXIT_SUCCESS;
}
if (key == ARG_setpathcost
|| key == ARG_setportprio
|| key == ARG_setbridgeprio
) {
static const uint8_t ops[] ALIGN1 = {
BRCTL_SET_PATH_COST, /* ARG_setpathcost */
BRCTL_SET_PORT_PRIORITY, /* ARG_setportprio */
BRCTL_SET_BRIDGE_PRIORITY /* ARG_setbridgeprio */
};
int port = -1;
unsigned arg1, arg2;
if (key != ARG_setbridgeprio) {
/* get portnum */
unsigned i;
port = if_nametoindex(*argv++);
if (!port)
bb_error_msg_and_die(bb_msg_invalid_arg_to, *argv, "port");
memset(ifidx, 0, sizeof ifidx);
arm_ioctl(args, BRCTL_GET_PORT_LIST, (unsigned long)ifidx,
MAX_PORTS);
xioctl(fd, SIOCDEVPRIVATE, &ifr);
for (i = 0; i < MAX_PORTS; i++) {
if (ifidx[i] == port) {
port = i;
break;
}
}
}
arg1 = port;
arg2 = xatoi_positive(*argv);
if (key == ARG_setbridgeprio) {
arg1 = arg2;
arg2 = 0;
}
arm_ioctl(args, ops[key - ARG_setpathcost], arg1, arg2);
if (!argv[1])
bb_show_usage();
/* BR is not used (and ignored!) for these commands:
* "setpathcost BR PORT N" writes "N\n" to
* /sys/class/net/PORT/brport/path_cost
* "setportprio BR PORT N" writes "N\n" to
* /sys/class/net/PORT/brport/priority
*/
write_uint(argv[0],
nth_string(
"brport/path_cost" "\0" /* ARG_setpathcost */
"brport/priority", /* ARG_setportprio */
key - ARG_setpathcost
),
xatoi_positive(argv[1])
);
//argv++;
//goto done_next_argv;
return EXIT_SUCCESS;
}
fire:
/* Execute the previously set command */
xioctl(fd, SIOCDEVPRIVATE, &ifr);
/* TODO: "showmacs BR"
* port no\tmac addr\t\tis local?\tageing timer
* <sp><sp>1\txx:xx:xx:xx:xx:xx\tno\t\t<sp><sp><sp>1.31
* port no mac addr is local? ageing timer
* 1 xx:xx:xx:xx:xx:xx no 1.31
* Read fixed-sized records from /sys/class/net/BR/brforward:
* struct __fdb_entry {
* uint8_t mac_addr[ETH_ALEN];
* uint8_t port_no; //lsb
* uint8_t is_local;
* uint32_t ageing_timer_value;
* uint8_t port_hi;
* uint8_t pad0;
* uint16_t unused;
* };
*/
#endif
done_next_argv:
argv++;
done:
close(fd);
/* always true: if (key == ARG_addif || key == ARG_delif) */ {
/* addif or delif */
struct ifreq ifr;
int fd = xsocket(AF_INET, SOCK_STREAM, 0);
strncpy_IFNAMSIZ(ifr.ifr_name, br);
ifr.ifr_ifindex = if_nametoindex(*argv);
if (ifr.ifr_ifindex == 0) {
bb_perror_msg_and_die("iface %s", *argv);
}
ioctl_or_perror_and_die(fd,
key == ARG_addif ? SIOCBRADDIF : SIOCBRDELIF,
&ifr, "bridge %s", br
);
//close(fd);
//goto done_next_argv;
if (ENABLE_FEATURE_CLEAN_UP)
close(fd);
return EXIT_SUCCESS;
}
// done_next_argv:
// argv++;
// done:
}
return EXIT_SUCCESS;
+5 -5
View File
@@ -133,7 +133,7 @@ static struct dns_entry *parse_conf_file(const char *fileconf)
}
if (OPT_verbose)
bb_error_msg("name:%s, ip:%s", token[0], token[1]);
bb_info_msg("name:%s, ip:%s", token[0], token[1]);
/* sizeof(*m) includes 1 byte for m->name[0] */
m = xzalloc(sizeof(*m) + strlen(token[0]) + 1);
@@ -438,7 +438,7 @@ static int process_packet(struct dns_entry *conf_data,
answstr = table_lookup(conf_data, type, query_string);
#if DEBUG
/* Shows lengths instead of dots, unusable for !DEBUG */
bb_error_msg("'%s'->'%s'", query_string, answstr);
bb_info_msg("'%s'->'%s'", query_string, answstr);
#endif
outr_rlen = 4;
if (answstr && type == htons(REQ_PTR)) {
@@ -474,7 +474,7 @@ static int process_packet(struct dns_entry *conf_data,
* RCODE = 0 "success"
*/
if (OPT_verbose)
bb_error_msg("returning positive reply");
bb_info_msg("returning positive reply");
outr_flags = htons(0x8000 | 0x0400 | 0);
/* we have one answer */
head->nansw = htons(1);
@@ -539,7 +539,7 @@ int dnsd_main(int argc UNUSED_PARAM, char **argv)
{
char *p = xmalloc_sockaddr2dotted(&lsa->u.sa);
bb_error_msg("accepting UDP packets on %s", p);
bb_info_msg("accepting UDP packets on %s", p);
free(p);
}
@@ -557,7 +557,7 @@ int dnsd_main(int argc UNUSED_PARAM, char **argv)
continue;
}
if (OPT_verbose)
bb_error_msg("got UDP packet");
bb_info_msg("got UDP packet");
buf[r] = '\0'; /* paranoia */
r = process_packet(conf_data, conf_ttl, buf);
if (r <= 0)
+313 -271
View File
@@ -95,9 +95,7 @@
* 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
* server exits with an error.
*
*/
/* TODO: use TCP_CORK, parse_config() */
//config:config HTTPD
//config: bool "httpd (32 kb)"
//config: default y
@@ -246,6 +244,8 @@
//usage: "\n -e STRING HTML encode STRING"
//usage: "\n -d STRING URL decode STRING"
/* TODO: use TCP_CORK, parse_config() */
#include "libbb.h"
#include "common_bufsiz.h"
#if ENABLE_PAM
@@ -259,17 +259,11 @@
#if ENABLE_FEATURE_USE_SENDFILE
# include <sys/sendfile.h>
#endif
/* amount of buffering in a pipe */
#ifndef PIPE_BUF
# define PIPE_BUF 4096
#endif
#define DEBUG 0
#define IOBUF_SIZE 8192
#if PIPE_BUF >= IOBUF_SIZE
# error "PIPE_BUF >= IOBUF_SIZE"
#endif
#define MAX_HTTP_HEADERS_SIZE (32*1024)
#define HEADER_READ_TIMEOUT 60
@@ -305,6 +299,13 @@ typedef struct Htaccess_Proxy {
char *url_to;
} Htaccess_Proxy;
typedef enum CGI_type {
CGI_NONE = 0,
CGI_NORMAL,
CGI_INDEX,
CGI_INTERPRETER,
} CGI_type;
enum {
HTTP_OK = 200,
HTTP_PARTIAL_CONTENT = 206,
@@ -316,6 +317,7 @@ enum {
HTTP_REQUEST_TIMEOUT = 408,
HTTP_NOT_IMPLEMENTED = 501, /* used for unrecognized requests */
HTTP_INTERNAL_SERVER_ERROR = 500,
HTTP_ENTITY_TOO_LARGE = 413,
HTTP_CONTINUE = 100,
#if 0 /* future use */
HTTP_SWITCHING_PROTOCOLS = 101,
@@ -347,6 +349,7 @@ static const uint16_t http_response_type[] ALIGN2 = {
HTTP_BAD_REQUEST,
HTTP_FORBIDDEN,
HTTP_INTERNAL_SERVER_ERROR,
HTTP_ENTITY_TOO_LARGE,
#if 0 /* not implemented */
HTTP_CREATED,
HTTP_ACCEPTED,
@@ -377,6 +380,7 @@ static const struct {
{ "Bad Request", "Unsupported method" },
{ "Forbidden", "" },
{ "Internal Server Error", "Internal Server Error" },
{ "Entity Too Large", "Entity Too Large" },
#if 0 /* not implemented */
{ "Created" },
{ "Accepted" },
@@ -396,12 +400,11 @@ struct globals {
/* client can handle gzip / we are going to send gzip */
smallint content_gzip;
#endif
unsigned rmt_ip; /* used for IP-based allow/deny rules */
time_t last_mod;
char *rmt_ip_str; /* for $REMOTE_ADDR and $REMOTE_PORT */
const char *bind_addr_or_port;
const char *g_query;
char *g_query;
const char *opt_c_configFile;
const char *home_httpd;
const char *index_page;
@@ -412,11 +415,6 @@ struct globals {
IF_FEATURE_HTTPD_BASIC_AUTH(const char *g_realm;)
IF_FEATURE_HTTPD_BASIC_AUTH(char *remoteuser;)
IF_FEATURE_HTTPD_CGI(char *referer;)
IF_FEATURE_HTTPD_CGI(char *user_agent;)
IF_FEATURE_HTTPD_CGI(char *host;)
IF_FEATURE_HTTPD_CGI(char *http_accept;)
IF_FEATURE_HTTPD_CGI(char *http_accept_language;)
off_t file_size; /* -1 - unknown */
#if ENABLE_FEATURE_HTTPD_RANGES
@@ -452,7 +450,6 @@ struct globals {
#else
# define content_gzip 0
#endif
#define rmt_ip (G.rmt_ip )
#define bind_addr_or_port (G.bind_addr_or_port)
#define g_query (G.g_query )
#define opt_c_configFile (G.opt_c_configFile )
@@ -1146,18 +1143,61 @@ static void send_headers(unsigned responseNum)
file_size = range_end - range_start + 1;
}
#endif
//RFC 2616 4.4 Message Length
// The transfer-length of a message is the length of the message-body as
// it appears in the message; that is, after any transfer-codings have
// been applied. When a message-body is included with a message, the
// transfer-length of that body is determined by one of the following
// (in order of precedence):
// 1.Any response message which "MUST NOT" include a message-body (such
// as the 1xx, 204, and 304 responses and any response to a HEAD
// request) is always terminated by the first empty line after the
// header fields, regardless of the entity-header fields present in
// the message.
// 2.If a Transfer-Encoding header field (section 14.41) is present and
// has any value other than "identity", then the transfer-length is
// defined by use of the "chunked" transfer-coding (section 3.6),
// unless the message is terminated by closing the connection.
// 3.If a Content-Length header field (section 14.13) is present, its
// decimal value in OCTETs represents both the entity-length and the
// transfer-length. The Content-Length header field MUST NOT be sent
// if these two lengths are different (i.e., if a Transfer-Encoding
// header field is present). If a message is received with both a
// Transfer-Encoding header field and a Content-Length header field,
// the latter MUST be ignored.
// 4.If the message uses the media type "multipart/byteranges" ...
// 5.By the server closing the connection.
//
// (NB: standards do not define "Transfer-Length:" _header_,
// transfer-length above is just a concept).
len += sprintf(iobuf + len,
#if ENABLE_FEATURE_HTTPD_RANGES
"Accept-Ranges: bytes\r\n"
#endif
"Last-Modified: %s\r\n"
"%s-Length: %"OFF_FMT"u\r\n",
/* Because of 4.4 (5), we can forgo sending of "Content-Length"
* since we close connection afterwards, but it helps clients
* to e.g. estimate download times, show progress bars etc.
* Theoretically we should not send it if page is compressed,
* but de-facto standard is to send it (see comment below).
*/
"Content-Length: %"OFF_FMT"u\r\n",
date_str,
content_gzip ? "Transfer" : "Content",
file_size
);
}
/* This should be "Transfer-Encoding", not "Content-Encoding":
* "data is compressed for transfer", not "data is an archive".
* But many clients were not handling "Transfer-Encoding" correctly
* (they were not uncompressing gzipped pages, tried to show
* raw compressed data), and servers worked around it by using
* "Content-Encoding" instead... and this become de-facto standard.
* https://bugzilla.mozilla.org/show_bug.cgi?id=68517
* https://bugs.chromium.org/p/chromium/issues/detail?id=94730
*/
if (content_gzip)
len += sprintf(iobuf + len, "Content-Encoding: gzip\r\n");
@@ -1194,37 +1234,39 @@ static void send_headers_and_exit(int responseNum)
}
/*
* Read from the socket until '\n' or EOF. '\r' chars are removed.
* Read from the socket until '\n' or EOF.
* '\r' chars are removed.
* '\n' is replaced with NUL.
* Return number of characters read or 0 if nothing is read
* ('\r' and '\n' are not counted).
* Data is returned in iobuf.
*/
static int get_line(void)
static unsigned get_line(void)
{
int count = 0;
unsigned count;
char c;
alarm(HEADER_READ_TIMEOUT);
count = 0;
while (1) {
if (hdr_cnt <= 0) {
alarm(HEADER_READ_TIMEOUT);
hdr_cnt = safe_read(STDIN_FILENO, hdr_buf, sizeof_hdr_buf);
if (hdr_cnt <= 0)
break;
goto ret;
hdr_ptr = hdr_buf;
}
iobuf[count] = c = *hdr_ptr++;
hdr_cnt--;
c = *hdr_ptr++;
if (c == '\r')
continue;
if (c == '\n') {
iobuf[count] = '\0';
if (c == '\n')
break;
}
iobuf[count] = c;
if (count < (IOBUF_SIZE - 1)) /* check overflow */
count++;
}
ret:
iobuf[count] = '\0';
return count;
}
@@ -1364,10 +1406,10 @@ static NOINLINE void cgi_io_loop_and_exit(int fromCgi_rd, int toCgi_wr, int post
* CGI may output a few first bytes and then wait
* for POSTDATA without closing stdout.
* With full_read we may wait here forever. */
count = safe_read(fromCgi_rd, rbuf + out_cnt, PIPE_BUF - 8);
count = safe_read(fromCgi_rd, rbuf + out_cnt, IOBUF_SIZE - 8);
if (count <= 0) {
/* eof (or error) and there was no "HTTP",
* so write it, then write received data */
* send "HTTP/1.0 200 OK\r\n", then send received data */
if (out_cnt) {
full_write(STDOUT_FILENO, HTTP_200, sizeof(HTTP_200)-1);
full_write(STDOUT_FILENO, rbuf, out_cnt);
@@ -1405,7 +1447,7 @@ static NOINLINE void cgi_io_loop_and_exit(int fromCgi_rd, int toCgi_wr, int post
out_cnt = -1; /* buffering off */
}
} else {
count = safe_read(fromCgi_rd, rbuf, PIPE_BUF);
count = safe_read(fromCgi_rd, rbuf, IOBUF_SIZE);
if (count <= 0)
break; /* eof (or error) */
}
@@ -1437,23 +1479,17 @@ static void setenv1(const char *name, const char *value)
* const char *url The requested URL (with leading /).
* const char *orig_uri The original URI before rewriting (if any)
* int post_len Length of the POST body.
* const char *cookie For set HTTP_COOKIE.
* const char *content_type For set CONTENT_TYPE.
*/
static void send_cgi_and_exit(
const char *url,
const char *orig_uri,
const char *request,
int post_len,
const char *cookie,
const char *content_type) NORETURN;
int post_len) NORETURN;
static void send_cgi_and_exit(
const char *url,
const char *orig_uri,
const char *request,
int post_len,
const char *cookie,
const char *content_type)
int post_len)
{
struct fd_pair fromCgi; /* CGI -> httpd pipe */
struct fd_pair toCgi; /* httpd -> CGI pipe */
@@ -1531,26 +1567,14 @@ static void send_cgi_and_exit(
#endif
}
}
setenv1("HTTP_USER_AGENT", G.user_agent);
if (G.http_accept)
setenv1("HTTP_ACCEPT", G.http_accept);
if (G.http_accept_language)
setenv1("HTTP_ACCEPT_LANGUAGE", G.http_accept_language);
if (post_len)
putenv(xasprintf("CONTENT_LENGTH=%u", post_len));
if (cookie)
setenv1("HTTP_COOKIE", cookie);
if (content_type)
setenv1("CONTENT_TYPE", content_type);
#if ENABLE_FEATURE_HTTPD_BASIC_AUTH
if (remoteuser) {
setenv1("REMOTE_USER", remoteuser);
putenv((char*)"AUTH_TYPE=Basic");
}
#endif
if (G.referer)
setenv1("HTTP_REFERER", G.referer);
setenv1("HTTP_HOST", G.host); /* set to "" if NULL */
/* setenv1("SERVER_NAME", safe_gethostname()); - don't do this,
* just run "env SERVER_NAME=xyz httpd ..." instead */
@@ -1702,8 +1726,10 @@ static NOINLINE void send_file_and_exit(const char *url, int what)
".jpg.jpeg\0" "image/jpeg\0"
".gif\0" "image/gif\0"
".png\0" "image/png\0"
".svg\0" "image/svg+xml\0"
/* .css line must be after .c line */
".css\0" "text/css\0"
".js\0" "application/javascript\0"
".wav\0" "audio/wav\0"
".avi\0" "video/x-msvideo\0"
".qt.mov\0" "video/quicktime\0"
@@ -1817,7 +1843,7 @@ static NOINLINE void send_file_and_exit(const char *url, int what)
log_and_exit();
}
static int checkPermIP(void)
static void if_ip_denied_send_HTTP_FORBIDDEN_and_exit(unsigned remote_ip)
{
Htaccess_IP *cur;
@@ -1836,11 +1862,15 @@ static int checkPermIP(void)
(unsigned char)(cur->mask)
);
#endif
if ((rmt_ip & cur->mask) == cur->ip)
return (cur->allow_deny == 'A'); /* A -> 1 */
if ((remote_ip & cur->mask) == cur->ip) {
if (cur->allow_deny == 'A')
return;
send_headers_and_exit(HTTP_FORBIDDEN);
}
}
return !flg_deny_all; /* depends on whether we saw "D:*" */
if (flg_deny_all) /* depends on whether we saw "D:*" */
send_headers_and_exit(HTTP_FORBIDDEN);
}
#if ENABLE_FEATURE_HTTPD_BASIC_AUTH
@@ -2077,12 +2107,15 @@ static void handle_incoming_and_exit(const len_and_sockaddr *fromAddr)
char *urlcopy;
char *urlp;
char *tptr;
unsigned remote_ip;
#if ENABLE_FEATURE_HTTPD_CGI
unsigned total_headers_len;
#endif
#if ENABLE_FEATURE_HTTPD_CGI
static const char request_HEAD[] ALIGN1 = "HEAD";
const char *prequest;
char *cookie = NULL;
char *content_type = NULL;
unsigned long length = 0;
enum CGI_type cgi_type = CGI_NONE;
#elif ENABLE_FEATURE_HTTPD_PROXY
#define prequest request_GET
unsigned long length = 0;
@@ -2090,29 +2123,22 @@ static void handle_incoming_and_exit(const len_and_sockaddr *fromAddr)
#if ENABLE_FEATURE_HTTPD_BASIC_AUTH
smallint authorized = -1;
#endif
smallint ip_allowed;
char http_major_version;
#if ENABLE_FEATURE_HTTPD_PROXY
char http_minor_version;
char *header_buf = header_buf; /* for gcc */
char *header_ptr = header_ptr;
Htaccess_Proxy *proxy_entry;
#endif
char *HTTP_slash;
/* Allocation of iobuf is postponed until now
* (IOW, server process doesn't need to waste 8k) */
iobuf = xmalloc(IOBUF_SIZE);
rmt_ip = 0;
remote_ip = 0;
if (fromAddr->u.sa.sa_family == AF_INET) {
rmt_ip = ntohl(fromAddr->u.sin.sin_addr.s_addr);
remote_ip = ntohl(fromAddr->u.sin.sin_addr.s_addr);
}
#if ENABLE_FEATURE_IPV6
if (fromAddr->u.sa.sa_family == AF_INET6
&& fromAddr->u.sin6.sin6_addr.s6_addr32[0] == 0
&& fromAddr->u.sin6.sin6_addr.s6_addr32[1] == 0
&& ntohl(fromAddr->u.sin6.sin6_addr.s6_addr32[2]) == 0xffff)
rmt_ip = ntohl(fromAddr->u.sin6.sin6_addr.s6_addr32[3]);
remote_ip = ntohl(fromAddr->u.sin6.sin6_addr.s6_addr32[3]);
#endif
if (ENABLE_FEATURE_HTTPD_CGI || DEBUG || verbose) {
/* NB: can be NULL (user runs httpd -i by hand?) */
@@ -2125,6 +2151,7 @@ static void handle_incoming_and_exit(const len_and_sockaddr *fromAddr)
if (verbose > 2)
bb_error_msg("connected");
}
if_ip_denied_send_HTTP_FORBIDDEN_and_exit(remote_ip);
/* Install timeout handler. get_line() needs it. */
signal(SIGALRM, send_REQUEST_TIMEOUT_and_exit);
@@ -2158,31 +2185,59 @@ static void handle_incoming_and_exit(const len_and_sockaddr *fromAddr)
if (urlp[0] != '/')
send_headers_and_exit(HTTP_BAD_REQUEST);
/* Find end of URL and parse HTTP version, if any */
http_major_version = '0';
IF_FEATURE_HTTPD_PROXY(http_minor_version = '0';)
tptr = strchrnul(urlp, ' ');
/* Find end of URL */
HTTP_slash = strchr(urlp, ' ');
/* Is it " HTTP/"? */
if (tptr[0] && strncmp(tptr + 1, HTTP_200, 5) == 0) {
http_major_version = tptr[6];
IF_FEATURE_HTTPD_PROXY(http_minor_version = tptr[8];)
}
*tptr = '\0';
if (!HTTP_slash || strncmp(HTTP_slash + 1, HTTP_200, 5) != 0)
send_headers_and_exit(HTTP_BAD_REQUEST);
*HTTP_slash++ = '\0';
/* Copy URL from after "GET "/"POST " to stack-allocated char[] */
urlcopy = alloca((tptr - urlp) + 2 + strlen(index_page));
urlcopy = alloca((HTTP_slash - urlp) + 2 + strlen(index_page));
/*if (urlcopy == NULL)
* send_headers_and_exit(HTTP_INTERNAL_SERVER_ERROR);*/
strcpy(urlcopy, urlp);
/* NB: urlcopy ptr is never changed after this */
/* Extract url args if present */
/* g_query = NULL; - already is */
tptr = strchr(urlcopy, '?');
if (tptr) {
*tptr++ = '\0';
g_query = tptr;
#if ENABLE_FEATURE_HTTPD_PROXY
{
int proxy_fd;
len_and_sockaddr *lsa;
Htaccess_Proxy *proxy_entry = find_proxy_entry(urlcopy);
if (proxy_entry) {
if (verbose > 1)
bb_error_msg("proxy:%s", urlcopy);
lsa = host2sockaddr(proxy_entry->host_port, 80);
if (!lsa)
send_headers_and_exit(HTTP_INTERNAL_SERVER_ERROR);
proxy_fd = socket(lsa->u.sa.sa_family, SOCK_STREAM, 0);
if (proxy_fd < 0)
send_headers_and_exit(HTTP_INTERNAL_SERVER_ERROR);
if (connect(proxy_fd, &lsa->u.sa, lsa->len) < 0)
send_headers_and_exit(HTTP_INTERNAL_SERVER_ERROR);
/* Disable peer header reading timeout */
alarm(0);
/* Config directive was of the form:
* P:/url:[http://]hostname[:port]/new/path
* When /urlSFX is requested, reverse proxy it
* to http://hostname[:port]/new/pathSFX
*/
fdprintf(proxy_fd, "%s %s%s %s\r\n",
prequest, /* "GET" or "POST" */
proxy_entry->url_to, /* "/new/path" */
urlcopy + strlen(proxy_entry->url_from), /* "SFX" */
HTTP_slash /* "HTTP/xyz" */
);
cgi_io_loop_and_exit(proxy_fd, proxy_fd, /*max POST length:*/ INT_MAX);
}
}
#endif
/* Extract url args if present */
g_query = strchr(urlcopy, '?');
if (g_query)
*g_query++ = '\0';
/* Decode URL escape sequences */
tptr = percent_decode_in_place(urlcopy, /*strict:*/ 1);
@@ -2222,7 +2277,7 @@ static void handle_incoming_and_exit(const len_and_sockaddr *fromAddr)
}
}
*++urlp = *tptr;
if (*urlp == '\0')
if (*tptr == '\0')
break;
next_char:
tptr++;
@@ -2240,193 +2295,17 @@ static void handle_incoming_and_exit(const len_and_sockaddr *fromAddr)
bb_error_msg("url:%s", urlcopy);
tptr = urlcopy;
ip_allowed = checkPermIP();
while (ip_allowed && (tptr = strchr(tptr + 1, '/')) != NULL) {
while ((tptr = strchr(tptr + 1, '/')) != NULL) {
/* have path1/path2 */
*tptr = '\0';
if (is_directory(urlcopy + 1, /*followlinks:*/ 1)) {
/* may have subdir config */
parse_conf(urlcopy + 1, SUBDIR_PARSE);
ip_allowed = checkPermIP();
if_ip_denied_send_HTTP_FORBIDDEN_and_exit(remote_ip);
}
*tptr = '/';
}
#if ENABLE_FEATURE_HTTPD_PROXY
proxy_entry = find_proxy_entry(urlcopy);
if (proxy_entry)
header_buf = header_ptr = xmalloc(IOBUF_SIZE);
#endif
if (http_major_version >= '0') {
/* Request was with "... HTTP/nXXX", and n >= 0 */
/* Read until blank line */
while (1) {
if (!get_line())
break; /* EOF or error or empty line */
if (DEBUG)
bb_error_msg("header: '%s'", iobuf);
#if ENABLE_FEATURE_HTTPD_PROXY
/* We need 2 more bytes for yet another "\r\n" -
* see near fdprintf(proxy_fd...) further below */
if (proxy_entry && (header_ptr - header_buf) < IOBUF_SIZE - 4) {
int len = strnlen(iobuf, IOBUF_SIZE - (header_ptr - header_buf) - 4);
memcpy(header_ptr, iobuf, len);
header_ptr += len;
header_ptr[0] = '\r';
header_ptr[1] = '\n';
header_ptr += 2;
}
#endif
#if ENABLE_FEATURE_HTTPD_CGI || ENABLE_FEATURE_HTTPD_PROXY
/* Try and do our best to parse more lines */
if ((STRNCASECMP(iobuf, "Content-Length:") == 0)) {
/* extra read only for POST */
if (prequest != request_GET
# if ENABLE_FEATURE_HTTPD_CGI
&& prequest != request_HEAD
# endif
) {
tptr = skip_whitespace(iobuf + sizeof("Content-Length:") - 1);
if (!tptr[0])
send_headers_and_exit(HTTP_BAD_REQUEST);
/* not using strtoul: it ignores leading minus! */
length = bb_strtou(tptr, NULL, 10);
/* length is "ulong", but we need to pass it to int later */
if (errno || length > INT_MAX)
send_headers_and_exit(HTTP_BAD_REQUEST);
}
}
#endif
#if ENABLE_FEATURE_HTTPD_CGI
else if (STRNCASECMP(iobuf, "Cookie:") == 0) {
if (!cookie) /* in case they send millions of these, do not OOM */
cookie = xstrdup(skip_whitespace(iobuf + sizeof("Cookie:")-1));
} else if (STRNCASECMP(iobuf, "Content-Type:") == 0) {
if (!content_type)
content_type = xstrdup(skip_whitespace(iobuf + sizeof("Content-Type:")-1));
} else if (STRNCASECMP(iobuf, "Referer:") == 0) {
if (!G.referer)
G.referer = xstrdup(skip_whitespace(iobuf + sizeof("Referer:")-1));
} else if (STRNCASECMP(iobuf, "User-Agent:") == 0) {
if (!G.user_agent)
G.user_agent = xstrdup(skip_whitespace(iobuf + sizeof("User-Agent:")-1));
} else if (STRNCASECMP(iobuf, "Host:") == 0) {
if (!G.host)
G.host = xstrdup(skip_whitespace(iobuf + sizeof("Host:")-1));
} else if (STRNCASECMP(iobuf, "Accept:") == 0) {
if (!G.http_accept)
G.http_accept = xstrdup(skip_whitespace(iobuf + sizeof("Accept:")-1));
} else if (STRNCASECMP(iobuf, "Accept-Language:") == 0) {
if (!G.http_accept_language)
G.http_accept_language = xstrdup(skip_whitespace(iobuf + sizeof("Accept-Language:")-1));
}
#endif
#if ENABLE_FEATURE_HTTPD_BASIC_AUTH
if (STRNCASECMP(iobuf, "Authorization:") == 0) {
/* We only allow Basic credentials.
* It shows up as "Authorization: Basic <user>:<passwd>" where
* "<user>:<passwd>" is base64 encoded.
*/
tptr = skip_whitespace(iobuf + sizeof("Authorization:")-1);
if (STRNCASECMP(tptr, "Basic") != 0)
continue;
tptr += sizeof("Basic")-1;
/* decodeBase64() skips whitespace itself */
decodeBase64(tptr);
authorized = check_user_passwd(urlcopy, tptr);
}
#endif
#if ENABLE_FEATURE_HTTPD_RANGES
if (STRNCASECMP(iobuf, "Range:") == 0) {
/* We know only bytes=NNN-[MMM] */
char *s = skip_whitespace(iobuf + sizeof("Range:")-1);
if (is_prefixed_with(s, "bytes=")) {
s += sizeof("bytes=")-1;
range_start = BB_STRTOOFF(s, &s, 10);
if (s[0] != '-' || range_start < 0) {
range_start = -1;
} else if (s[1]) {
range_end = BB_STRTOOFF(s+1, NULL, 10);
if (errno || range_end < range_start)
range_start = -1;
}
}
}
#endif
#if ENABLE_FEATURE_HTTPD_GZIP
if (STRNCASECMP(iobuf, "Accept-Encoding:") == 0) {
/* Note: we do not support "gzip;q=0"
* method of _disabling_ gzip
* delivery. No one uses that, though */
const char *s = strstr(iobuf, "gzip");
if (s) {
// want more thorough checks?
//if (s[-1] == ' '
// || s[-1] == ','
// || s[-1] == ':'
//) {
content_gzip = 1;
//}
}
}
#endif
} /* while extra header reading */
}
/* We are done reading headers, disable peer timeout */
alarm(0);
if (strcmp(bb_basename(urlcopy), HTTPD_CONF) == 0 || !ip_allowed) {
/* protect listing [/path]/httpd.conf or IP deny */
send_headers_and_exit(HTTP_FORBIDDEN);
}
#if ENABLE_FEATURE_HTTPD_BASIC_AUTH
/* Case: no "Authorization:" was seen, but page might require passwd.
* Check that with dummy user:pass */
if (authorized < 0)
authorized = check_user_passwd(urlcopy, (char *) "");
if (!authorized)
send_headers_and_exit(HTTP_UNAUTHORIZED);
#endif
if (found_moved_temporarily) {
send_headers_and_exit(HTTP_MOVED_TEMPORARILY);
}
#if ENABLE_FEATURE_HTTPD_PROXY
if (proxy_entry != NULL) {
int proxy_fd;
len_and_sockaddr *lsa;
lsa = host2sockaddr(proxy_entry->host_port, 80);
if (lsa == NULL)
send_headers_and_exit(HTTP_INTERNAL_SERVER_ERROR);
proxy_fd = socket(lsa->u.sa.sa_family, SOCK_STREAM, 0);
if (proxy_fd < 0)
send_headers_and_exit(HTTP_INTERNAL_SERVER_ERROR);
if (connect(proxy_fd, &lsa->u.sa, lsa->len) < 0)
send_headers_and_exit(HTTP_INTERNAL_SERVER_ERROR);
fdprintf(proxy_fd, "%s %s%s%s%s HTTP/%c.%c\r\n",
prequest, /* GET or POST */
proxy_entry->url_to, /* url part 1 */
urlcopy + strlen(proxy_entry->url_from), /* url part 2 */
(g_query ? "?" : ""), /* "?" (maybe) */
(g_query ? g_query : ""), /* query string (maybe) */
http_major_version, http_minor_version);
header_ptr[0] = '\r';
header_ptr[1] = '\n';
header_ptr += 2;
write(proxy_fd, header_buf, header_ptr - header_buf);
free(header_buf); /* on the order of 8k, free it */
cgi_io_loop_and_exit(proxy_fd, proxy_fd, length);
}
#endif
tptr = urlcopy + 1; /* skip first '/' */
#if ENABLE_FEATURE_HTTPD_CGI
@@ -2435,7 +2314,7 @@ static void handle_incoming_and_exit(const len_and_sockaddr *fromAddr)
/* protect listing "cgi-bin/" */
send_headers_and_exit(HTTP_FORBIDDEN);
}
send_cgi_and_exit(urlcopy, urlcopy, prequest, length, cookie, content_type);
cgi_type = CGI_NORMAL;
}
#endif
@@ -2456,25 +2335,186 @@ static void handle_incoming_and_exit(const len_and_sockaddr *fromAddr)
Htaccess *cur;
for (cur = script_i; cur; cur = cur->next) {
if (strcmp(cur->before_colon + 1, suffix) == 0) {
send_cgi_and_exit(urlcopy, urlcopy, prequest, length, cookie, content_type);
cgi_type = CGI_INTERPRETER;
break;
}
}
}
#endif
file_size = sb.st_size;
last_mod = sb.st_mtime;
if (!found_moved_temporarily) {
file_size = sb.st_size;
last_mod = sb.st_mtime;
}
}
#if ENABLE_FEATURE_HTTPD_CGI
else if (urlp[-1] == '/') {
/* It's a dir URL and there is no index.html
* Try cgi-bin/index.cgi */
if (access("/cgi-bin/index.cgi"+1, X_OK) == 0) {
urlp[0] = '\0'; /* remove index_page */
send_cgi_and_exit("/cgi-bin/index.cgi", urlcopy, prequest, length, cookie, content_type);
cgi_type = CGI_INDEX;
}
}
/* else fall through to send_file, it errors out if open fails: */
#endif
urlp[0] = '\0';
#if ENABLE_FEATURE_HTTPD_CGI
total_headers_len = 0;
#endif
/* Read until blank line */
while (1) {
unsigned iobuf_len = get_line();
if (!iobuf_len)
break; /* EOF or error or empty line */
#if ENABLE_FEATURE_HTTPD_CGI
/* Prevent unlimited growth of HTTP_xyz envvars */
total_headers_len += iobuf_len;
if (total_headers_len >= MAX_HTTP_HEADERS_SIZE)
send_headers_and_exit(HTTP_ENTITY_TOO_LARGE);
#endif
if (DEBUG)
bb_error_msg("header: '%s'", iobuf);
#if ENABLE_FEATURE_HTTPD_CGI || ENABLE_FEATURE_HTTPD_PROXY
/* Try and do our best to parse more lines */
if (STRNCASECMP(iobuf, "Content-Length:") == 0) {
/* extra read only for POST */
if (prequest != request_GET
# if ENABLE_FEATURE_HTTPD_CGI
&& prequest != request_HEAD
# endif
) {
tptr = skip_whitespace(iobuf + sizeof("Content-Length:") - 1);
if (!tptr[0])
send_headers_and_exit(HTTP_BAD_REQUEST);
/* not using strtoul: it ignores leading minus! */
length = bb_strtou(tptr, NULL, 10);
/* length is "ulong", but we need to pass it to int later */
if (errno || length > INT_MAX)
send_headers_and_exit(HTTP_BAD_REQUEST);
}
continue;
}
#endif
#if ENABLE_FEATURE_HTTPD_BASIC_AUTH
if (STRNCASECMP(iobuf, "Authorization:") == 0) {
/* We only allow Basic credentials.
* It shows up as "Authorization: Basic <user>:<passwd>" where
* "<user>:<passwd>" is base64 encoded.
*/
tptr = skip_whitespace(iobuf + sizeof("Authorization:")-1);
if (STRNCASECMP(tptr, "Basic") == 0) {
tptr += sizeof("Basic")-1;
/* decodeBase64() skips whitespace itself */
decodeBase64(tptr);
authorized = check_user_passwd(urlcopy, tptr);
continue;
}
}
#endif
#if ENABLE_FEATURE_HTTPD_RANGES
if (STRNCASECMP(iobuf, "Range:") == 0) {
/* We know only bytes=NNN-[MMM] */
char *s = skip_whitespace(iobuf + sizeof("Range:")-1);
if (is_prefixed_with(s, "bytes=")) {
s += sizeof("bytes=")-1;
range_start = BB_STRTOOFF(s, &s, 10);
if (s[0] != '-' || range_start < 0) {
range_start = -1;
} else if (s[1]) {
range_end = BB_STRTOOFF(s+1, NULL, 10);
if (errno || range_end < range_start)
range_start = -1;
}
}
continue;
}
#endif
#if ENABLE_FEATURE_HTTPD_GZIP
if (STRNCASECMP(iobuf, "Accept-Encoding:") == 0) {
/* Note: we do not support "gzip;q=0"
* method of _disabling_ gzip
* delivery. No one uses that, though */
const char *s = strstr(iobuf, "gzip");
if (s) {
// want more thorough checks?
//if (s[-1] == ' '
// || s[-1] == ','
// || s[-1] == ':'
//) {
content_gzip = 1;
//}
}
continue;
}
#endif
#if ENABLE_FEATURE_HTTPD_CGI
if (cgi_type != CGI_NONE) {
bool ct = (STRNCASECMP(iobuf, "Content-Type:") == 0);
char *cp;
char *colon = strchr(iobuf, ':');
if (!colon)
continue;
cp = iobuf;
while (cp < colon) {
/* a-z => A-Z, not-alnum => _ */
char c = (*cp & ~0x20); /* toupper for A-Za-z, undef for others */
if ((unsigned)(c - 'A') <= ('Z' - 'A')) {
*cp++ = c;
continue;
}
if (!isdigit(*cp))
*cp = '_';
cp++;
}
/* "Content-Type:" gets no HTTP_ prefix, all others do */
cp = xasprintf(ct ? "HTTP_%.*s=%s" + 5 : "HTTP_%.*s=%s",
(int)(colon - iobuf), iobuf,
skip_whitespace(colon + 1)
);
putenv(cp);
}
#endif
} /* while extra header reading */
/* We are done reading headers, disable peer timeout */
alarm(0);
if (strcmp(bb_basename(urlcopy), HTTPD_CONF) == 0) {
/* protect listing [/path]/httpd.conf or IP deny */
send_headers_and_exit(HTTP_FORBIDDEN);
}
#if ENABLE_FEATURE_HTTPD_BASIC_AUTH
/* Case: no "Authorization:" was seen, but page might require passwd.
* Check that with dummy user:pass */
if (authorized < 0)
authorized = check_user_passwd(urlcopy, (char *) "");
if (!authorized)
send_headers_and_exit(HTTP_UNAUTHORIZED);
#endif
if (found_moved_temporarily) {
send_headers_and_exit(HTTP_MOVED_TEMPORARILY);
}
tptr = urlcopy + 1; /* skip first '/' */
#if ENABLE_FEATURE_HTTPD_CGI
if (cgi_type != CGI_NONE) {
send_cgi_and_exit(
(cgi_type == CGI_INDEX) ? "/cgi-bin/index.cgi"
/*CGI_NORMAL or CGI_INTERPRETER*/ : urlcopy,
urlcopy, prequest, length
);
}
#endif
if (urlp[-1] == '/') {
strcpy(urlp, index_page);
}
#if ENABLE_FEATURE_HTTPD_CGI
if (prequest != request_GET && prequest != request_HEAD) {
/* POST for files does not make sense */
send_headers_and_exit(HTTP_NOT_IMPLEMENTED);
@@ -2593,7 +2633,9 @@ static void mini_httpd_inetd(void)
static void sighup_handler(int sig UNUSED_PARAM)
{
int sv = errno;
parse_conf(DEFAULT_PATH_HTTPD_CONF, SIGNALED_PARSE);
errno = sv;
}
enum {
+11 -19
View File
@@ -326,7 +326,7 @@ static int run_script(const char *action)
char *argv[5];
int r;
bb_error_msg("executing '%s %s %s'", G.script_name, G.iface, action);
bb_info_msg("executing '%s %s %s'", G.script_name, G.iface, action);
argv[0] = (char*) G.script_name;
argv[1] = (char*) G.iface;
@@ -345,7 +345,7 @@ static int run_script(const char *action)
bb_unsetenv_and_free(env_PREVIOUS);
bb_unsetenv_and_free(env_CURRENT);
bb_error_msg("exit code: %d", r & 0xff);
bb_info_msg("exit code: %d", r & 0xff);
return (option_mask32 & FLAG_IGNORE_RETVAL) ? 0 : r;
}
@@ -365,7 +365,7 @@ static void up_iface(void)
if (!(ifrequest.ifr_flags & IFF_UP)) {
ifrequest.ifr_flags |= IFF_UP;
/* Let user know we mess up with interface */
bb_error_msg("upping interface");
bb_info_msg("upping interface");
if (network_ioctl(SIOCSIFFLAGS, &ifrequest, "setting interface flags") < 0) {
if (errno != ENODEV && errno != EADDRNOTAVAIL)
xfunc_die();
@@ -414,7 +414,7 @@ static void maybe_up_new_iface(void)
(uint8_t)(ifrequest.ifr_hwaddr.sa_data[5]));
}
bb_error_msg("using interface %s%s with driver<%s> (version: %s)",
bb_info_msg("using interface %s%s with driver<%s> (version: %s)",
G.iface, buf, driver_info.driver, driver_info.version);
}
#endif
@@ -447,7 +447,7 @@ static smallint detect_link(void)
logmode = sv_logmode;
if (status != IFSTATUS_ERR) {
G.api_method_num = i;
bb_error_msg("using %s detection mode", method_table[i].name);
bb_info_msg("using %s detection mode", method_table[i].name);
break;
}
}
@@ -604,15 +604,7 @@ int ifplugd_main(int argc UNUSED_PARAM, char **argv)
xmove_fd(xsocket(AF_INET, SOCK_DGRAM, 0), ioctl_fd);
if (opts & FLAG_MONITOR) {
struct sockaddr_nl addr;
int fd = xsocket(PF_NETLINK, SOCK_DGRAM, NETLINK_ROUTE);
memset(&addr, 0, sizeof(addr));
addr.nl_family = AF_NETLINK;
addr.nl_groups = RTMGRP_LINK;
addr.nl_pid = getpid();
xbind(fd, (struct sockaddr*)&addr, sizeof(addr));
int fd = create_and_bind_to_netlink(NETLINK_ROUTE, RTMGRP_LINK, 0);
xmove_fd(fd, netlink_fd);
}
@@ -632,7 +624,7 @@ int ifplugd_main(int argc UNUSED_PARAM, char **argv)
/* | (1 << SIGCHLD) - run_script does not use it anymore */
, record_signo);
bb_error_msg("started: %s", bb_banner);
bb_info_msg("started: %s", bb_banner);
if (opts & FLAG_MONITOR) {
struct ifreq ifrequest;
@@ -649,7 +641,7 @@ int ifplugd_main(int argc UNUSED_PARAM, char **argv)
iface_status_str = strstatus(iface_status);
if (opts & FLAG_MONITOR) {
bb_error_msg("interface %s",
bb_info_msg("interface %s",
G.iface_exists ? "exists"
: "doesn't exist, waiting");
}
@@ -657,7 +649,7 @@ int ifplugd_main(int argc UNUSED_PARAM, char **argv)
* by potentially lying that it really exists */
if (G.iface_exists) {
bb_error_msg("link is %s", iface_status_str);
bb_info_msg("link is %s", iface_status_str);
}
if ((!(opts & FLAG_NO_STARTUP)
@@ -712,7 +704,7 @@ int ifplugd_main(int argc UNUSED_PARAM, char **argv)
if (G.iface_exists < 0) /* error */
goto exiting;
if (iface_exists_old != G.iface_exists) {
bb_error_msg("interface %sappeared",
bb_info_msg("interface %sappeared",
G.iface_exists ? "" : "dis");
if (G.iface_exists)
maybe_up_new_iface();
@@ -730,7 +722,7 @@ int ifplugd_main(int argc UNUSED_PARAM, char **argv)
iface_status_str = strstatus(iface_status);
if (iface_status_old != iface_status) {
bb_error_msg("link is %s", iface_status_str);
bb_info_msg("link is %s", iface_status_str);
if (delay_time) {
/* link restored its old status before
+9 -3
View File
@@ -1177,8 +1177,15 @@ static int doit(char *str)
static int execute_all(struct interface_defn_t *ifd, const char *opt)
{
/* 'opt' is always short, the longest value is "post-down".
* Can use on-stack buffer instead of xasprintf'ed one.
*/
char buf[sizeof("run-parts /etc/network/if-%s.d")
+ sizeof("post-down")
/*paranoia:*/ + 8
];
int i;
char *buf;
for (i = 0; i < ifd->n_options; i++) {
if (strcmp(ifd->option[i].name, opt) == 0) {
if (!doit(ifd->option[i].value)) {
@@ -1192,8 +1199,7 @@ static int execute_all(struct interface_defn_t *ifd, const char *opt)
* complains, and this message _is_ annoyingly visible.
* Don't "fix" this (unless newer Debian does).
*/
buf = xasprintf("run-parts /etc/network/if-%s.d", opt);
/* heh, we don't bother free'ing it */
sprintf(buf, "run-parts /etc/network/if-%s.d", opt);
return doit(buf);
}
+2 -2
View File
@@ -1207,7 +1207,7 @@ static void clean_up_and_exit(int sig UNUSED_PARAM)
if (ENABLE_FEATURE_CLEAN_UP)
close(sep->se_fd);
}
remove_pidfile(CONFIG_PID_FILE_PATH "/inetd.pid");
remove_pidfile_std_path_and_ext("inetd");
exit(EXIT_SUCCESS);
}
@@ -1256,7 +1256,7 @@ int inetd_main(int argc UNUSED_PARAM, char **argv)
setgroups(1, &gid);
}
write_pidfile(CONFIG_PID_FILE_PATH "/inetd.pid");
write_pidfile_std_path_and_ext("inetd");
/* never fails under Linux (except if you pass it bad arguments) */
getrlimit(RLIMIT_NOFILE, &rlim_ofile);
+10 -8
View File
@@ -23,6 +23,7 @@
struct filter_t {
char *label;
/* Flush cmd buf. If !NULL, print_addrinfo() constructs flush commands in it */
char *flushb;
struct rtnl_handle *rth;
int scope, scopemask;
@@ -34,6 +35,8 @@ struct filter_t {
smallint showqueue;
smallint oneline;
smallint up;
/* Misnomer. Does not mean "flushed something" */
/* More like "flush commands were constructed by print_addrinfo()" */
smallint flushed;
inet_prefix pfx;
} FIX_ALIASING;
@@ -201,7 +204,7 @@ static NOINLINE int print_linkinfo(const struct nlmsghdr *n)
static int flush_update(void)
{
if (rtnl_send(G_filter.rth, G_filter.flushb, G_filter.flushp) < 0) {
if (rtnl_send_check(G_filter.rth, G_filter.flushb, G_filter.flushp) < 0) {
bb_perror_msg("can't send flush request");
return -1;
}
@@ -327,6 +330,10 @@ static int FAST_FUNC print_addrinfo(const struct sockaddr_nl *who UNUSED_PARAM,
ifa->ifa_flags &= ~IFA_F_TENTATIVE;
printf("tentative ");
}
if (ifa->ifa_flags & IFA_F_DADFAILED) {
ifa->ifa_flags &= ~IFA_F_DADFAILED;
printf("dadfailed ");
}
if (ifa->ifa_flags & IFA_F_DEPRECATED) {
ifa->ifa_flags &= ~IFA_F_DEPRECATED;
printf("deprecated ");
@@ -420,7 +427,6 @@ int FAST_FUNC ipaddr_list_or_flush(char **argv, int flush)
struct nlmsg_list *l;
struct rtnl_handle rth;
char *filter_dev = NULL;
int no_link = 0;
ipaddr_reset_filter(oneline);
G_filter.showqueue = 1;
@@ -507,14 +513,10 @@ int FAST_FUNC ipaddr_list_or_flush(char **argv, int flush)
xrtnl_dump_filter(&rth, store_nlmsg, &ainfo);
}
if (G_filter.family && G_filter.family != AF_PACKET) {
struct nlmsg_list **lp;
lp = &linfo;
if (G_filter.oneline)
no_link = 1;
while ((l = *lp) != NULL) {
int ok = 0;
struct ifinfomsg *ifi = NLMSG_DATA(&l->h);
@@ -570,9 +572,9 @@ int FAST_FUNC ipaddr_list_or_flush(char **argv, int flush)
}
for (l = linfo; l; l = l->next) {
if (no_link
|| (oneline || print_linkinfo(&l->h) == 0)
if ((oneline && G_filter.family != AF_PACKET)
/* ^^^^^^^^^ "ip -oneline a" does not print link info */
|| (print_linkinfo(&l->h) == 0)
) {
struct ifinfomsg *ifi = NLMSG_DATA(&l->h);
if (G_filter.family != AF_PACKET)
+12 -6
View File
@@ -490,11 +490,11 @@ static void vlan_parse_opt(char **argv, struct nlmsghdr *n, unsigned int size)
;
enum {
ARG_id = 0,
ARG_protocol,
ARG_reorder_hdr,
ARG_gvrp,
ARG_mvrp,
ARG_loose_binding,
ARG_protocol,
};
enum {
PROTO_8021Q = 0,
@@ -518,11 +518,11 @@ static void vlan_parse_opt(char **argv, struct nlmsghdr *n, unsigned int size)
id = get_u16(*argv, "id");
addattr_l(n, size, IFLA_VLAN_ID, &id, sizeof(id));
} else if (arg == ARG_protocol) {
arg = index_in_substrings(protocols, *argv);
arg = index_in_substrings(protocols, str_tolower(*argv));
if (arg == PROTO_8021Q)
proto = ETH_P_8021Q;
proto = htons(ETH_P_8021Q);
else if (arg == PROTO_8021AD)
proto = ETH_P_8021AD;
proto = htons(ETH_P_8021AD);
else
bb_error_msg_and_die("unknown VLAN encapsulation protocol '%s'",
*argv);
@@ -673,13 +673,19 @@ static int do_add_or_delete(char **argv, const unsigned rtm)
linkinfo->rta_len = (void *)NLMSG_TAIL(&req.n) - (void *)linkinfo;
}
/* Allow "ip link add dev" and "ip link add name" */
if (!name_str)
name_str = dev_str;
else if (!dev_str)
dev_str = name_str;
/* else if (!strcmp(name_str, dev_str))
name_str = dev_str; */
if (rtm != RTM_NEWLINK) {
if (!dev_str)
return 1; /* Need a device to delete */
req.i.ifi_index = xll_name_to_index(dev_str);
} else {
if (!name_str)
name_str = dev_str;
if (link_str) {
int idx = xll_name_to_index(link_str);
addattr_l(&req.n, sizeof(req), IFLA_LINK, &idx, 4);
+5 -4
View File
@@ -32,7 +32,10 @@ struct filter_t {
int state;
int unused_only;
inet_prefix pfx;
/* Misnomer. Does not mean "flushed N something" */
/* More like "no_of_flush_commands_constructed_by_print_neigh()" */
int flushed;
/* Flush cmd buf. If !NULL, print_neigh() constructs flush commands in it */
char *flushb;
int flushp;
int flushe;
@@ -45,7 +48,7 @@ typedef struct filter_t filter_t;
static int flush_update(void)
{
if (rtnl_send(G_filter.rth, G_filter.flushb, G_filter.flushp) < 0) {
if (rtnl_send_check(G_filter.rth, G_filter.flushb, G_filter.flushp) < 0) {
bb_perror_msg("can't send flush request");
return -1;
}
@@ -299,9 +302,7 @@ static int FAST_FUNC ipneigh_list_or_flush(char **argv, int flush)
G_filter.rth = &rth;
while (round < MAX_ROUNDS) {
if (xrtnl_wilddump_request(&rth, G_filter.family, RTM_GETNEIGH) < 0) {
bb_perror_msg_and_die("can't send dump request");
}
xrtnl_wilddump_request(&rth, G_filter.family, RTM_GETNEIGH);
G_filter.flushed = 0;
if (xrtnl_dump_filter(&rth, print_neigh, NULL) < 0) {
bb_perror_msg_and_die("flush terminated");
+4 -1
View File
@@ -26,7 +26,10 @@
struct filter_t {
int tb;
/* Misnomer. Does not mean "flushed something" */
/* More like "flush commands were constructed by print_route()" */
smallint flushed;
/* Flush cmd buf. If !NULL, print_route() constructs flush commands in it */
char *flushb;
int flushp;
int flushe;
@@ -53,7 +56,7 @@ typedef struct filter_t filter_t;
static int flush_update(void)
{
if (rtnl_send(G_filter.rth, G_filter.flushb, G_filter.flushp) < 0) {
if (rtnl_send_check(G_filter.rth, G_filter.flushb, G_filter.flushp) < 0) {
bb_perror_msg("can't send flush request");
return -1;
}
+35 -8
View File
@@ -34,7 +34,7 @@ void FAST_FUNC xrtnl_open(struct rtnl_handle *rth/*, unsigned subscriptions*/)
rth->seq = time(NULL);
}
int FAST_FUNC xrtnl_wilddump_request(struct rtnl_handle *rth, int family, int type)
void FAST_FUNC xrtnl_wilddump_request(struct rtnl_handle *rth, int family, int type)
{
struct {
struct nlmsghdr nlh;
@@ -48,18 +48,45 @@ int FAST_FUNC xrtnl_wilddump_request(struct rtnl_handle *rth, int family, int ty
req.nlh.nlmsg_seq = rth->dump = ++rth->seq;
req.g.rtgen_family = family;
return rtnl_send(rth, (void*)&req, sizeof(req));
rtnl_send(rth, (void*)&req, sizeof(req));
}
//TODO: pass rth->fd instead of full rth?
int FAST_FUNC rtnl_send(struct rtnl_handle *rth, char *buf, int len)
/* A version which checks for e.g. EPERM errors.
* Try: setuidgid 1:1 ip addr flush dev eth0
*/
int FAST_FUNC rtnl_send_check(struct rtnl_handle *rth, const void *buf, int len)
{
struct sockaddr_nl nladdr;
struct nlmsghdr *h;
int status;
char resp[1024];
memset(&nladdr, 0, sizeof(nladdr));
nladdr.nl_family = AF_NETLINK;
status = write(rth->fd, buf, len);
if (status < 0)
return status;
return xsendto(rth->fd, buf, len, (struct sockaddr*)&nladdr, sizeof(nladdr));
/* Check for immediate errors */
status = recv(rth->fd, resp, sizeof(resp), MSG_DONTWAIT|MSG_PEEK);
if (status < 0) {
if (errno == EAGAIN) /* if no error, this happens */
return 0;
return -1;
}
for (h = (struct nlmsghdr *)resp;
NLMSG_OK(h, status);
h = NLMSG_NEXT(h, status)
) {
if (h->nlmsg_type == NLMSG_ERROR) {
struct nlmsgerr *err = (struct nlmsgerr*)NLMSG_DATA(h);
if (h->nlmsg_len < NLMSG_LENGTH(sizeof(struct nlmsgerr)))
bb_error_msg("ERROR truncated");
else
errno = -err->error;
return -1;
}
}
return 0;
}
int FAST_FUNC rtnl_dump_request(struct rtnl_handle *rth, int type, void *req, int len)
+17 -2
View File
@@ -20,7 +20,7 @@ struct rtnl_handle {
extern void xrtnl_open(struct rtnl_handle *rth) FAST_FUNC;
#define rtnl_close(rth) (close((rth)->fd))
extern int xrtnl_wilddump_request(struct rtnl_handle *rth, int fam, int type) FAST_FUNC;
extern void xrtnl_wilddump_request(struct rtnl_handle *rth, int fam, int type) FAST_FUNC;
extern int rtnl_dump_request(struct rtnl_handle *rth, int type, void *req, int len) FAST_FUNC;
extern int xrtnl_dump_filter(struct rtnl_handle *rth,
int (*filter)(const struct sockaddr_nl*, struct nlmsghdr *n, void*) FAST_FUNC,
@@ -34,8 +34,23 @@ extern int rtnl_talk(struct rtnl_handle *rtnl, struct nlmsghdr *n, pid_t peer,
int (*junk)(struct sockaddr_nl *,struct nlmsghdr *n, void *),
void *jarg) FAST_FUNC;
extern int rtnl_send(struct rtnl_handle *rth, char *buf, int) FAST_FUNC;
int rtnl_send_check(struct rtnl_handle *rth, const void *buf, int len) FAST_FUNC;
//TODO: pass rth->fd instead of full rth?
static ALWAYS_INLINE void rtnl_send(struct rtnl_handle *rth, const void *buf, int len)
{
// Used to be:
//struct sockaddr_nl nladdr;
//memset(&nladdr, 0, sizeof(nladdr));
//nladdr.nl_family = AF_NETLINK;
//return xsendto(rth->fd, buf, len, (struct sockaddr*)&nladdr, sizeof(nladdr));
// iproute2-4.2.0 simplified the above to:
//return send(rth->fd, buf, len, 0);
// We are using even shorter:
xwrite(rth->fd, buf, len);
// and convert to void, inline.
}
extern int addattr32(struct nlmsghdr *n, int maxlen, int type, uint32_t data) FAST_FUNC;
extern int addattr_l(struct nlmsghdr *n, int maxlen, int type, void *data, int alen) FAST_FUNC;
+1 -1
View File
@@ -15,7 +15,7 @@
/* Please conditionalize exotic protocols on CONFIG_something */
static const uint16_t llproto_ids[] = {
static const uint16_t llproto_ids[] ALIGN2 = {
#define __PF(f,n) ETH_P_##f,
__PF(LOOP,loop)
__PF(PUP,pup)
+8 -4
View File
@@ -257,7 +257,7 @@ int nslookup_main(int argc, char **argv)
struct ns {
const char *name;
len_and_sockaddr *lsa;
int failures;
//UNUSED: int failures;
int replies;
};
@@ -320,6 +320,7 @@ struct globals {
struct query *query;
char *search;
smalluint have_search_directive;
smalluint exitcode;
} FIX_ALIASING;
#define G (*(struct globals*)bb_common_bufsiz1)
#define INIT_G() do { \
@@ -593,7 +594,7 @@ static int send_queries(struct ns *ns)
/* Retry immediately on SERVFAIL */
if (rcode == 2) {
ns->failures++;
//UNUSED: ns->failures++;
if (servfail_retry) {
servfail_retry--;
write(pfd.fd, G.query[qn].query, G.query[qn].qlen);
@@ -612,9 +613,12 @@ static int send_queries(struct ns *ns)
if (rcode != 0) {
printf("** server can't find %s: %s\n",
G.query[qn].name, rcodes[rcode]);
G.exitcode = EXIT_FAILURE;
} else {
if (parse_reply(reply, recvlen) < 0)
if (parse_reply(reply, recvlen) < 0) {
printf("*** Can't find %s: Parse error\n", G.query[qn].name);
G.exitcode = EXIT_FAILURE;
}
}
bb_putchar('\n');
n_replies++;
@@ -988,7 +992,7 @@ int nslookup_main(int argc UNUSED_PARAM, char **argv)
free(G.query);
}
return EXIT_SUCCESS;
return G.exitcode;
}
#endif
+11 -10
View File
@@ -177,12 +177,11 @@
*/
#define STEP_THRESHOLD 1
/* Slew threshold (sec): adjtimex() won't accept offsets larger than this.
* Using exact power of 2 (1/8) results in smaller code
* Using exact power of 2 (1/8, 1/2 etc) results in smaller code
*/
#define SLEW_THRESHOLD 0.125
//^^^^^^^^^^^^^^^^^^^^^^^^^^ TODO: man adjtimex about tmx.offset:
// "Since Linux 2.6.26, the supplied value is clamped to the range (-0.5s, +0.5s)"
// - can use this larger value instead?
#define SLEW_THRESHOLD 0.5
// ^^^^ used to be 0.125.
// Since Linux 2.6.26 (circa 2006), kernel accepts (-0.5s, +0.5s) range
/* Stepout threshold (sec). std ntpd uses 900 (11 mins (!)) */
//UNUSED: #define WATCH_THRESHOLD 128
@@ -1131,7 +1130,7 @@ step_time(double offset)
}
tval = tvn.tv_sec;
strftime_YYYYMMDDHHMMSS(buf, sizeof(buf), &tval);
bb_error_msg("setting time to %s.%06u (offset %+fs)", buf, (unsigned)tvn.tv_usec, offset);
bb_info_msg("setting time to %s.%06u (offset %+fs)", buf, (unsigned)tvn.tv_usec, offset);
//maybe? G.FREQHOLD_cnt = 0;
/* Correct various fields which contain time-relative values: */
@@ -2133,7 +2132,7 @@ recv_and_process_peer_pkt(peer_t *p)
p->reachable_bits |= 1;
if ((MAX_VERBOSE && G.verbose) || (option_mask32 & OPT_w)) {
bb_error_msg("reply from %s: offset:%+f delay:%f status:0x%02x strat:%d refid:0x%08x rootdelay:%f reach:0x%02x",
bb_info_msg("reply from %s: offset:%+f delay:%f status:0x%02x strat:%d refid:0x%08x rootdelay:%f reach:0x%02x",
p->p_dotted,
offset,
p->p_raw_delay,
@@ -2586,6 +2585,10 @@ static NOINLINE void ntp_init(char **argv)
/* -l but no peers: "stratum 1 server" mode */
G.stratum = 1;
}
if (!(opts & OPT_n)) /* only if backgrounded: */
write_pidfile_std_path_and_ext("ntpd");
/* If network is up, syncronization occurs in ~10 seconds.
* We give "ntpd -q" 10 seconds to get first reply,
* then another 50 seconds to finish syncing.
@@ -2642,8 +2645,6 @@ int ntpd_main(int argc UNUSED_PARAM, char **argv)
*/
cnt = G.peer_cnt * (INITIAL_SAMPLES + 1);
write_pidfile(CONFIG_PID_FILE_PATH "/ntpd.pid");
while (!bb_got_signal) {
llist_t *item;
unsigned i, j;
@@ -2815,7 +2816,7 @@ int ntpd_main(int argc UNUSED_PARAM, char **argv)
}
} /* while (!bb_got_signal) */
remove_pidfile(CONFIG_PID_FILE_PATH "/ntpd.pid");
remove_pidfile_std_path_and_ext("ntpd");
kill_myself_with_sig(bb_got_signal);
}
+4 -2
View File
@@ -124,7 +124,8 @@ static char* print_tc_classid(uint32_t cid)
}
/* Get a qdisc handle. Return 0 on success, !0 otherwise. */
static int get_qdisc_handle(uint32_t *h, const char *str) {
static int get_qdisc_handle(uint32_t *h, const char *str)
{
uint32_t maj;
char *p;
@@ -143,7 +144,8 @@ static int get_qdisc_handle(uint32_t *h, const char *str) {
}
/* Get class ID. Return 0 on success, !0 otherwise. */
static int get_tc_classid(uint32_t *h, const char *str) {
static int get_tc_classid(uint32_t *h, const char *str)
{
uint32_t maj, min;
char *p;
+99 -108
View File
@@ -94,19 +94,19 @@ enum {
IACBUFSIZE = 128,
CHM_TRY = 0,
CHM_ON = 1,
CHM_ON = 1,
CHM_OFF = 2,
UF_ECHO = 0x01,
UF_SGA = 0x02,
UF_SGA = 0x02,
TS_NORMAL = 0,
TS_COPY = 1,
TS_IAC = 2,
TS_OPT = 3,
TS_IAC = 2,
TS_OPT = 3,
TS_SUB1 = 4,
TS_SUB2 = 5,
TS_CR = 6,
TS_CR = 6,
};
typedef unsigned char byte;
@@ -152,8 +152,10 @@ static void subneg(byte c);
static void iac_flush(void)
{
full_write(netfd, G.iacbuf, G.iaclen);
G.iaclen = 0;
if (G.iaclen != 0) {
full_write(netfd, G.iacbuf, G.iaclen);
G.iaclen = 0;
}
}
static void doexit(int ev) NORETURN;
@@ -244,25 +246,34 @@ static void handle_net_output(int len)
static void handle_net_input(int len)
{
byte c;
int i;
int cstart = 0;
for (i = 0; i < len; i++) {
byte c = G.buf[i];
if (G.telstate == TS_NORMAL) { /* most typical state */
if (c == IAC) {
cstart = i;
G.telstate = TS_IAC;
}
else if (c == '\r') {
cstart = i + 1;
G.telstate = TS_CR;
}
/* No IACs were seen so far, no need to copy
* bytes within G.buf: */
continue;
i = 0;
//bb_error_msg("[%u,'%.*s']", G.telstate, len, G.buf);
if (G.telstate == TS_NORMAL) { /* most typical state */
while (i < len) {
c = G.buf[i];
i++;
if (c == IAC) /* unlikely */
goto got_IAC;
if (c != '\r') /* likely */
continue;
G.telstate = TS_CR;
cstart = i;
goto got_special;
}
full_write(STDOUT_FILENO, G.buf, len);
return;
got_IAC:
G.telstate = TS_IAC;
cstart = i - 1;
got_special: ;
}
for (; i < len; i++) {
c = G.buf[i];
switch (G.telstate) {
case TS_CR:
@@ -278,20 +289,19 @@ static void handle_net_input(int len)
/* Similar to NORMAL, but in TS_COPY we need to copy bytes */
if (c == IAC)
G.telstate = TS_IAC;
else
else {
G.buf[cstart++] = c;
if (c == '\r')
G.telstate = TS_CR;
if (c == '\r')
G.telstate = TS_CR;
}
break;
case TS_IAC: /* Prev char was IAC */
if (c == IAC) { /* IAC IAC -> one IAC */
switch (c) {
case IAC: /* IAC IAC -> one IAC */
G.buf[cstart++] = c;
G.telstate = TS_COPY;
break;
}
/* else */
switch (c) {
case SB:
G.telstate = TS_SUB1;
break;
@@ -320,103 +330,83 @@ static void handle_net_input(int len)
}
}
if (G.telstate != TS_NORMAL) {
/* We had some IACs, or CR */
if (G.iaclen)
iac_flush();
if (G.telstate == TS_COPY) /* we aren't in the middle of IAC */
G.telstate = TS_NORMAL;
len = cstart;
}
if (len)
full_write(STDOUT_FILENO, G.buf, len);
/* We had some IACs, or CR */
iac_flush();
if (G.telstate == TS_COPY) /* we aren't in the middle of IAC */
G.telstate = TS_NORMAL;
if (cstart != 0)
full_write(STDOUT_FILENO, G.buf, cstart);
}
static void put_iac(int c)
{
G.iacbuf[G.iaclen++] = c;
}
static void put_iac2_merged(unsigned wwdd_and_c)
{
if (G.iaclen + 3 > IACBUFSIZE)
int iaclen = G.iaclen;
if (iaclen >= IACBUFSIZE) {
iac_flush();
put_iac(IAC);
put_iac(wwdd_and_c >> 8);
put_iac(wwdd_and_c & 0xff);
iaclen = 0;
}
G.iacbuf[iaclen] = c; /* "... & 0xff" is implicit */
G.iaclen = iaclen + 1;
}
#define put_iac2(wwdd,c) put_iac2_merged(((wwdd)<<8) + (c))
static void put_iac2_msb_lsb(unsigned x_y)
{
put_iac(x_y >> 8); /* "... & 0xff" is implicit */
put_iac(x_y); /* "... & 0xff" is implicit */
}
#define put_iac2_x_y(x,y) put_iac2_msb_lsb(((x)<<8) + (y))
static void put_iac4_msb_lsb(unsigned x_y_z_t)
{
put_iac2_msb_lsb(x_y_z_t >> 16);
put_iac2_msb_lsb(x_y_z_t); /* "... & 0xffff" is implicit */
}
#define put_iac4_x_y_z_t(x,y,z,t) put_iac4_msb_lsb(((x)<<24) + ((y)<<16) + ((z)<<8) + (t))
static void put_iac3_IAC_x_y_merged(unsigned wwdd_and_c)
{
put_iac(IAC);
put_iac2_msb_lsb(wwdd_and_c);
}
#define put_iac3_IAC_x_y(wwdd,c) put_iac3_IAC_x_y_merged(((wwdd)<<8) + (c))
#if ENABLE_FEATURE_TELNET_TTYPE
static void put_iac_subopt(byte c, char *str)
{
int len = strlen(str) + 6; // ( 2 + 1 + 1 + strlen + 2 )
if (G.iaclen + len > IACBUFSIZE)
iac_flush();
put_iac(IAC);
put_iac(SB);
put_iac(c);
put_iac(0);
put_iac4_x_y_z_t(IAC, SB, c, 0);
while (*str)
put_iac(*str++);
put_iac(IAC);
put_iac(SE);
put_iac2_x_y(IAC, SE);
}
#endif
#if ENABLE_FEATURE_TELNET_AUTOLOGIN
static void put_iac_subopt_autologin(void)
{
int len = strlen(G.autologin) + 6; // (2 + 1 + 1 + strlen + 2)
const char *p = "USER";
const char *p;
if (G.iaclen + len > IACBUFSIZE)
iac_flush();
put_iac(IAC);
put_iac(SB);
put_iac(TELOPT_NEW_ENVIRON);
put_iac(TELQUAL_IS);
put_iac(NEW_ENV_VAR);
while (*p)
put_iac(*p++);
put_iac(NEW_ENV_VALUE);
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" */
put_iac2_x_y('R', NEW_ENV_VALUE);
p = G.autologin;
while (*p)
put_iac(*p++);
put_iac(IAC);
put_iac(SE);
put_iac2_x_y(IAC, SE);
}
#endif
#if ENABLE_FEATURE_TELNET_WIDTH
static void put_iac_naws(byte c, int x, int y)
{
if (G.iaclen + 9 > IACBUFSIZE)
iac_flush();
put_iac3_IAC_x_y(SB, c);
put_iac(IAC);
put_iac(SB);
put_iac(c);
put_iac4_msb_lsb((x << 16) + y);
/* "... & 0xff" implicitly done below */
put_iac(x >> 8);
put_iac(x);
put_iac(y >> 8);
put_iac(y);
put_iac(IAC);
put_iac(SE);
put_iac2_x_y(IAC, SE);
}
#endif
@@ -445,8 +435,8 @@ static void will_charmode(void)
G.telflags |= (UF_ECHO | UF_SGA);
setConMode();
put_iac2(DO, TELOPT_ECHO);
put_iac2(DO, TELOPT_SGA);
put_iac3_IAC_x_y(DO, TELOPT_ECHO);
put_iac3_IAC_x_y(DO, TELOPT_SGA);
iac_flush();
}
@@ -456,24 +446,24 @@ static void do_linemode(void)
G.telflags &= ~(UF_ECHO | UF_SGA);
setConMode();
put_iac2(DONT, TELOPT_ECHO);
put_iac2(DONT, TELOPT_SGA);
put_iac3_IAC_x_y(DONT, TELOPT_ECHO);
put_iac3_IAC_x_y(DONT, TELOPT_SGA);
iac_flush();
}
static void to_notsup(char c)
{
if (G.telwish == WILL)
put_iac2(DONT, c);
put_iac3_IAC_x_y(DONT, c);
else if (G.telwish == DO)
put_iac2(WONT, c);
put_iac3_IAC_x_y(WONT, c);
}
static void to_echo(void)
{
/* if server requests ECHO, don't agree */
if (G.telwish == DO) {
put_iac2(WONT, TELOPT_ECHO);
put_iac3_IAC_x_y(WONT, TELOPT_ECHO);
return;
}
if (G.telwish == DONT)
@@ -489,9 +479,9 @@ static void to_echo(void)
G.telflags ^= UF_ECHO;
if (G.telflags & UF_ECHO)
put_iac2(DO, TELOPT_ECHO);
put_iac3_IAC_x_y(DO, TELOPT_ECHO);
else
put_iac2(DONT, TELOPT_ECHO);
put_iac3_IAC_x_y(DONT, TELOPT_ECHO);
setConMode();
full_write1_str("\r\n"); /* sudden modec */
@@ -509,9 +499,9 @@ static void to_sga(void)
G.telflags ^= UF_SGA; /* toggle */
if (G.telflags & UF_SGA)
put_iac2(DO, TELOPT_SGA);
put_iac3_IAC_x_y(DO, TELOPT_SGA);
else
put_iac2(DONT, TELOPT_SGA);
put_iac3_IAC_x_y(DONT, TELOPT_SGA);
}
#if ENABLE_FEATURE_TELNET_TTYPE
@@ -519,9 +509,9 @@ static void to_ttype(void)
{
/* Tell server we will (or won't) do TTYPE */
if (G.ttype)
put_iac2(WILL, TELOPT_TTYPE);
put_iac3_IAC_x_y(WILL, TELOPT_TTYPE);
else
put_iac2(WONT, TELOPT_TTYPE);
put_iac3_IAC_x_y(WONT, TELOPT_TTYPE);
}
#endif
@@ -530,9 +520,9 @@ static void to_new_environ(void)
{
/* Tell server we will (or will not) do AUTOLOGIN */
if (G.autologin)
put_iac2(WILL, TELOPT_NEW_ENVIRON);
put_iac3_IAC_x_y(WILL, TELOPT_NEW_ENVIRON);
else
put_iac2(WONT, TELOPT_NEW_ENVIRON);
put_iac3_IAC_x_y(WONT, TELOPT_NEW_ENVIRON);
}
#endif
@@ -540,7 +530,7 @@ static void to_new_environ(void)
static void to_naws(void)
{
/* Tell server we will do NAWS */
put_iac2(WILL, TELOPT_NAWS);
put_iac3_IAC_x_y(WILL, TELOPT_NAWS);
}
#endif
@@ -649,6 +639,7 @@ int telnet_main(int argc UNUSED_PARAM, char **argv)
bb_show_usage();
xmove_fd(create_and_connect_stream_or_die(host, port), netfd);
printf("Connected to %s\n", host);
setsockopt_keepalive(netfd);
+29 -3
View File
@@ -249,7 +249,7 @@ safe_write_to_pty_decode_iac(struct tsession *ts)
* IAC SE (240) End of subnegotiation. Treated as NOP.
* IAC NOP (241) NOP. Supported.
* IAC BRK (243) Break. Like serial line break. TODO via tcsendbreak()?
* IAC AYT (246) Are you there. Send back evidence that AYT was seen. TODO (send NOP back)?
* IAC AYT (246) Are you there.
* These don't look useful:
* IAC DM (242) Data mark. What is this?
* IAC IP (244) Suspend, interrupt or abort the process. (Ancient cousin of ^C).
@@ -277,6 +277,18 @@ safe_write_to_pty_decode_iac(struct tsession *ts)
rc = 2;
goto update_and_return;
}
if (buf[1] == AYT) {
if (ts->size2 == 0) { /* if nothing buffered yet... */
/* Send back evidence that AYT was seen */
unsigned char *buf2 = TS_BUF2(ts);
buf2[0] = IAC;
buf2[1] = NOP;
ts->wridx2 = 0;
ts->rdidx2 = ts->size2 = 2;
}
rc = 2;
goto update_and_return;
}
if (buf[1] >= 240 && buf[1] <= 249) {
/* NOP (241). Ignore (putty keepalive, etc) */
/* All other 2-byte commands also treated as NOPs here */
@@ -865,11 +877,25 @@ int telnetd_main(int argc UNUSED_PARAM, char **argv)
skip3:
if (/*ts->size2 < BUFSIZE &&*/ FD_ISSET(ts->ptyfd, &rdfdset)) {
/* Read from pty to buffer 2 */
int eio = 0;
read_pty:
count = MIN(BUFSIZE - ts->rdidx2, BUFSIZE - ts->size2);
count = safe_read(ts->ptyfd, TS_BUF2(ts) + ts->rdidx2, count);
if (count <= 0) {
if (count < 0 && errno == EAGAIN)
goto skip4;
if (count < 0) {
if (errno == EAGAIN)
goto skip4;
/* login process might call vhangup(),
* which causes intermittent EIOs on read above
* (observed on kernel 4.12.0). Try up to 10 ms.
*/
if (errno == EIO && eio < 10) {
eio++;
//bb_error_msg("EIO pty %u", eio);
usleep(1000);
goto read_pty;
}
}
goto kill_session;
}
ts->size2 += count;
+50 -3
View File
@@ -31,6 +31,11 @@
//config: default y
//config: depends on TFTP
//config:
//config:config FEATURE_TFTP_HPA_COMPAT
//config: bool "tftp-hpa compat (support -c get/put FILE)"
//config: default y
//config: depends on TFTP
//config:
//config:config TFTPD
//config: bool "tftpd (10 kb)"
//config: default y
@@ -101,9 +106,10 @@
//usage: IF_FEATURE_TFTP_BLOCKSIZE(
//usage: "\n -b SIZE Transfer blocks of SIZE octets"
//usage: )
///////: "\n -m STR Accepted and ignored ('-m binary' compat with tftp-hpa 5.2)"
//usage:
//usage:#define tftpd_trivial_usage
//usage: "[-cr] [-u USER] [DIR]"
//usage: "[-crl] [-u USER] [DIR]"
//usage:#define tftpd_full_usage "\n\n"
//usage: "Transfer a file on tftp client's request\n"
//usage: "\n"
@@ -245,7 +251,7 @@ static int tftp_blksize_check(const char *blksize_str, int maxsize)
return -1;
}
# if ENABLE_TFTP_DEBUG
bb_error_msg("using blksize %u", blksize);
bb_info_msg("using blksize %u", blksize);
# endif
return blksize;
}
@@ -759,15 +765,54 @@ int tftp_main(int argc UNUSED_PARAM, char **argv)
INIT_G();
if (ENABLE_FEATURE_TFTP_HPA_COMPAT) {
/* As of 2019, common tftp client in Linux distros
* is one maintained by H. Peter Anvin:
* I've seen "tftp-hpa 5.2" version.
* Make the following command work:
* "tftp HOST [PORT] -m binary -c get/put FILE"
* by mangling it into "....... -g/-p -r FILE"
* and accepting and ignoring -m STR option.
*/
unsigned i = 1;
while (argv[i]) {
/* Accept not only -c, but also
* -lc, -cl, -llcclcllcc etc:
* "-l Literal mode (do not recognize HOST:FILE)"
* since we do not recognize that syntax anyway,
* might as well allow the option.
*/
if (argv[i][0] == '-' && strchr(argv[i], 'c')
/*&& argv[i][1+strspn(argv[i]+1, "lc")] == '\0'*/
) {
if (!argv[++i])
break;
if (strcmp(argv[i], "get") == 0) {
argv[i-1] = (char*)"-g";
argv[i] = (char*)"-r";
break;
}
if (strcmp(argv[i], "put") == 0) {
argv[i-1] = (char*)"-p";
argv[i] = (char*)"-r";
break;
}
}
i++;
}
}
IF_GETPUT(opt =) getopt32(argv, "^"
IF_FEATURE_TFTP_GET("g") IF_FEATURE_TFTP_PUT("p")
"l:r:" IF_FEATURE_TFTP_BLOCKSIZE("b:")
IF_FEATURE_TFTP_HPA_COMPAT("m:")
"\0"
/* -p or -g is mandatory, and they are mutually exclusive */
IF_FEATURE_TFTP_GET("g:") IF_FEATURE_TFTP_PUT("p:")
IF_GETPUT("g--p:p--g:"),
&local_file, &remote_file
IF_FEATURE_TFTP_BLOCKSIZE(, &blksize_str)
IF_FEATURE_TFTP_HPA_COMPAT(, NULL)
);
argv += optind;
@@ -897,6 +942,7 @@ int tftpd_main(int argc UNUSED_PARAM, char **argv)
mode = local_file + strlen(local_file) + 1;
/* RFC 1350 says mode string is case independent */
if (mode >= G.block_buf + result || strcasecmp(mode, "octet") != 0) {
error_msg = "mode is not 'octet'";
goto err;
}
# if ENABLE_FEATURE_TFTP_BLOCKSIZE
@@ -944,7 +990,8 @@ int tftpd_main(int argc UNUSED_PARAM, char **argv)
/* tftp_protocol() will create new one, bound to particular local IP */
result = tftp_protocol(
our_lsa, peer_lsa,
local_file IF_TFTP(, NULL /*remote_file*/)
local_file
IF_TFTP(, NULL /*remote_file*/)
IF_FEATURE_TFTP_BLOCKSIZE(, want_transfer_size)
IF_FEATURE_TFTP_BLOCKSIZE(, blksize)
);
+11 -3
View File
@@ -1387,12 +1387,12 @@ static void find_key_in_der_cert(tls_state_t *tls, uint8_t *der, int len)
/* enter subjectPublicKeyInfo */
der = enter_der_item(der, &end);
{ /* check subjectPublicKeyInfo.algorithm */
static const uint8_t OID_RSA_KEY_ALG[] = {
static const uint8_t OID_RSA_KEY_ALG[] ALIGN1 = {
0x30,0x0d, // SEQ 13 bytes
0x06,0x09, 0x2a,0x86,0x48,0x86,0xf7,0x0d,0x01,0x01,0x01, //OID_RSA_KEY_ALG 42.134.72.134.247.13.1.1.1
//0x05,0x00, // NULL
};
static const uint8_t OID_ECDSA_KEY_ALG[] = {
static const uint8_t OID_ECDSA_KEY_ALG[] ALIGN1 = {
0x30,0x13, // SEQ 0x13 bytes
0x06,0x07, 0x2a,0x86,0x48,0xce,0x3d,0x02,0x01, //OID_ECDSA_KEY_ALG 42.134.72.206.61.2.1
//allow any curve code for now...
@@ -1531,9 +1531,17 @@ static void send_client_hello_and_alloc_hsd(tls_state_t *tls, const char *sni)
0x00,0x04, //ext len
0x00,0x02, //list len
0x00,0x1d, //curve_x25519 (RFC 7748)
//0x00,0x1e, //curve_x448 (RFC 7748)
//0x00,0x17, //curve_secp256r1
//0x00,0x18, //curve_secp384r1
//0x00,0x19, //curve_secp521r1
//TODO: implement secp256r1 (at least): dl.fedoraproject.org immediately aborts
//if only x25519/x448 are advertised, seems to support only secpNNNr1 curves:
// openssl s_client -connect dl.fedoraproject.org:443 -debug -tls1_2 -cipher ECDHE-RSA-AES128-GCM-SHA256
//Peer signing digest: SHA512
//Peer signature type: RSA
//Server Temp Key: ECDH, P-256, 256 bits
//TLSv1.2, Cipher is ECDHE-RSA-AES128-GCM-SHA256
};
//static const uint8_t signature_algorithms[] = {
// 000d
@@ -2075,7 +2083,7 @@ static void send_client_key_exchange(tls_state_t *tls)
}
}
static const uint8_t rec_CHANGE_CIPHER_SPEC[] = {
static const uint8_t rec_CHANGE_CIPHER_SPEC[] ALIGN1 = {
RECORD_TYPE_CHANGE_CIPHER_SPEC, TLS_MAJ, TLS_MIN, 00, 01,
01
};
+1 -1
View File
@@ -130,7 +130,7 @@ 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.
static const uint8_t Rcon[] = {
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,...
// but aes256 only uses values up to 0x36
+7 -11
View File
@@ -43,17 +43,13 @@ typedef uint32_t word32;
#if 0 //UNUSED
static void fprime_copy(byte *x, const byte *a)
{
int i;
for (i = 0; i < F25519_SIZE; i++)
x[i] = a[i];
memcpy(x, a, F25519_SIZE);
}
#endif
static void lm_copy(byte* x, const byte* a)
{
int i;
for (i = 0; i < F25519_SIZE; i++)
x[i] = a[i];
memcpy(x, a, F25519_SIZE);
}
#if 0 //UNUSED
@@ -200,7 +196,7 @@ static void fe_load(byte *x, word32 c)
static void fe_normalize(byte *x)
{
byte minusp[F25519_SIZE];
word16 c;
unsigned c;
int i;
/* Reduce using 2^255 = 19 mod p */
@@ -219,13 +215,13 @@ static void fe_normalize(byte *x)
*/
c = 19;
for (i = 0; i + 1 < F25519_SIZE; i++) {
for (i = 0; i < F25519_SIZE - 1; i++) {
c += x[i];
minusp[i] = (byte)c;
c >>= 8;
}
c += ((word16)x[i]) - 128;
c += ((unsigned)x[i]) - 128;
minusp[31] = (byte)c;
/* Load x-p if no underflow */
@@ -234,13 +230,13 @@ static void fe_normalize(byte *x)
static void lm_add(byte* r, const byte* a, const byte* b)
{
word16 c = 0;
unsigned c = 0;
int i;
/* Add */
for (i = 0; i < F25519_SIZE; i++) {
c >>= 8;
c += ((word16)a[i]) + ((word16)b[i]);
c += ((unsigned)a[i]) + ((unsigned)b[i]);
r[i] = (byte)c;
}
+77 -32
View File
@@ -47,13 +47,18 @@
//#include "../cryptoApi.h"
#ifndef DISABLE_PSTM
#undef pstm_mul_2d
static int32 pstm_mul_2d(pstm_int *a, int b, pstm_int *c); //bbox: was int16 b
#define pstm_mul_2d(a, b, c) (pstm_mul_2d(a, b, c), PSTM_OKAY)
/******************************************************************************/
/*
init an pstm_int for a given size
*/
int32 pstm_init_size(psPool_t *pool, pstm_int * a, uint32 size)
#undef pstm_init_size
#define pstm_init_size(pool, a, size) \
pstm_init_size( a, size)
int32 FAST_FUNC pstm_init_size(psPool_t *pool, pstm_int * a, uint32 size)
{
//bbox
// uint16 x;
@@ -75,12 +80,17 @@ int32 pstm_init_size(psPool_t *pool, pstm_int * a, uint32 size)
// }
return PSTM_OKAY;
}
#undef pstm_init_size
#define pstm_init_size(pool, a, size) (pstm_init_size(a, size), PSTM_OKAY)
/******************************************************************************/
/*
Init a new pstm_int.
*/
int32 pstm_init(psPool_t *pool, pstm_int * a)
#undef pstm_init
#define pstm_init(pool, a) \
pstm_init( a)
static int32 pstm_init(psPool_t *pool, pstm_int * a)
{
//bbox
// int32 i;
@@ -106,12 +116,15 @@ int32 pstm_init(psPool_t *pool, pstm_int * a)
return PSTM_OKAY;
}
#undef pstm_init
#define pstm_init(pool, a) (pstm_init(a), PSTM_OKAY)
/******************************************************************************/
/*
Grow as required
*/
int32 pstm_grow(pstm_int * a, int size)
#undef pstm_grow
int32 FAST_FUNC pstm_grow(pstm_int * a, int size)
{
int i; //bbox: was int16
pstm_digit *tmp;
@@ -142,11 +155,13 @@ int32 pstm_grow(pstm_int * a, int size)
}
return PSTM_OKAY;
}
#define pstm_grow(a, size) (pstm_grow(a, size), PSTM_OKAY)
/******************************************************************************/
/*
copy, b = a (b must be pre-allocated)
*/
#undef pstm_copy
int32 pstm_copy(pstm_int * a, pstm_int * b)
{
int32 res, n;
@@ -195,6 +210,7 @@ int32 pstm_copy(pstm_int * a, pstm_int * b)
b->sign = a->sign;
return PSTM_OKAY;
}
#define pstm_copy(a, b) (pstm_copy(a, b), PSTM_OKAY)
/******************************************************************************/
/*
@@ -204,7 +220,7 @@ int32 pstm_copy(pstm_int * a, pstm_int * b)
leading "used" digit will be non-zero. Typically very fast. Also fixes
the sign if there are no more leading digits
*/
void pstm_clamp(pstm_int * a)
void FAST_FUNC pstm_clamp(pstm_int * a)
{
/* decrease used while the most significant digit is zero. */
while (a->used > 0 && a->dp[a->used - 1] == 0) {
@@ -220,7 +236,7 @@ void pstm_clamp(pstm_int * a)
/*
clear one (frees).
*/
void pstm_clear(pstm_int * a)
void FAST_FUNC pstm_clear(pstm_int * a)
{
int32 i;
/*
@@ -248,6 +264,7 @@ void pstm_clear(pstm_int * a)
/*
clear many (frees).
*/
#if 0 //UNUSED
void pstm_clear_multi(pstm_int *mp0, pstm_int *mp1, pstm_int *mp2,
pstm_int *mp3, pstm_int *mp4, pstm_int *mp5,
pstm_int *mp6, pstm_int *mp7)
@@ -272,12 +289,13 @@ void pstm_clear_multi(pstm_int *mp0, pstm_int *mp1, pstm_int *mp2,
}
}
}
#endif
/******************************************************************************/
/*
Set to zero.
*/
void pstm_zero(pstm_int * a)
static void pstm_zero(pstm_int * a)
{
int32 n;
pstm_digit *tmp;
@@ -296,7 +314,7 @@ void pstm_zero(pstm_int * a)
/*
Compare maginitude of two ints (unsigned).
*/
int32 pstm_cmp_mag(pstm_int * a, pstm_int * b)
int32 FAST_FUNC pstm_cmp_mag(pstm_int * a, pstm_int * b)
{
int n; //bbox: was int16
pstm_digit *tmpa, *tmpb;
@@ -336,7 +354,7 @@ int32 pstm_cmp_mag(pstm_int * a, pstm_int * b)
/*
Compare two ints (signed)
*/
int32 pstm_cmp(pstm_int * a, pstm_int * b)
int32 FAST_FUNC pstm_cmp(pstm_int * a, pstm_int * b)
{
/*
compare based on sign
@@ -364,7 +382,7 @@ int32 pstm_cmp(pstm_int * a, pstm_int * b)
pstm_ints can be initialized more precisely when they will populated
using pstm_read_unsigned_bin since the length of the byte stream is known
*/
int32 pstm_init_for_read_unsigned_bin(psPool_t *pool, pstm_int *a, uint32 len)
int32 FAST_FUNC pstm_init_for_read_unsigned_bin(psPool_t *pool, pstm_int *a, uint32 len)
{
int32 size;
/*
@@ -385,7 +403,7 @@ int32 pstm_init_for_read_unsigned_bin(psPool_t *pool, pstm_int *a, uint32 len)
called pstm_init_for_read_unsigned_bin first. There is some grow logic
here if the default pstm_init was used but we don't really want to hit it.
*/
int32 pstm_read_unsigned_bin(pstm_int *a, unsigned char *b, int32 c)
int32 FAST_FUNC pstm_read_unsigned_bin(pstm_int *a, unsigned char *b, int32 c)
{
/* zero the int */
pstm_zero (a);
@@ -460,7 +478,7 @@ int32 pstm_read_unsigned_bin(pstm_int *a, unsigned char *b, int32 c)
/******************************************************************************/
/*
*/
int pstm_count_bits (pstm_int * a)
static int pstm_count_bits(pstm_int * a)
{
int r; //bbox: was int16
pstm_digit q;
@@ -482,14 +500,14 @@ int pstm_count_bits (pstm_int * a)
}
/******************************************************************************/
int32 pstm_unsigned_bin_size(pstm_int *a)
int32 FAST_FUNC pstm_unsigned_bin_size(pstm_int *a)
{
int32 size = pstm_count_bits (a);
return (size / 8 + ((size & 7) != 0 ? 1 : 0));
}
/******************************************************************************/
void pstm_set(pstm_int *a, pstm_digit b)
static void pstm_set(pstm_int *a, pstm_digit b)
{
pstm_zero(a);
a->dp[0] = b;
@@ -500,7 +518,7 @@ void pstm_set(pstm_int *a, pstm_digit b)
/*
Right shift
*/
void pstm_rshd(pstm_int *a, int x)
static void pstm_rshd(pstm_int *a, int x)
{
int y; //bbox: was int16
@@ -529,7 +547,8 @@ void pstm_rshd(pstm_int *a, int x)
/*
Shift left a certain amount of digits.
*/
int32 pstm_lshd(pstm_int * a, int b)
#undef pstm_lshd
static int32 pstm_lshd(pstm_int * a, int b)
{
int x; //bbox: was int16
int32 res;
@@ -577,12 +596,13 @@ int32 pstm_lshd(pstm_int * a, int b)
}
return PSTM_OKAY;
}
#define pstm_lshd(a, b) (pstm_lshd(a, b), PSTM_OKAY)
/******************************************************************************/
/*
computes a = 2**b
*/
int32 pstm_2expt(pstm_int *a, int b)
static int32 pstm_2expt(pstm_int *a, int b)
{
int z; //bbox: was int16
@@ -616,7 +636,7 @@ int32 pstm_2expt(pstm_int *a, int b)
/*
*/
int32 pstm_mul_2(pstm_int * a, pstm_int * b)
int32 FAST_FUNC pstm_mul_2(pstm_int * a, pstm_int * b)
{
int32 res;
int x, oldused; //bbox: was int16
@@ -682,7 +702,7 @@ int32 pstm_mul_2(pstm_int * a, pstm_int * b)
/*
unsigned subtraction ||a|| >= ||b|| ALWAYS!
*/
int32 s_pstm_sub(pstm_int *a, pstm_int *b, pstm_int *c)
int32 FAST_FUNC s_pstm_sub(pstm_int *a, pstm_int *b, pstm_int *c)
{
int oldbused, oldused; //bbox: was int16
int32 x;
@@ -779,7 +799,7 @@ static int32 s_pstm_add(pstm_int *a, pstm_int *b, pstm_int *c)
/*
*/
int32 pstm_sub(pstm_int *a, pstm_int *b, pstm_int *c)
int32 FAST_FUNC pstm_sub(pstm_int *a, pstm_int *b, pstm_int *c)
{
int32 res;
int sa, sb; //bbox: was int16
@@ -824,6 +844,7 @@ int32 pstm_sub(pstm_int *a, pstm_int *b, pstm_int *c)
/*
c = a - b
*/
#if 0 //UNUSED
int32 pstm_sub_d(psPool_t *pool, pstm_int *a, pstm_digit b, pstm_int *c)
{
pstm_int tmp;
@@ -837,12 +858,13 @@ int32 pstm_sub_d(psPool_t *pool, pstm_int *a, pstm_digit b, pstm_int *c)
pstm_clear(&tmp);
return res;
}
#endif
/******************************************************************************/
/*
setups the montgomery reduction
*/
int32 pstm_montgomery_setup(pstm_int *a, pstm_digit *rho)
static int32 pstm_montgomery_setup(pstm_int *a, pstm_digit *rho)
{
pstm_digit x, b;
@@ -878,7 +900,7 @@ int32 pstm_montgomery_setup(pstm_int *a, pstm_digit *rho)
* computes a = B**n mod b without division or multiplication useful for
* normalizing numbers in a Montgomery system.
*/
int32 pstm_montgomery_calc_normalization(pstm_int *a, pstm_int *b)
static int32 pstm_montgomery_calc_normalization(pstm_int *a, pstm_int *b)
{
int32 x;
int bits; //bbox: was int16
@@ -916,6 +938,7 @@ int32 pstm_montgomery_calc_normalization(pstm_int *a, pstm_int *b)
/*
c = a * 2**d
*/
#undef pstm_mul_2d
static int32 pstm_mul_2d(pstm_int *a, int b, pstm_int *c)
{
pstm_digit carry, carrytmp, shift;
@@ -956,11 +979,13 @@ static int32 pstm_mul_2d(pstm_int *a, int b, pstm_int *c)
pstm_clamp(c);
return PSTM_OKAY;
}
#define pstm_mul_2d(a, b, c) (pstm_mul_2d(a, b, c), PSTM_OKAY)
/******************************************************************************/
/*
c = a mod 2**d
*/
#undef pstm_mod_2d
static int32 pstm_mod_2d(pstm_int *a, int b, pstm_int *c) //bbox: was int16 b
{
int x; //bbox: was int16
@@ -991,13 +1016,15 @@ static int32 pstm_mod_2d(pstm_int *a, int b, pstm_int *c) //bbox: was int16 b
pstm_clamp (c);
return PSTM_OKAY;
}
#define pstm_mod_2d(a, b, c) (pstm_mod_2d(a, b, c), PSTM_OKAY)
/******************************************************************************/
/*
c = a * b
*/
int32 pstm_mul_d(pstm_int *a, pstm_digit b, pstm_int *c)
#undef pstm_mul_d
static int32 pstm_mul_d(pstm_int *a, pstm_digit b, pstm_int *c)
{
pstm_word w;
int32 res;
@@ -1027,12 +1054,16 @@ int32 pstm_mul_d(pstm_int *a, pstm_digit b, pstm_int *c)
pstm_clamp(c);
return PSTM_OKAY;
}
#define pstm_mul_d(a, b, c) (pstm_mul_d(a, b, c), PSTM_OKAY)
/******************************************************************************/
/*
c = a / 2**b
*/
int32 pstm_div_2d(psPool_t *pool, pstm_int *a, int b, pstm_int *c,
#undef pstm_div_2d
#define pstm_div_2d(pool, a, b, c, d) \
pstm_div_2d( a, b, c, d)
static int32 pstm_div_2d(psPool_t *pool, pstm_int *a, int b, pstm_int *c,
pstm_int *d)
{
pstm_digit D, r, rr;
@@ -1113,11 +1144,14 @@ LBL_DONE:
}
return res;
}
#undef pstm_div_2d
#define pstm_div_2d(pool, a, b, c, d) (pstm_div_2d(a, b, c, d), PSTM_OKAY)
/******************************************************************************/
/*
b = a/2
*/
#if 0 //UNUSED
int32 pstm_div_2(pstm_int * a, pstm_int * b)
{
int x, oldused; //bbox: was int16
@@ -1161,12 +1195,16 @@ int32 pstm_div_2(pstm_int * a, pstm_int * b)
pstm_clamp (b);
return PSTM_OKAY;
}
#endif
/******************************************************************************/
/*
Creates "a" then copies b into it
*/
int32 pstm_init_copy(psPool_t *pool, pstm_int * a, pstm_int * b, int toSqr)
#undef pstm_init_copy
#define pstm_init_copy(pool, a, b, toSqr) \
pstm_init_copy( a, b, toSqr)
static int32 pstm_init_copy(psPool_t *pool, pstm_int * a, pstm_int * b, int toSqr)
{
int x; //bbox: was int16
int32 res;
@@ -1191,6 +1229,8 @@ int32 pstm_init_copy(psPool_t *pool, pstm_int * a, pstm_int * b, int toSqr)
}
return pstm_copy(b, a);
}
#undef pstm_init_copy
#define pstm_init_copy(pool, a, b, toSqr) (pstm_init_copy(a, b, toSqr), PSTM_OKAY)
/******************************************************************************/
/*
@@ -1274,7 +1314,7 @@ static uint64 psDiv128(uint128 *numerator, uint64 denominator)
/*
a/b => cb + d == a
*/
int32 pstm_div(psPool_t *pool, pstm_int *a, pstm_int *b, pstm_int *c,
static int32 pstm_div(psPool_t *pool, pstm_int *a, pstm_int *b, pstm_int *c,
pstm_int *d)
{
pstm_int q, x, y, t1, t2;
@@ -1487,7 +1527,7 @@ LBL_T1:pstm_clear (&t1);
Swap the elements of two integers, for cases where you can't simply swap
the pstm_int pointers around
*/
void pstm_exch(pstm_int * a, pstm_int * b)
static void pstm_exch(pstm_int * a, pstm_int * b)
{
pstm_int t;
@@ -1500,7 +1540,7 @@ void pstm_exch(pstm_int * a, pstm_int * b)
/*
c = a mod b, 0 <= c < b
*/
int32 pstm_mod(psPool_t *pool, pstm_int *a, pstm_int *b, pstm_int *c)
static int32 pstm_mod(psPool_t *pool, pstm_int *a, pstm_int *b, pstm_int *c)
{
pstm_int t;
int32 err;
@@ -1527,7 +1567,7 @@ int32 pstm_mod(psPool_t *pool, pstm_int *a, pstm_int *b, pstm_int *c)
/*
d = a * b (mod c)
*/
int32 pstm_mulmod(psPool_t *pool, pstm_int *a, pstm_int *b, pstm_int *c,
int32 FAST_FUNC pstm_mulmod(psPool_t *pool, pstm_int *a, pstm_int *b, pstm_int *c,
pstm_int *d)
{
int32 res;
@@ -1560,7 +1600,7 @@ int32 pstm_mulmod(psPool_t *pool, pstm_int *a, pstm_int *b, pstm_int *c,
* y = g**x (mod b)
* Some restrictions... x must be positive and < b
*/
int32 pstm_exptmod(psPool_t *pool, pstm_int *G, pstm_int *X, pstm_int *P,
int32 FAST_FUNC pstm_exptmod(psPool_t *pool, pstm_int *G, pstm_int *X, pstm_int *P,
pstm_int *Y)
{
pstm_int M[32], res; /* Keep this winsize based: (1 << max_winsize) */
@@ -1801,7 +1841,7 @@ LBL_RES:pstm_clear(&res);
/*
*/
int32 pstm_add(pstm_int *a, pstm_int *b, pstm_int *c)
int32 FAST_FUNC pstm_add(pstm_int *a, pstm_int *b, pstm_int *c)
{
int32 res;
int sa, sb; //bbox: was int16
@@ -1862,6 +1902,7 @@ static void pstm_reverse (unsigned char *s, int len) //bbox: was int16 len
No reverse. Useful in some of the EIP-154 PKA stuff where special byte
order seems to come into play more often
*/
#if 0 //UNUSED
int32 pstm_to_unsigned_bin_nr(psPool_t *pool, pstm_int *a, unsigned char *b)
{
int32 res;
@@ -1883,11 +1924,12 @@ int32 pstm_to_unsigned_bin_nr(psPool_t *pool, pstm_int *a, unsigned char *b)
pstm_clear(&t);
return PS_SUCCESS;
}
#endif
/******************************************************************************/
/*
*/
int32 pstm_to_unsigned_bin(psPool_t *pool, pstm_int *a, unsigned char *b)
int32 FAST_FUNC pstm_to_unsigned_bin(psPool_t *pool, pstm_int *a, unsigned char *b)
{
int32 res;
int x; //bbox: was int16
@@ -1910,11 +1952,12 @@ int32 pstm_to_unsigned_bin(psPool_t *pool, pstm_int *a, unsigned char *b)
return PS_SUCCESS;
}
#if 0 //UNUSED
/******************************************************************************/
/*
compare against a single digit
*/
int32 pstm_cmp_d(pstm_int *a, pstm_digit b)
static int32 pstm_cmp_d(pstm_int *a, pstm_digit b)
{
/* compare based on sign */
if ((b && a->used == 0) || a->sign == PSTM_NEG) {
@@ -2259,5 +2302,7 @@ LBL_Y: pstm_clear(&y);
LBL_X: pstm_clear(&x);
return res;
}
#endif //UNUSED
#endif /* !DISABLE_PSTM */
/******************************************************************************/
+43 -43
View File
@@ -136,148 +136,148 @@ typedef struct {
#define pstm_isodd(a) (((a)->used > 0 && (((a)->dp[0] & 1) == 1)) ? PS_TRUE : PS_FALSE)
#define pstm_abs(a, b) { pstm_copy(a, b); (b)->sign = 0; }
extern void pstm_set(pstm_int *a, pstm_digit b);
//made static:extern void pstm_set(pstm_int *a, pstm_digit b);
extern void pstm_zero(pstm_int * a);
//made static:extern void pstm_zero(pstm_int * a);
//bbox: pool unused
#define pstm_init(pool, a) \
pstm_init( a)
extern int32 pstm_init(psPool_t *pool, pstm_int * a);
//made static:extern int32 pstm_init(psPool_t *pool, pstm_int * a);
//bbox: pool unused
#define pstm_init_size(pool, a, size) \
pstm_init_size( a, size)
extern int32 pstm_init_size(psPool_t *pool, pstm_int * a, uint32 size);
extern int32 pstm_init_size(psPool_t *pool, pstm_int * a, uint32 size) FAST_FUNC;
//bbox: pool unused
#define pstm_init_copy(pool, a, b, toSqr) \
pstm_init_copy( a, b, toSqr)
extern int32 pstm_init_copy(psPool_t *pool, pstm_int * a, pstm_int * b,
int toSqr); //bbox: was int16 toSqr
//made static:extern int32 pstm_init_copy(psPool_t *pool, pstm_int * a, pstm_int * b,
//made static: int toSqr); //bbox: was int16 toSqr
extern int pstm_count_bits (pstm_int * a); //bbox: was returning int16
//made static:extern int pstm_count_bits (pstm_int * a) FAST_FUNC; //bbox: was returning int16
//bbox: pool unused
#define pstm_init_for_read_unsigned_bin(pool, a, len) \
pstm_init_for_read_unsigned_bin( a, len)
extern int32 pstm_init_for_read_unsigned_bin(psPool_t *pool, pstm_int *a,
uint32 len);
uint32 len) FAST_FUNC;
extern int32 pstm_read_unsigned_bin(pstm_int *a, unsigned char *b, int32 c);
extern int32 pstm_read_unsigned_bin(pstm_int *a, unsigned char *b, int32 c) FAST_FUNC;
extern int32 pstm_unsigned_bin_size(pstm_int *a);
extern int32 pstm_unsigned_bin_size(pstm_int *a) FAST_FUNC;
extern int32 pstm_copy(pstm_int * a, pstm_int * b);
extern void pstm_exch(pstm_int * a, pstm_int * b);
//made static:extern void pstm_exch(pstm_int * a, pstm_int * b);
extern void pstm_clear(pstm_int * a);
extern void pstm_clear(pstm_int * a) FAST_FUNC;
extern void pstm_clear_multi(pstm_int *mp0, pstm_int *mp1, pstm_int *mp2,
pstm_int *mp3, pstm_int *mp4, pstm_int *mp5, pstm_int *mp6,
pstm_int *mp7);
pstm_int *mp7) FAST_FUNC;
extern int32 pstm_grow(pstm_int * a, int size); //bbox: was int16 size
extern int32 pstm_grow(pstm_int * a, int size) FAST_FUNC; //bbox: was int16 size
extern void pstm_clamp(pstm_int * a);
extern void pstm_clamp(pstm_int * a) FAST_FUNC;
extern int32 pstm_cmp(pstm_int * a, pstm_int * b);
extern int32 pstm_cmp(pstm_int * a, pstm_int * b) FAST_FUNC;
extern int32 pstm_cmp_mag(pstm_int * a, pstm_int * b);
extern int32 pstm_cmp_mag(pstm_int * a, pstm_int * b) FAST_FUNC;
extern void pstm_rshd(pstm_int *a, int x); //bbox: was int16 x
//made static:extern void pstm_rshd(pstm_int *a, int x); //bbox: was int16 x
extern int32 pstm_lshd(pstm_int * a, int b); //bbox: was int16 b
//made static:extern int32 pstm_lshd(pstm_int * a, int b); //bbox: was int16 b
//bbox: pool unused
#define pstm_div(pool, a, b, c, d) \
pstm_div( a, b, c, d)
extern int32 pstm_div(psPool_t *pool, pstm_int *a, pstm_int *b, pstm_int *c,
pstm_int *d);
//made static:extern int32 pstm_div(psPool_t *pool, pstm_int *a, pstm_int *b, pstm_int *c,
//made static: pstm_int *d);
//bbox: pool unused
#define pstm_div_2d(pool, a, b, c, d) \
pstm_div_2d( a, b, c, d)
extern int32 pstm_div_2d(psPool_t *pool, pstm_int *a, int b, pstm_int *c,
pstm_int *d); //bbox: was int16 b
//made static:extern int32 pstm_div_2d(psPool_t *pool, pstm_int *a, int b, pstm_int *c,
//made static: pstm_int *d); //bbox: was int16 b
extern int32 pstm_div_2(pstm_int * a, pstm_int * b);
extern int32 pstm_div_2(pstm_int * a, pstm_int * b) FAST_FUNC;
extern int32 s_pstm_sub(pstm_int *a, pstm_int *b, pstm_int *c);
extern int32 s_pstm_sub(pstm_int *a, pstm_int *b, pstm_int *c) FAST_FUNC;
extern int32 pstm_sub(pstm_int *a, pstm_int *b, pstm_int *c);
extern int32 pstm_sub(pstm_int *a, pstm_int *b, pstm_int *c) FAST_FUNC;
//bbox: pool unused
#define pstm_sub_d(pool, a, b, c) \
pstm_sub_d( a, b, c)
extern int32 pstm_sub_d(psPool_t *pool, pstm_int *a, pstm_digit b, pstm_int *c);
extern int32 pstm_sub_d(psPool_t *pool, pstm_int *a, pstm_digit b, pstm_int *c) FAST_FUNC;
extern int32 pstm_mul_2(pstm_int * a, pstm_int * b);
extern int32 pstm_mul_2(pstm_int * a, pstm_int * b) FAST_FUNC;
//bbox: pool unused
#define pstm_mod(pool, a, b, c) \
pstm_mod( a, b, c)
extern int32 pstm_mod(psPool_t *pool, pstm_int *a, pstm_int *b, pstm_int *c);
//made static:extern int32 pstm_mod(psPool_t *pool, pstm_int *a, pstm_int *b, pstm_int *c);
//bbox: pool unused
#define pstm_mulmod(pool, a, b, c, d) \
pstm_mulmod( a, b, c, d)
extern int32 pstm_mulmod(psPool_t *pool, pstm_int *a, pstm_int *b, pstm_int *c,
pstm_int *d);
pstm_int *d) FAST_FUNC;
//bbox: pool unused
#define pstm_exptmod(pool, G, X, P, Y) \
pstm_exptmod( G, X, P, Y)
extern int32 pstm_exptmod(psPool_t *pool, pstm_int *G, pstm_int *X, pstm_int *P,
pstm_int *Y);
pstm_int *Y) FAST_FUNC;
extern int32 pstm_2expt(pstm_int *a, int b); //bbox: was int16 b
//made static:extern int32 pstm_2expt(pstm_int *a, int b); //bbox: was int16 b
extern int32 pstm_add(pstm_int *a, pstm_int *b, pstm_int *c);
extern int32 pstm_add(pstm_int *a, pstm_int *b, pstm_int *c) FAST_FUNC;
//bbox: pool unused
#define pstm_to_unsigned_bin(pool, a, b) \
pstm_to_unsigned_bin( a, b)
extern int32 pstm_to_unsigned_bin(psPool_t *pool, pstm_int *a,
unsigned char *b);
unsigned char *b) FAST_FUNC;
//bbox: pool unused
#define pstm_to_unsigned_bin_nr(pool, a, b) \
pstm_to_unsigned_bin_nr( a, b)
extern int32 pstm_to_unsigned_bin_nr(psPool_t *pool, pstm_int *a,
unsigned char *b);
unsigned char *b) FAST_FUNC;
extern int32 pstm_montgomery_setup(pstm_int *a, pstm_digit *rho);
//made static:extern int32 pstm_montgomery_setup(pstm_int *a, pstm_digit *rho);
//bbox: pool unused
#define pstm_montgomery_reduce(pool, a, m, mp, paD, paDlen) \
pstm_montgomery_reduce( a, m, mp, paD, paDlen)
extern int32 pstm_montgomery_reduce(psPool_t *pool, pstm_int *a, pstm_int *m,
pstm_digit mp, pstm_digit *paD, uint32 paDlen);
pstm_digit mp, pstm_digit *paD, uint32 paDlen) FAST_FUNC;
#define pstm_mul_comba(pool, A, B, C, paD, paDlen) \
pstm_mul_comba( A, B, C, paD, paDlen)
extern int32 pstm_mul_comba(psPool_t *pool, pstm_int *A, pstm_int *B,
pstm_int *C, pstm_digit *paD, uint32 paDlen);
pstm_int *C, pstm_digit *paD, uint32 paDlen) FAST_FUNC;
//bbox: pool unused
#define pstm_sqr_comba(pool, A, B, paD, paDlen) \
pstm_sqr_comba( A, B, paD, paDlen)
extern int32 pstm_sqr_comba(psPool_t *pool, pstm_int *A, pstm_int *B,
pstm_digit *paD, uint32 paDlen);
pstm_digit *paD, uint32 paDlen) FAST_FUNC;
extern int32 pstm_cmp_d(pstm_int *a, pstm_digit b);
//made static:extern int32 pstm_cmp_d(pstm_int *a, pstm_digit b);
extern int32 pstm_montgomery_calc_normalization(pstm_int *a, pstm_int *b);
//made static:extern int32 pstm_montgomery_calc_normalization(pstm_int *a, pstm_int *b);
extern int32 pstm_mul_d(pstm_int *a, pstm_digit b, pstm_int *c);
//made static:extern int32 pstm_mul_d(pstm_int *a, pstm_digit b, pstm_int *c);
//bbox: pool unused
#define pstm_invmod(pool, a, b, c) \
pstm_invmod( a, b, c)
extern int32 pstm_invmod(psPool_t *pool, pstm_int * a, pstm_int * b,
pstm_int * c);
pstm_int * c) FAST_FUNC;
#else /* DISABLE_PSTM */
typedef int32 pstm_int;
+7 -7
View File
@@ -73,7 +73,7 @@ asm( \
"movl %%edx,%1 \n\t" \
:"=g"(_c[LO]), "=r"(cy) \
:"0"(_c[LO]), "1"(cy), "g"(mu), "g"(*tmpm++) \
: "%eax", "%edx", "%cc")
: "%eax", "%edx", "cc")
#define PROPCARRY \
asm( \
@@ -82,7 +82,7 @@ asm( \
"movzbl %%al,%1 \n\t" \
:"=g"(_c[LO]), "=r"(cy) \
:"0"(_c[LO]), "1"(cy) \
: "%eax", "%cc")
: "%eax", "cc")
/******************************************************************************/
#elif defined(PSTM_X86_64)
@@ -235,7 +235,7 @@ asm( \
" STR r0,%1 \n\t" \
:"=r"(cy),"=m"(_c[0])\
:"0"(cy),"r"(mu),"r"(*tmpm++),"m"(_c[0])\
:"r0","%cc");
:"r0","cc");
#define PROPCARRY \
asm( \
" LDR r0,%1 \n\t" \
@@ -246,7 +246,7 @@ asm( \
" MOVCC %0,#0 \n\t" \
:"=r"(cy),"=m"(_c[0])\
:"0"(cy),"m"(_c[0])\
:"r0","%cc");
:"r0","cc");
#else /* Non-Thumb2 code */
//#pragma message ("Using 32 bit ARM Assembly Optimizations")
#define INNERMUL \
@@ -259,7 +259,7 @@ asm( \
" STR r0,%1 \n\t" \
:"=r"(cy),"=m"(_c[0])\
:"0"(cy),"r"(mu),"r"(*tmpm++),"m"(_c[0])\
:"r0","%cc");
:"r0","cc");
#define PROPCARRY \
asm( \
" LDR r0,%1 \n\t" \
@@ -269,7 +269,7 @@ asm( \
" MOVCC %0,#0 \n\t" \
:"=r"(cy),"=m"(_c[0])\
:"0"(cy),"m"(_c[0])\
:"r0","%cc");
:"r0","cc");
#endif /* __thumb2__ */
@@ -340,7 +340,7 @@ asm( \
#define LO 0
/* computes x/R == x (mod N) via Montgomery Reduction */
int32 pstm_montgomery_reduce(psPool_t *pool, pstm_int *a, pstm_int *m,
int32 FAST_FUNC pstm_montgomery_reduce(psPool_t *pool, pstm_int *a, pstm_int *m,
pstm_digit mp, pstm_digit *paD, uint32 paDlen)
{
pstm_digit *c, *_c, *tmpm, mu;
+3 -3
View File
@@ -85,7 +85,7 @@ asm( \
"addl %%eax,%0 \n\t" \
"adcl %%edx,%1 \n\t" \
"adcl $0,%2 \n\t" \
:"=rm"(c0), "=rm"(c1), "=rm"(c2): "0"(c0), "1"(c1), "2"(c2), "m"(i), "m"(j) :"%eax","%edx","%cc");
:"=rm"(c0), "=rm"(c1), "=rm"(c2): "0"(c0), "1"(c1), "2"(c2), "m"(i), "m"(j) :"%eax","%edx","cc");
//bbox: ^^^ replaced "=r" with "=rm": %ebx is not available on shared build
/******************************************************************************/
@@ -155,7 +155,7 @@ asm( \
" ADDS %0,%0,r0 \n\t" \
" ADCS %1,%1,r1 \n\t" \
" ADC %2,%2,#0 \n\t" \
:"=r"(c0), "=r"(c1), "=r"(c2) : "0"(c0), "1"(c1), "2"(c2), "r"(i), "r"(j) : "r0", "r1", "%cc");
:"=r"(c0), "=r"(c1), "=r"(c2) : "0"(c0), "1"(c1), "2"(c2), "r"(i), "r"(j) : "r0", "r1", "cc");
/******************************************************************************/
#elif defined(PSTM_MIPS)
@@ -754,7 +754,7 @@ static int32 pstm_mul_comba32(pstm_int *A, pstm_int *B, pstm_int *C)
/******************************************************************************/
int32 pstm_mul_comba(psPool_t *pool, pstm_int *A, pstm_int *B, pstm_int *C,
int32 FAST_FUNC pstm_mul_comba(psPool_t *pool, pstm_int *A, pstm_int *B, pstm_int *C,
pstm_digit *paD, uint32 paDlen)
{
#ifdef USE_1024_KEY_SPEED_OPTIMIZATIONS
+12 -12
View File
@@ -78,7 +78,7 @@ asm( \
"addl %%eax,%0 \n\t" \
"adcl %%edx,%1 \n\t" \
"adcl $0,%2 \n\t" \
:"=rm"(c0), "=rm"(c1), "=rm"(c2): "0"(c0), "1"(c1), "2"(c2), "m"(i) :"%eax","%edx","%cc");
:"=rm"(c0), "=rm"(c1), "=rm"(c2): "0"(c0), "1"(c1), "2"(c2), "m"(i) :"%eax","%edx","cc");
//bbox: ^^^ replaced "=r" with "=rm": %ebx is not available on shared build
#define SQRADD2(i, j) \
@@ -91,7 +91,7 @@ asm( \
"addl %%eax,%0 \n\t" \
"adcl %%edx,%1 \n\t" \
"adcl $0,%2 \n\t" \
:"=rm"(c0), "=rm"(c1), "=rm"(c2): "0"(c0), "1"(c1), "2"(c2), "m"(i), "m"(j) :"%eax","%edx","%cc");
:"=rm"(c0), "=rm"(c1), "=rm"(c2): "0"(c0), "1"(c1), "2"(c2), "m"(i), "m"(j) :"%eax","%edx","cc");
//bbox: ^^^ replaced "=r" with "=rm": %ebx is not available on shared build
#define SQRADDSC(i, j) \
@@ -101,7 +101,7 @@ asm( \
"movl %%eax,%0 \n\t" \
"movl %%edx,%1 \n\t" \
"xorl %2,%2 \n\t" \
:"=r"(sc0), "=r"(sc1), "=r"(sc2): "0"(sc0), "1"(sc1), "2"(sc2), "g"(i), "g"(j) :"%eax","%edx","%cc");
:"=r"(sc0), "=r"(sc1), "=r"(sc2): "0"(sc0), "1"(sc1), "2"(sc2), "g"(i), "g"(j) :"%eax","%edx","cc");
#define SQRADDAC(i, j) \
asm( \
@@ -110,7 +110,7 @@ asm( \
"addl %%eax,%0 \n\t" \
"adcl %%edx,%1 \n\t" \
"adcl $0,%2 \n\t" \
:"=r"(sc0), "=r"(sc1), "=r"(sc2): "0"(sc0), "1"(sc1), "2"(sc2), "g"(i), "g"(j) :"%eax","%edx","%cc");
:"=r"(sc0), "=r"(sc1), "=r"(sc2): "0"(sc0), "1"(sc1), "2"(sc2), "g"(i), "g"(j) :"%eax","%edx","cc");
#define SQRADDDB \
asm( \
@@ -120,7 +120,7 @@ asm( \
"addl %6,%0 \n\t" \
"adcl %7,%1 \n\t" \
"adcl %8,%2 \n\t" \
:"=r"(c0), "=r"(c1), "=r"(c2) : "0"(c0), "1"(c1), "2"(c2), "r"(sc0), "r"(sc1), "r"(sc2) : "%cc");
:"=r"(c0), "=r"(c1), "=r"(c2) : "0"(c0), "1"(c1), "2"(c2), "r"(sc0), "r"(sc1), "r"(sc2) : "cc");
/******************************************************************************/
#elif defined(PSTM_X86_64)
@@ -223,7 +223,7 @@ asm( \
" ADDS %0,%0,r0 \n\t" \
" ADCS %1,%1,r1 \n\t" \
" ADC %2,%2,#0 \n\t" \
:"=r"(c0), "=r"(c1), "=r"(c2) : "0"(c0), "1"(c1), "2"(c2), "r"(i) : "r0", "r1", "%cc");
:"=r"(c0), "=r"(c1), "=r"(c2) : "0"(c0), "1"(c1), "2"(c2), "r"(i) : "r0", "r1", "cc");
/* for squaring some of the terms are doubled... */
#define SQRADD2(i, j) \
@@ -235,13 +235,13 @@ asm( \
" ADDS %0,%0,r0 \n\t" \
" ADCS %1,%1,r1 \n\t" \
" ADC %2,%2,#0 \n\t" \
:"=r"(c0), "=r"(c1), "=r"(c2) : "0"(c0), "1"(c1), "2"(c2), "r"(i), "r"(j) : "r0", "r1", "%cc");
:"=r"(c0), "=r"(c1), "=r"(c2) : "0"(c0), "1"(c1), "2"(c2), "r"(i), "r"(j) : "r0", "r1", "cc");
#define SQRADDSC(i, j) \
asm( \
" UMULL %0,%1,%6,%7 \n\t" \
" SUB %2,%2,%2 \n\t" \
:"=r"(sc0), "=r"(sc1), "=r"(sc2) : "0"(sc0), "1"(sc1), "2"(sc2), "r"(i), "r"(j) : "%cc");
:"=r"(sc0), "=r"(sc1), "=r"(sc2) : "0"(sc0), "1"(sc1), "2"(sc2), "r"(i), "r"(j) : "cc");
#define SQRADDAC(i, j) \
asm( \
@@ -249,7 +249,7 @@ asm( \
" ADDS %0,%0,r0 \n\t" \
" ADCS %1,%1,r1 \n\t" \
" ADC %2,%2,#0 \n\t" \
:"=r"(sc0), "=r"(sc1), "=r"(sc2) : "0"(sc0), "1"(sc1), "2"(sc2), "r"(i), "r"(j) : "r0", "r1", "%cc");
:"=r"(sc0), "=r"(sc1), "=r"(sc2) : "0"(sc0), "1"(sc1), "2"(sc2), "r"(i), "r"(j) : "r0", "r1", "cc");
#define SQRADDDB \
asm( \
@@ -259,7 +259,7 @@ asm( \
" ADDS %0,%0,%3 \n\t" \
" ADCS %1,%1,%4 \n\t" \
" ADC %2,%2,%5 \n\t" \
:"=r"(c0), "=r"(c1), "=r"(c2) : "r"(sc0), "r"(sc1), "r"(sc2), "0"(c0), "1"(c1), "2"(c2) : "%cc");
:"=r"(c0), "=r"(c1), "=r"(c2) : "r"(sc0), "r"(sc1), "r"(sc2), "0"(c0), "1"(c1), "2"(c2) : "cc");
/******************************************************************************/
#elif defined(PSTM_MIPS)
@@ -330,7 +330,7 @@ asm( \
" mflo %0 \n\t" \
" mfhi %1 \n\t" \
" xor %2,%2,%2 \n\t" \
:"=r"(sc0), "=r"(sc1), "=r"(sc2):"0"(sc0), "1"(sc1), "2"(sc2), "r"(i),"r"(j) : "%cc");
:"=r"(sc0), "=r"(sc1), "=r"(sc2):"0"(sc0), "1"(sc1), "2"(sc2), "r"(i),"r"(j) : "cc");
#define SQRADDAC(i, j) \
asm( \
@@ -1085,7 +1085,7 @@ static int32 pstm_sqr_comba32(pstm_int *A, pstm_int *B)
/******************************************************************************/
/*
*/
int32 pstm_sqr_comba(psPool_t *pool, pstm_int *A, pstm_int *B, pstm_digit *paD,
int32 FAST_FUNC pstm_sqr_comba(psPool_t *pool, pstm_int *A, pstm_int *B, pstm_digit *paD,
uint32 paDlen)
{
#ifdef USE_1024_KEY_SPEED_OPTIMIZATIONS
+3 -1
View File
@@ -173,7 +173,9 @@ error:
res = PS_FAILURE;
done:
if (type == PRIVKEY_TYPE && key->optimized) {
pstm_clear_multi(&tmpa, &tmpb, NULL, NULL, NULL, NULL, NULL, NULL);
//pstm_clear_multi(&tmpa, &tmpb, NULL, NULL, NULL, NULL, NULL, NULL);
pstm_clear(&tmpa);
pstm_clear(&tmpb);
}
pstm_clear(&tmp);
return res;
+1 -1
View File
@@ -116,7 +116,7 @@ config FEATURE_UDHCP_PORT
config UDHCP_DEBUG
int "Maximum verbosity level (0..9)"
default 9
default 2
range 0 9
depends on UDHCPD || UDHCPC || UDHCPC6 || DHCPRELAY
help
+15 -7
View File
@@ -54,6 +54,8 @@ const struct dhcp_optflag dhcp_optflags[] = {
{ OPTION_STRING , 0x43 }, /* DHCP_BOOT_FILE */
//TODO: not a string, but a set of LASCII strings:
// { OPTION_STRING , 0x4D }, /* DHCP_USER_CLASS */
{ OPTION_STRING , 0x64 }, /* DHCP_PCODE */
{ OPTION_STRING , 0x65 }, /* DHCP_TCODE */
#if ENABLE_FEATURE_UDHCP_RFC3397
{ OPTION_DNS_STRING | OPTION_LIST , 0x77 }, /* DHCP_DOMAIN_SEARCH */
{ OPTION_SIP_SERVERS , 0x78 }, /* DHCP_SIP_SERVERS */
@@ -121,6 +123,8 @@ const char dhcp_option_strings[] ALIGN1 =
"tftp" "\0" /* DHCP_TFTP_SERVER_NAME*/
"bootfile" "\0" /* DHCP_BOOT_FILE */
// "userclass" "\0" /* DHCP_USER_CLASS */
"tzstr" "\0" /* DHCP_PCODE */
"tzdbstr" "\0" /* DHCP_TCODE */
#if ENABLE_FEATURE_UDHCP_RFC3397
"search" "\0" /* DHCP_DOMAIN_SEARCH */
// doesn't work in udhcpd.conf since OPTION_SIP_SERVERS
@@ -187,7 +191,7 @@ static void log_option(const char *pfx, const uint8_t *opt)
if (dhcp_verbose >= 2) {
char buf[256 * 2 + 2];
*bin2hex(buf, (void*) (opt + OPT_DATA), opt[OPT_LEN]) = '\0';
bb_error_msg("%s: 0x%02x %s", pfx, opt[OPT_CODE], buf);
bb_info_msg("%s: 0x%02x %s", pfx, opt[OPT_CODE], buf);
}
}
#else
@@ -302,7 +306,7 @@ uint8_t* FAST_FUNC udhcp_get_option32(struct dhcp_packet *packet, int code)
{
uint8_t *r = udhcp_get_option(packet, code);
if (r) {
if (r[-1] != 4)
if (r[-OPT_DATA + OPT_LEN] != 4)
r = NULL;
}
return r;
@@ -422,6 +426,7 @@ static NOINLINE void attach_option(
if (errno)
bb_error_msg_and_die("malformed hex string '%s'", buffer);
length = end - allocated;
buffer = allocated;
}
#if ENABLE_FEATURE_UDHCP_RFC3397
if ((optflag->flags & OPTION_TYPE_MASK) == OPTION_DNS_STRING) {
@@ -441,15 +446,14 @@ static NOINLINE void attach_option(
new->data = xmalloc(length + OPT_DATA);
new->data[OPT_CODE] = optflag->code;
new->data[OPT_LEN] = length;
memcpy(new->data + OPT_DATA, (allocated ? allocated : buffer),
length);
memcpy(new->data + OPT_DATA, buffer, length);
} else {
new->data = xmalloc(length + D6_OPT_DATA);
new->data[D6_OPT_CODE] = optflag->code >> 8;
new->data[D6_OPT_CODE + 1] = optflag->code & 0xff;
new->data[D6_OPT_LEN] = length >> 8;
new->data[D6_OPT_LEN + 1] = length & 0xff;
memcpy(new->data + D6_OPT_DATA, (allocated ? allocated : buffer),
memcpy(new->data + D6_OPT_DATA, buffer,
length);
}
@@ -472,6 +476,8 @@ static NOINLINE void attach_option(
/* actually 255 is ok too, but adding a space can overlow it */
existing->data = xrealloc(existing->data, OPT_DATA + 1 + old_len + length);
// So far dhcp_optflags[] has no OPTION_STRING[_HOST] | OPTION_LIST items
#if 0
if ((optflag->flags & OPTION_TYPE_MASK) == OPTION_STRING
|| (optflag->flags & OPTION_TYPE_MASK) == OPTION_STRING_HOST
) {
@@ -479,7 +485,9 @@ static NOINLINE void attach_option(
existing->data[OPT_DATA + old_len] = ' ';
old_len++;
}
memcpy(existing->data + OPT_DATA + old_len, (allocated ? allocated : buffer), length);
#endif
memcpy(existing->data + OPT_DATA + old_len, buffer, length);
existing->data[OPT_LEN] = old_len + length;
} /* else, ignore the data, we could put this in a second option in the future */
} /* else, ignore the new data */
@@ -553,7 +561,7 @@ int FAST_FUNC udhcp_str2optset(const char *const_str, void *arg,
if (retval)
retval = udhcp_str2nip(val, buffer + 4);
break;
case_OPTION_STRING:
case_OPTION_STRING:
case OPTION_STRING:
case OPTION_STRING_HOST:
#if ENABLE_FEATURE_UDHCP_RFC3397
+30 -36
View File
@@ -40,7 +40,7 @@ struct dhcp_packet {
uint32_t yiaddr; /* 'your' (client) IP address */
/* IP address of next server to use in bootstrap, returned in DHCPOFFER, DHCPACK by server */
uint32_t siaddr_nip;
uint32_t gateway_nip; /* relay agent IP address */
uint32_t gateway_nip; /* aka 'giaddr': relay agent IP address */
uint8_t chaddr[16]; /* link-layer client hardware address (MAC) */
uint8_t sname[64]; /* server host name (ASCIZ) */
uint8_t file[128]; /* boot file name (ASCIZ) */
@@ -119,7 +119,7 @@ enum {
//#define DHCP_TIME_SERVER 0x04 /* RFC 868 time server (32-bit, 0 = 1.1.1900) */
//#define DHCP_NAME_SERVER 0x05 /* IEN 116 _really_ ancient kind of NS */
//#define DHCP_DNS_SERVER 0x06
//#define DHCP_LOG_SERVER 0x07 /* port 704 UDP log (not syslog)
//#define DHCP_LOG_SERVER 0x07 /* port 704 UDP log (not syslog) */
//#define DHCP_COOKIE_SERVER 0x08 /* "quote of the day" server */
//#define DHCP_LPR_SERVER 0x09
#define DHCP_HOST_NAME 0x0c /* 12: either client informs server or server gives name to client */
@@ -149,13 +149,15 @@ enum {
//#define DHCP_BOOT_FILE 0x43 /* 67: same as 'file' field */
//#define DHCP_USER_CLASS 0x4d /* 77: RFC 3004. set of LASCII strings. "I am a printer" etc */
#define DHCP_FQDN 0x51 /* 81: client asks to update DNS to map its FQDN to its new IP */
//#define DHCP_PCODE 0x64 /* 100: RFC 4833. IEEE 1003.1 TZ string */
//#define DHCP_TCODE 0x65 /* 101: RFC 4833. Reference to the TZ database string */
//#define DHCP_DOMAIN_SEARCH 0x77 /* 119: RFC 3397. set of ASCIZ string, DNS-style compressed */
//#define DHCP_SIP_SERVERS 0x78 /* 120: RFC 3361. flag byte, then: 0: domain names, 1: IP addrs */
//#define DHCP_STATIC_ROUTES 0x79 /* 121: RFC 3442. (mask,ip,router) tuples */
//#define DHCP_VLAN_ID 0x84 /* 132: 802.1P VLAN ID */
//#define DHCP_VLAN_PRIORITY 0x85 /* 133: 802.1Q VLAN priority */
//#define DHCP_PXE_CONF_FILE 0xd1 /* 209: RFC 5071 Configuration File */
//#define DHCP_PXE_PATH_PREFIX 0xd2 /* 210: RFC 5071 Configuration File */
//#define DHCP_PXE_CONF_FILE 0xd1 /* 209: RFC 5071 Configuration file */
//#define DHCP_PXE_PATH_PREFIX 0xd2 /* 210: RFC 5071 Path prefix */
//#define DHCP_REBOOT_TIME 0xd3 /* 211: RFC 5071 Reboot time */
//#define DHCP_MS_STATIC_ROUTES 0xf9 /* 249: Microsoft's pre-RFC 3442 code for 0x79? */
//#define DHCP_WPAD 0xfc /* 252: MSIE's Web Proxy Autodiscovery Protocol */
@@ -220,10 +222,9 @@ uint8_t *dname_enc(const uint8_t *cstr, int clen, const char *src, int *retlen)
#endif
struct option_set *udhcp_find_option(struct option_set *opt_list, uint8_t code) FAST_FUNC;
// RFC 2131 Table 5: Fields and options used by DHCP clients
//
// Fields 'hops', 'yiaddr', 'siaddr', 'giaddr' are always zero
// Fields 'hops', 'yiaddr', 'siaddr', 'giaddr' are always zero, 'chaddr' is always client's MAC
//
// Field DHCPDISCOVER DHCPINFORM DHCPREQUEST DHCPDECLINE DHCPRELEASE
// ----- ------------ ------------ ----------- ----------- -----------
@@ -232,56 +233,49 @@ struct option_set *udhcp_find_option(struct option_set *opt_list, uint8_t code)
// 'secs' 0 or seconds since 0 or seconds since 0 or seconds since 0 0
// DHCP process started DHCP process started DHCP process started
// 'flags' Set 'BROADCAST' Set 'BROADCAST' Set 'BROADCAST' 0 0
// flag if client flag if client flag if client
// requires broadcast requires broadcast requires broadcast
// reply reply reply
// flag if client needs flag if client needs flag if client needs
// broadcast reply broadcast reply broadcast reply
// 'ciaddr' 0 client's IP 0 or client's IP 0 client's IP
// (BOUND/RENEW/REBIND)
// 'chaddr' client's MAC client's MAC client's MAC client's MAC client's MAC
// 'sname' options or sname options or sname options or sname (unused) (unused)
// 'file' options or file options or file options or file (unused) (unused)
// 'options' options options options message type opt message type opt
//
// Option DHCPDISCOVER DHCPINFORM DHCPREQUEST DHCPDECLINE DHCPRELEASE
// ------ ------------ ---------- ----------- ----------- -----------
// Requested IP address MAY MUST NOT MUST (in MUST MUST NOT
// SELECTING or
// INIT-REBOOT)
// MUST NOT (in
// BOUND or
// RENEWING)
// IP address lease time MAY MUST NOT MAY MUST NOT MUST NOT
// Use 'file'/'sname' fields MAY MAY MAY MAY MAY
// Client identifier MAY MAY MAY MAY MAY
// Vendor class identifier MAY MAY MAY MUST NOT MUST NOT
// Server identifier MUST NOT MUST NOT MUST (after MUST MUST
// SELECTING)
// Option DHCPDISCOVER DHCPINFORM DHCPREQUEST DHCPDECLINE DHCPRELEASE
// ------ ------------ ---------- ----------- ----------- -----------
// Requested IP address MAY MUST NOT MUST (in SELECTING MUST MUST NOT
// or INIT-REBOOT)
// MUST NOT (in BOUND
// or RENEWING)
// IP address lease time MAY MUST NOT MAY MUST NOT MUST NOT
// Use 'file'/'sname' fields MAY MAY MAY MAY MAY
// Client identifier MAY MAY MAY MAY MAY
// Vendor class identifier MAY MAY MAY MUST NOT MUST NOT
// Server identifier MUST NOT MUST NOT MUST (after SELECTING) MUST MUST
// MUST NOT (after
// INIT-REBOOT,
// BOUND, RENEWING
// or REBINDING)
// Parameter request list MAY MAY MAY MUST NOT MUST NOT
// Maximum message size MAY MAY MAY MUST NOT MUST NOT
// Message SHOULD NOT SHOULD NOT SHOULD NOT SHOULD SHOULD
// Site-specific MAY MAY MAY MUST NOT MUST NOT
// All others MAY MAY MAY MUST NOT MUST NOT
// INIT-REBOOT, BOUND,
// RENEWING or REBINDING)
// Parameter request list MAY MAY MAY MUST NOT MUST NOT
// Maximum message size MAY MAY MAY MUST NOT MUST NOT
// Message SHOULD NOT SHOULD NOT SHOULD NOT SHOULD SHOULD
// Site-specific MAY MAY MAY MUST NOT MUST NOT
// All others MAY MAY MAY MUST NOT MUST NOT
/*** Logging ***/
#if defined CONFIG_UDHCP_DEBUG && CONFIG_UDHCP_DEBUG >= 1
# define IF_UDHCP_VERBOSE(...) __VA_ARGS__
extern unsigned dhcp_verbose;
# define log1(...) do { if (dhcp_verbose >= 1) bb_error_msg(__VA_ARGS__); } while (0)
# define log1(...) do { if (dhcp_verbose >= 1) bb_info_msg(__VA_ARGS__); } while (0)
# if CONFIG_UDHCP_DEBUG >= 2
void udhcp_dump_packet(struct dhcp_packet *packet) FAST_FUNC;
# define log2(...) do { if (dhcp_verbose >= 2) bb_error_msg(__VA_ARGS__); } while (0)
# define log2(...) do { if (dhcp_verbose >= 2) bb_info_msg(__VA_ARGS__); } while (0)
# else
# define udhcp_dump_packet(...) ((void)0)
# define log2(...) ((void)0)
# endif
# if CONFIG_UDHCP_DEBUG >= 3
# define log3(...) do { if (dhcp_verbose >= 3) bb_error_msg(__VA_ARGS__); } while (0)
# define log3(...) do { if (dhcp_verbose >= 3) bb_info_msg(__VA_ARGS__); } while (0)
# else
# define log3(...) ((void)0)
# endif
+7 -2
View File
@@ -141,11 +141,16 @@ struct client6_data_t {
unsigned env_idx;
/* link-local IPv6 address */
struct in6_addr ll_ip6;
};
} FIX_ALIASING;
#define client6_data (*(struct client6_data_t*)(&bb_common_bufsiz1[COMMON_BUFSIZE - sizeof(struct client6_data_t)]))
int FAST_FUNC d6_read_interface(const char *interface, int *ifindex, struct in6_addr *nip6, uint8_t *mac);
int FAST_FUNC d6_read_interface(
const char *interface,
int *ifindex,
struct in6_addr *nip6,
uint8_t *mac
);
int FAST_FUNC d6_listen_socket(int port, const char *inf);
+114 -113
View File
@@ -2,15 +2,13 @@
/*
* DHCPv6 client.
*
* WARNING: THIS CODE IS INCOMPLETE.
*
* Copyright (C) 2011-2017 Denys Vlasenko.
*
* Licensed under GPLv2, see file LICENSE in this source tree.
*/
//config:config UDHCPC6
//config: bool "udhcpc6 (21 kb)"
//config: default n # not yet ready
//config: default y
//config: depends on FEATURE_IPV6
//config: help
//config: udhcpc6 is a DHCPv6 client
@@ -65,7 +63,7 @@
#include <netpacket/packet.h>
#include <linux/filter.h>
/* "struct client_config_t client_config" is in bb_common_bufsiz1 */
/* "struct client_data_t client_data" is in bb_common_bufsiz1 */
static const struct dhcp_optflag d6_optflags[] = {
#if ENABLE_FEATURE_UDHCPC6_RFC3646
@@ -206,7 +204,6 @@ static void *d6_copy_option(uint8_t *option, uint8_t *option_end, unsigned code)
return xmemdup(opt, opt[3] + 4);
}
/*** Script execution code ***/
static char** new_env(void)
@@ -430,7 +427,7 @@ static char **fill_envp(const uint8_t *option, const uint8_t *option_end)
client6_data.env_ptr = NULL;
client6_data.env_idx = 0;
*new_env() = xasprintf("interface=%s", client_config.interface);
*new_env() = xasprintf("interface=%s", client_data.interface);
if (option)
option_to_env(option, option_end);
@@ -452,8 +449,8 @@ static void d6_run_script(const uint8_t *option, const uint8_t *option_end,
envp = fill_envp(option, option_end);
/* call script */
log1("executing %s %s", client_config.script, name);
argv[0] = (char*) client_config.script;
log1("executing %s %s", client_data.script, name);
argv[0] = (char*) client_data.script;
argv[1] = (char*) name;
argv[2] = NULL;
spawn_and_wait(argv);
@@ -489,7 +486,7 @@ static uint8_t *init_d6_packet(struct d6_packet *packet, char type, uint32_t xid
packet->d6_xid32 = xid;
packet->d6_msg_type = type;
clientid = (void*)client_config.clientid;
clientid = (void*)client_data.clientid;
return mempcpy(packet->d6_options, clientid, clientid->len + 2+2);
}
@@ -502,7 +499,7 @@ static uint8_t *add_d6_client_options(uint8_t *ptr)
ptr += 4;
for (option = 1; option < 256; option++) {
if (client_config.opt_mask[option >> 3] & (1 << (option & 7))) {
if (client_data.opt_mask[option >> 3] & (1 << (option & 7))) {
ptr[0] = (option >> 8);
ptr[1] = option;
ptr += 2;
@@ -521,7 +518,7 @@ static uint8_t *add_d6_client_options(uint8_t *ptr)
ptr = mempcpy(ptr, &opt_fqdn_req, sizeof(opt_fqdn_req));
#endif
/* Add -x options if any */
curr = client_config.options;
curr = client_data.options;
while (curr) {
len = (curr->data[D6_OPT_LEN] << 8) | curr->data[D6_OPT_LEN + 1];
ptr = mempcpy(ptr, curr->data, D6_OPT_DATA + len);
@@ -531,8 +528,9 @@ static uint8_t *add_d6_client_options(uint8_t *ptr)
return ptr;
}
static int d6_mcast_from_client_config_ifindex(struct d6_packet *packet, uint8_t *end)
static int d6_mcast_from_client_data_ifindex(struct d6_packet *packet, uint8_t *end)
{
/* FF02::1:2 is "All_DHCP_Relay_Agents_and_Servers" address */
static const uint8_t FF02__1_2[16] = {
0xFF, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x02,
@@ -542,7 +540,7 @@ static int d6_mcast_from_client_config_ifindex(struct d6_packet *packet, uint8_t
packet, (end - (uint8_t*) packet),
/*src*/ &client6_data.ll_ip6, CLIENT_PORT6,
/*dst*/ (struct in6_addr*)FF02__1_2, SERVER_PORT6, MAC_BCAST_ADDR,
client_config.ifindex
client_data.ifindex
);
}
@@ -672,8 +670,8 @@ static NOINLINE int send_d6_discover(uint32_t xid, struct in6_addr *requested_ip
*/
opt_ptr = add_d6_client_options(opt_ptr);
bb_error_msg("sending %s", "discover");
return d6_mcast_from_client_config_ifindex(&packet, opt_ptr);
bb_info_msg("sending %s", "discover");
return d6_mcast_from_client_data_ifindex(&packet, opt_ptr);
}
/* Multicast a DHCPv6 request message
@@ -729,8 +727,8 @@ static NOINLINE int send_d6_select(uint32_t xid)
*/
opt_ptr = add_d6_client_options(opt_ptr);
bb_error_msg("sending %s", "select");
return d6_mcast_from_client_config_ifindex(&packet, opt_ptr);
bb_info_msg("sending %s", "select");
return d6_mcast_from_client_data_ifindex(&packet, opt_ptr);
}
/* Unicast or broadcast a DHCP renew message
@@ -802,15 +800,15 @@ static NOINLINE int send_d6_renew(uint32_t xid, struct in6_addr *server_ipv6, st
*/
opt_ptr = add_d6_client_options(opt_ptr);
bb_error_msg("sending %s", "renew");
bb_info_msg("sending %s", "renew");
if (server_ipv6)
return d6_send_kernel_packet(
&packet, (opt_ptr - (uint8_t*) &packet),
our_cur_ipv6, CLIENT_PORT6,
server_ipv6, SERVER_PORT6,
client_config.ifindex
client_data.ifindex
);
return d6_mcast_from_client_config_ifindex(&packet, opt_ptr);
return d6_mcast_from_client_data_ifindex(&packet, opt_ptr);
}
/* Unicast a DHCP release message */
@@ -832,12 +830,12 @@ int send_d6_release(struct in6_addr *server_ipv6, struct in6_addr *our_cur_ipv6)
if (client6_data.ia_pd)
opt_ptr = mempcpy(opt_ptr, client6_data.ia_pd, client6_data.ia_pd->len + 2+2);
bb_error_msg("sending %s", "release");
bb_info_msg("sending %s", "release");
return d6_send_kernel_packet(
&packet, (opt_ptr - (uint8_t*) &packet),
our_cur_ipv6, CLIENT_PORT6,
server_ipv6, SERVER_PORT6,
client_config.ifindex
client_data.ifindex
);
}
@@ -903,16 +901,14 @@ static NOINLINE int d6_recv_raw_packet(struct in6_addr *peer_ipv6, struct d6_pac
return bytes;
}
/*** Main ***/
static int sockfd = -1;
/* Values for client_data.listen_mode */
#define LISTEN_NONE 0
#define LISTEN_KERNEL 1
#define LISTEN_RAW 2
static smallint listen_mode;
/* Values for client_data.state */
/* initial state: (re)start DHCP negotiation */
#define INIT_SELECTING 0
/* discover was sent, DHCPOFFER reply received */
@@ -927,7 +923,6 @@ static smallint listen_mode;
#define RENEW_REQUESTED 5
/* release, possibly manually requested (SIGUSR2) */
#define RELEASED 6
static smallint state;
static int d6_raw_socket(int ifindex)
{
@@ -986,7 +981,7 @@ static int d6_raw_socket(int ifindex)
log2("opening raw socket on ifindex %d", ifindex);
fd = xsocket(PF_PACKET, SOCK_DGRAM, htons(ETH_P_IPV6));
log2("got raw socket fd %d", fd);
log3("got raw socket fd %d", fd);
memset(&sock, 0, sizeof(sock)); /* let's be deterministic */
sock.sll_family = AF_PACKET;
@@ -1021,35 +1016,35 @@ static void change_listen_mode(int new_mode)
: "none"
);
listen_mode = new_mode;
if (sockfd >= 0) {
close(sockfd);
sockfd = -1;
client_data.listen_mode = new_mode;
if (client_data.sockfd >= 0) {
close(client_data.sockfd);
client_data.sockfd = -1;
}
if (new_mode == LISTEN_KERNEL)
sockfd = udhcp_listen_socket(/*INADDR_ANY,*/ CLIENT_PORT6, client_config.interface);
client_data.sockfd = udhcp_listen_socket(/*INADDR_ANY,*/ CLIENT_PORT6, client_data.interface);
else if (new_mode != LISTEN_NONE)
sockfd = d6_raw_socket(client_config.ifindex);
/* else LISTEN_NONE: sockfd stays closed */
client_data.sockfd = d6_raw_socket(client_data.ifindex);
/* else LISTEN_NONE: client_data.sockfd stays closed */
}
/* Called only on SIGUSR1 */
static void perform_renew(void)
{
bb_error_msg("performing DHCP renew");
switch (state) {
bb_info_msg("performing DHCP renew");
switch (client_data.state) {
case BOUND:
change_listen_mode(LISTEN_KERNEL);
case RENEWING:
case REBINDING:
state = RENEW_REQUESTED;
client_data.state = RENEW_REQUESTED;
break;
case RENEW_REQUESTED: /* impatient are we? fine, square 1 */
d6_run_script_no_option("deconfig");
case REQUESTING:
case RELEASED:
change_listen_mode(LISTEN_RAW);
state = INIT_SELECTING;
client_data.state = INIT_SELECTING;
break;
case INIT_SELECTING:
break;
@@ -1059,15 +1054,15 @@ static void perform_renew(void)
static void perform_d6_release(struct in6_addr *server_ipv6, struct in6_addr *our_cur_ipv6)
{
/* send release packet */
if (state == BOUND
|| state == RENEWING
|| state == REBINDING
|| state == RENEW_REQUESTED
if (client_data.state == BOUND
|| client_data.state == RENEWING
|| client_data.state == REBINDING
|| client_data.state == RENEW_REQUESTED
) {
bb_error_msg("unicasting a release");
bb_info_msg("unicasting a release");
send_d6_release(server_ipv6, our_cur_ipv6); /* unicast */
}
bb_error_msg("entering released state");
bb_info_msg("entering released state");
/*
* We can be here on: SIGUSR2,
* or on exit (SIGTERM) and -R "release on quit" is specified.
@@ -1076,7 +1071,7 @@ static void perform_d6_release(struct in6_addr *server_ipv6, struct in6_addr *ou
*/
d6_run_script_no_option("deconfig");
change_listen_mode(LISTEN_NONE);
state = RELEASED;
client_data.state = RELEASED;
}
///static uint8_t* alloc_dhcp_option(int code, const char *str, int extra)
@@ -1096,7 +1091,7 @@ static void client_background(void)
bb_daemonize(0);
logmode &= ~LOGMODE_STDIO;
/* rewrite pidfile, as our pid is different now */
write_pidfile(client_config.pidfile);
write_pidfile(client_data.pidfile);
}
#endif
@@ -1147,7 +1142,6 @@ static void client_background(void)
//usage: "\n USR1 Renew lease"
//usage: "\n USR2 Release lease"
int udhcpc6_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
int udhcpc6_main(int argc UNUSED_PARAM, char **argv)
{
@@ -1176,8 +1170,13 @@ int udhcpc6_main(int argc UNUSED_PARAM, char **argv)
/* Default options */
IF_FEATURE_UDHCP_PORT(SERVER_PORT6 = 547;)
IF_FEATURE_UDHCP_PORT(CLIENT_PORT6 = 546;)
client_config.interface = "eth0";
client_config.script = CONFIG_UDHCPC_DEFAULT_SCRIPT;
client_data.interface = "eth0";
client_data.script = CONFIG_UDHCPC_DEFAULT_SCRIPT;
client_data.sockfd = -1;
/* Make sure fd 0,1,2 are open */
/* Set up the signal pipe on fds 3,4 - must be before openlog() */
udhcp_sp_setup();
/* Parse command line */
opt = getopt32long(argv, "^"
@@ -1189,8 +1188,8 @@ int udhcpc6_main(int argc UNUSED_PARAM, char **argv)
"v"
"\0" IF_UDHCP_VERBOSE("vv") /* -v is a counter */
, udhcpc6_longopts
, &client_config.interface, &client_config.pidfile, &str_r /* i,p */
, &client_config.script /* s */
, &client_data.interface, &client_data.pidfile, &str_r /* i,p */
, &client_data.script /* s */
, &discover_timeout, &discover_retries, &tryagain_timeout /* T,t,A */
, &list_O
, &list_x
@@ -1221,29 +1220,29 @@ int udhcpc6_main(int argc UNUSED_PARAM, char **argv)
n = udhcp_option_idx(optstr, d6_option_strings);
n = d6_optflags[n].code;
}
client_config.opt_mask[n >> 3] |= 1 << (n & 7);
client_data.opt_mask[n >> 3] |= 1 << (n & 7);
}
if (!(opt & OPT_o)) {
unsigned i, n;
for (i = 0; (n = d6_optflags[i].code) != 0; i++) {
if (d6_optflags[i].flags & OPTION_REQ) {
client_config.opt_mask[n >> 3] |= 1 << (n & 7);
client_data.opt_mask[n >> 3] |= 1 << (n & 7);
}
}
}
while (list_x) {
char *optstr = xstrdup(llist_pop(&list_x));
udhcp_str2optset(optstr, &client_config.options,
udhcp_str2optset(optstr, &client_data.options,
d6_optflags, d6_option_strings,
/*dhcpv6:*/ 1
);
free(optstr);
}
if (d6_read_interface(client_config.interface,
&client_config.ifindex,
if (d6_read_interface(client_data.interface,
&client_data.ifindex,
&client6_data.ll_ip6,
client_config.client_mac)
client_data.client_mac)
) {
return 1;
}
@@ -1257,8 +1256,8 @@ int udhcpc6_main(int argc UNUSED_PARAM, char **argv)
clientid->data[1] = 3; /* DUID-LL */
clientid->data[3] = 1; /* ethernet */
clientid_mac_ptr = clientid->data + 2+2;
memcpy(clientid_mac_ptr, client_config.client_mac, 6);
client_config.clientid = (void*)clientid;
memcpy(clientid_mac_ptr, client_data.client_mac, 6);
client_data.clientid = (void*)clientid;
}
#if !BB_MMU
@@ -1273,16 +1272,12 @@ int udhcpc6_main(int argc UNUSED_PARAM, char **argv)
logmode |= LOGMODE_SYSLOG;
}
/* Make sure fd 0,1,2 are open */
bb_sanitize_stdio();
/* Create pidfile */
write_pidfile(client_config.pidfile);
write_pidfile(client_data.pidfile);
/* Goes to stdout (unless NOMMU) and possibly syslog */
bb_error_msg("started, v"BB_VER);
/* Set up the signal pipe */
udhcp_sp_setup();
bb_info_msg("started, v"BB_VER);
state = INIT_SELECTING;
client_data.state = INIT_SELECTING;
d6_run_script_no_option("deconfig");
change_listen_mode(LISTEN_RAW);
packet_num = 0;
@@ -1301,16 +1296,16 @@ int udhcpc6_main(int argc UNUSED_PARAM, char **argv)
/* silence "uninitialized!" warning */
unsigned timestamp_before_wait = timestamp_before_wait;
//bb_error_msg("sockfd:%d, listen_mode:%d", sockfd, listen_mode);
//bb_error_msg("sockfd:%d, listen_mode:%d", client_data.sockfd, client_data.listen_mode);
/* Was opening raw or udp socket here
* if (listen_mode != LISTEN_NONE && sockfd < 0),
* if (client_data.listen_mode != LISTEN_NONE && client_data.sockfd < 0),
* but on fast network renew responses return faster
* than we open sockets. Thus this code is moved
* to change_listen_mode(). Thus we open listen socket
* BEFORE we send renew request (see "case BOUND:"). */
udhcp_sp_fd_set(pfds, sockfd);
udhcp_sp_fd_set(pfds, client_data.sockfd);
tv = timeout - already_waited_sec;
retval = 0;
@@ -1339,20 +1334,20 @@ int udhcpc6_main(int argc UNUSED_PARAM, char **argv)
* or if the status of the bridge changed).
* Refresh ifindex and client_mac:
*/
if (d6_read_interface(client_config.interface,
&client_config.ifindex,
if (d6_read_interface(client_data.interface,
&client_data.ifindex,
&client6_data.ll_ip6,
client_config.client_mac)
client_data.client_mac)
) {
goto ret0; /* iface is gone? */
}
memcpy(clientid_mac_ptr, client_config.client_mac, 6);
memcpy(clientid_mac_ptr, client_data.client_mac, 6);
/* We will restart the wait in any case */
already_waited_sec = 0;
switch (state) {
switch (client_data.state) {
case INIT_SELECTING:
if (!discover_retries || packet_num < discover_retries) {
if (packet_num == 0)
@@ -1367,14 +1362,20 @@ int udhcpc6_main(int argc UNUSED_PARAM, char **argv)
d6_run_script_no_option("leasefail");
#if BB_MMU /* -b is not supported on NOMMU */
if (opt & OPT_b) { /* background if no lease */
bb_error_msg("no lease, forking to background");
bb_info_msg("no lease, forking to background");
client_background();
/* do not background again! */
opt = ((opt & ~OPT_b) | OPT_f);
opt = ((opt & ~(OPT_b|OPT_n)) | OPT_f);
/* ^^^ also disables -n (-b takes priority over -n):
* ifup's default udhcpc options are -R -n,
* and users want to be able to add -b
* (in a config file) to make it background
* _and not exit_.
*/
} else
#endif
if (opt & OPT_n) { /* abort if no lease */
bb_error_msg("no lease, failing");
bb_info_msg("no lease, failing");
retval = 1;
goto ret;
}
@@ -1395,12 +1396,12 @@ int udhcpc6_main(int argc UNUSED_PARAM, char **argv)
* were seen in the wild. Treat them similarly
* to "no response to discover" case */
change_listen_mode(LISTEN_RAW);
state = INIT_SELECTING;
client_data.state = INIT_SELECTING;
goto leasefail;
case BOUND:
/* 1/2 lease passed, enter renewing state */
state = RENEWING;
client_config.first_secs = 0; /* make secs field count from 0 */
client_data.state = RENEWING;
client_data.first_secs = 0; /* make secs field count from 0 */
change_listen_mode(LISTEN_KERNEL);
log1("entering renew state");
/* fall right through */
@@ -1423,7 +1424,7 @@ int udhcpc6_main(int argc UNUSED_PARAM, char **argv)
}
/* Timed out, enter rebinding state */
log1("entering rebinding state");
state = REBINDING;
client_data.state = REBINDING;
/* fall right through */
case REBINDING:
/* Switch to bcast receive */
@@ -1437,10 +1438,10 @@ int udhcpc6_main(int argc UNUSED_PARAM, char **argv)
continue;
}
/* Timed out, enter init state */
bb_error_msg("lease lost, entering init state");
bb_info_msg("lease lost, entering init state");
d6_run_script_no_option("deconfig");
state = INIT_SELECTING;
client_config.first_secs = 0; /* make secs field count from 0 */
client_data.state = INIT_SELECTING;
client_data.first_secs = 0; /* make secs field count from 0 */
/*timeout = 0; - already is */
packet_num = 0;
continue;
@@ -1456,10 +1457,10 @@ int udhcpc6_main(int argc UNUSED_PARAM, char **argv)
/* Is it a signal? */
switch (udhcp_sp_read()) {
case SIGUSR1:
client_config.first_secs = 0; /* make secs field count from 0 */
client_data.first_secs = 0; /* make secs field count from 0 */
already_waited_sec = 0;
perform_renew();
if (state == RENEW_REQUESTED) {
if (client_data.state == RENEW_REQUESTED) {
/* We might be either on the same network
* (in which case renew might work),
* or we might be on a completely different one
@@ -1482,7 +1483,7 @@ int udhcpc6_main(int argc UNUSED_PARAM, char **argv)
timeout = INT_MAX;
continue;
case SIGTERM:
bb_error_msg("received %s", "SIGTERM");
bb_info_msg("received %s", "SIGTERM");
goto ret0;
}
@@ -1494,15 +1495,15 @@ int udhcpc6_main(int argc UNUSED_PARAM, char **argv)
int len;
/* A packet is ready, read it */
if (listen_mode == LISTEN_KERNEL)
len = d6_recv_kernel_packet(&srv6_buf, &packet, sockfd);
if (client_data.listen_mode == LISTEN_KERNEL)
len = d6_recv_kernel_packet(&srv6_buf, &packet, client_data.sockfd);
else
len = d6_recv_raw_packet(&srv6_buf, &packet, sockfd);
len = d6_recv_raw_packet(&srv6_buf, &packet, client_data.sockfd);
if (len == -1) {
/* Error is severe, reopen socket */
bb_error_msg("read error: "STRERROR_FMT", reopening socket" STRERROR_ERRNO);
sleep(discover_timeout); /* 3 seconds by default */
change_listen_mode(listen_mode); /* just close and reopen */
change_listen_mode(client_data.listen_mode); /* just close and reopen */
}
/* If this packet will turn out to be unrelated/bogus,
* we will go back and wait for next one.
@@ -1519,7 +1520,7 @@ int udhcpc6_main(int argc UNUSED_PARAM, char **argv)
continue;
}
switch (state) {
switch (client_data.state) {
case INIT_SELECTING:
if (packet.d6_msg_type == D6_MSG_ADVERTISE)
goto type_is_ok;
@@ -1542,15 +1543,15 @@ int udhcpc6_main(int argc UNUSED_PARAM, char **argv)
option = d6_find_option(packet.d6_options, packet_end, D6_OPT_STATUS_CODE);
if (option && (option->data[0] | option->data[1]) != 0) {
/* return to init state */
bb_error_msg("received DHCP NAK (%u)", option->data[4]);
bb_info_msg("received DHCP NAK (%u)", option->data[4]);
d6_run_script(packet.d6_options,
packet_end, "nak");
if (state != REQUESTING)
if (client_data.state != REQUESTING)
d6_run_script_no_option("deconfig");
change_listen_mode(LISTEN_RAW);
sleep(3); /* avoid excessive network traffic */
state = INIT_SELECTING;
client_config.first_secs = 0; /* make secs field count from 0 */
client_data.state = INIT_SELECTING;
client_data.first_secs = 0; /* make secs field count from 0 */
requested_ipv6 = NULL;
timeout = 0;
packet_num = 0;
@@ -1559,7 +1560,7 @@ int udhcpc6_main(int argc UNUSED_PARAM, char **argv)
}
option = d6_copy_option(packet.d6_options, packet_end, D6_OPT_SERVERID);
if (!option) {
bb_error_msg("no server ID, ignoring packet");
bb_info_msg("no server ID, ignoring packet");
continue;
/* still selecting - this server looks bad */
}
@@ -1570,7 +1571,7 @@ int udhcpc6_main(int argc UNUSED_PARAM, char **argv)
client6_data.server_id = option;
if (packet.d6_msg_type == D6_MSG_ADVERTISE) {
/* enter requesting state */
state = REQUESTING;
client_data.state = REQUESTING;
timeout = 0;
packet_num = 0;
already_waited_sec = 0;
@@ -1668,11 +1669,11 @@ int udhcpc6_main(int argc UNUSED_PARAM, char **argv)
free(client6_data.ia_na);
client6_data.ia_na = d6_copy_option(packet.d6_options, packet_end, D6_OPT_IA_NA);
if (!client6_data.ia_na) {
bb_error_msg("no %s option, ignoring packet", "IA_NA");
bb_info_msg("no %s option, ignoring packet", "IA_NA");
continue;
}
if (client6_data.ia_na->len < (4 + 4 + 4) + (2 + 2 + 16 + 4 + 4)) {
bb_error_msg("%s option is too short:%d bytes",
bb_info_msg("%s option is too short:%d bytes",
"IA_NA", client6_data.ia_na->len);
continue;
}
@@ -1681,11 +1682,11 @@ int udhcpc6_main(int argc UNUSED_PARAM, char **argv)
D6_OPT_IAADDR
);
if (!iaaddr) {
bb_error_msg("no %s option, ignoring packet", "IAADDR");
bb_info_msg("no %s option, ignoring packet", "IAADDR");
continue;
}
if (iaaddr->len < (16 + 4 + 4)) {
bb_error_msg("%s option is too short:%d bytes",
bb_info_msg("%s option is too short:%d bytes",
"IAADDR", iaaddr->len);
continue;
}
@@ -1696,7 +1697,7 @@ int udhcpc6_main(int argc UNUSED_PARAM, char **argv)
move_from_unaligned32(lease_seconds, iaaddr->data + 16 + 4);
lease_seconds = ntohl(lease_seconds);
/// TODO: check for 0 lease time?
bb_error_msg("%s obtained, lease time %u",
bb_info_msg("%s obtained, lease time %u",
"IPv6", /*inet_ntoa(temp_addr),*/ (unsigned)lease_seconds);
address_timeout = lease_seconds;
}
@@ -1706,11 +1707,11 @@ int udhcpc6_main(int argc UNUSED_PARAM, char **argv)
free(client6_data.ia_pd);
client6_data.ia_pd = d6_copy_option(packet.d6_options, packet_end, D6_OPT_IA_PD);
if (!client6_data.ia_pd) {
bb_error_msg("no %s option, ignoring packet", "IA_PD");
bb_info_msg("no %s option, ignoring packet", "IA_PD");
continue;
}
if (client6_data.ia_pd->len < (4 + 4 + 4) + (2 + 2 + 4 + 4 + 1 + 16)) {
bb_error_msg("%s option is too short:%d bytes",
bb_info_msg("%s option is too short:%d bytes",
"IA_PD", client6_data.ia_pd->len);
continue;
}
@@ -1719,17 +1720,17 @@ int udhcpc6_main(int argc UNUSED_PARAM, char **argv)
D6_OPT_IAPREFIX
);
if (!iaprefix) {
bb_error_msg("no %s option, ignoring packet", "IAPREFIX");
bb_info_msg("no %s option, ignoring packet", "IAPREFIX");
continue;
}
if (iaprefix->len < (4 + 4 + 1 + 16)) {
bb_error_msg("%s option is too short:%d bytes",
bb_info_msg("%s option is too short:%d bytes",
"IAPREFIX", iaprefix->len);
continue;
}
move_from_unaligned32(lease_seconds, iaprefix->data + 4);
lease_seconds = ntohl(lease_seconds);
bb_error_msg("%s obtained, lease time %u",
bb_info_msg("%s obtained, lease time %u",
"prefix", /*inet_ntoa(temp_addr),*/ (unsigned)lease_seconds);
prefix_timeout = lease_seconds;
}
@@ -1745,9 +1746,9 @@ int udhcpc6_main(int argc UNUSED_PARAM, char **argv)
timeout = 61;
/* enter bound state */
d6_run_script(packet.d6_options, packet_end,
(state == REQUESTING ? "bound" : "renew"));
(client_data.state == REQUESTING ? "bound" : "renew"));
state = BOUND;
client_data.state = BOUND;
change_listen_mode(LISTEN_NONE);
if (opt & OPT_q) { /* quit after lease */
goto ret0;
@@ -1776,7 +1777,7 @@ int udhcpc6_main(int argc UNUSED_PARAM, char **argv)
perform_d6_release(&srv6_buf, requested_ipv6);
retval = 0;
ret:
/*if (client_config.pidfile) - remove_pidfile has its own check */
remove_pidfile(client_config.pidfile);
/*if (client_data.pidfile) - remove_pidfile has its own check */
remove_pidfile(client_data.pidfile);
return retval;
}
+2 -2
View File
@@ -17,7 +17,7 @@ void FAST_FUNC d6_dump_packet(struct d6_packet *packet)
if (dhcp_verbose < 2)
return;
bb_error_msg(
bb_info_msg(
" xid %x"
, packet->d6_xid32
);
@@ -40,7 +40,7 @@ int FAST_FUNC d6_recv_kernel_packet(struct in6_addr *peer_ipv6
}
if (bytes < offsetof(struct d6_packet, d6_options)) {
bb_error_msg("packet with bad magic, ignoring");
bb_info_msg("packet with bad magic, ignoring");
return -2;
}
log1("received %s", "a packet");
Loaded 100 of 159 files, more files were not shown because too many files have changed in this diff. Show more