Compare commits

..
Author SHA1 Message Date
Denys Vlasenko 1dd2685dcc Bump version to 1.30.1
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-02-14 15:25:41 +01:00
Rostislav Skudnov c199472e3a 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-14 14:40:57 +01:00
Denys Vlasenko d7a622b572 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-14 14:40:57 +01:00
Ari Sundholm 256ee62224 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-02-14 14:40:57 +01:00
Denys Vlasenko 5c6b9165e7 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-02-14 14:40:57 +01:00
Bernhard Reutner-Fischer 8296334c1f 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-02-14 14:40:57 +01:00
Denys Vlasenko 7f8f20714a ip link: fix mismatched enums in vlan_parse_opt(), closes 11631
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-02-14 14:40:57 +01:00
Brian Foley b65db51ac1 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-02-14 14:40:57 +01:00
Mark Marshall fa86b27e24 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-02-14 14:40:57 +01:00
Denys Vlasenko b570954363 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-02-14 14:40:57 +01:00
Denys Vlasenko c28dc0b58b 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-02-14 14:40:57 +01:00
Denys Vlasenko 60fb586597 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-02-14 14:40:57 +01:00
Denys Vlasenko 715273a992 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-02-14 14:40:57 +01:00
Martijn Dekker a89ec68a8a 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-02-14 14:40:57 +01:00
Denys Vlasenko 5cea086bbf 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-02-14 14:40:57 +01:00
Denys Vlasenko 9c36a02f4d bc: formatting changes, added a FIXME comment, no logic changes
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-02-14 14:40:57 +01:00
Denys Vlasenko 5b35d599e8 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-02-14 14:40:57 +01:00
Denys Vlasenko c7679c759a 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-02-14 14:40:57 +01:00
Denys Vlasenko d2651fb775 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-02-14 14:40:57 +01:00
Denys Vlasenko fb001145e1 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-02-14 14:40:57 +01:00
Denys Vlasenko ef2e6a8062 bc: add a palceholder comment for "void" return
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-02-14 14:40:57 +01:00
Denys Vlasenko f40467d369 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-02-14 14:40:57 +01:00
Denys Vlasenko 56e09e93bd 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-02-14 14:40:57 +01:00
Denys Vlasenko 18351b4a89 bc: make error line number also size_t, like everything else
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-02-14 14:40:57 +01:00
Denys Vlasenko a8ec556458 bc: generate large bc tests on the fly, -5 mbytes in the git tree
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-02-14 14:40:57 +01:00
Denys Vlasenko 7dd6ba12f7 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-02-14 14:40:57 +01:00
Denys Vlasenko f23c04af2d 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-02-14 14:40:57 +01:00
Denys Vlasenko c3de036da9 bc: in xc_read_line(), check ^C on NUL input bytes too
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-02-14 14:40:57 +01:00
Denys Vlasenko 2123ceed18 bc: remove superfluous assigment
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2019-02-14 14:40:57 +01:00
Denys Vlasenko 8a7411fcc8 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>
2019-02-14 14:40:57 +01:00
Denys Vlasenko 07c8b240d5 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>
2019-02-14 14:40:57 +01:00
150 changed files with 4755 additions and 6191 deletions

No files matched your search

+1 -10
View File
@@ -12,7 +12,7 @@ config HAVE_DOT_CONFIG
menu "Settings"
config DESKTOP
bool "Enable compatibility for full-blown desktop systems (8kb)"
bool "Enable compatibility for full-blown desktop systems"
default y
help
Enable applet options and features which are not essential.
@@ -339,15 +339,6 @@ 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
+1 -1
View File
@@ -1,5 +1,5 @@
VERSION = 1
PATCHLEVEL = 31
PATCHLEVEL = 30
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];
+1 -19
View File
@@ -96,24 +96,6 @@ 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;
}
@@ -146,7 +128,7 @@ unpack_xz_stream(transformer_state_t *xstate)
break;
}
}
end:
xz_dec_end(state);
free(membuf);
+17 -27
View File
@@ -159,44 +159,47 @@ 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. */
xstate->signature_skipped = 2;
xread(fd, xstate->magic.b16, 2);
xread(fd, magic.b16, sizeof(magic.b16[0]));
if (ENABLE_FEATURE_SEAMLESS_GZ
&& xstate->magic.b16[0] == GZIP_MAGIC
&& 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
&& xstate->magic.b16[0] == COMPRESS_MAGIC
&& 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
&& xstate->magic.b16[0] == BZIP2_MAGIC
&& 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
&& xstate->magic.b16[0] == XZ_MAGIC1
&& magic.b16[0] == XZ_MAGIC1
) {
uint32_t v32;
xstate->signature_skipped = 6;
xread(fd, &xstate->magic.b16[1], 4);
move_from_unaligned32(v32, &xstate->magic.b16[1]);
if (v32 == XZ_MAGIC2) {
xread(fd, magic.b32, sizeof(magic.b32[0]));
if (magic.b32[0] == XZ_MAGIC2) {
xstate->xformer = unpack_xz_stream;
USE_FOR_NOMMU(xstate->xformer_prog = "unxz";)
goto found_magic;
@@ -341,24 +344,11 @@ 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.
* 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
);
/* File is not compressed */
//FIXME: avoid seek
xlseek(xstate->src_fd, - xstate->signature_skipped, SEEK_CUR);
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 "\375""7zXZ"
#define HEADER_MAGIC "\3757zXZ"
#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' and 'date -s DATE' support
//config: With this option off, 'date DATE' is '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 (strptime format) for -d TIME conversion"
//usage: "\n -D FMT Use FMT for -d TIME conversion"
//usage: )
//usage: "\n"
//usage: "\nRecognized TIME formats:"
+19 -23
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|append]"
//usage: " [iflag=skip_bytes|fullblock] [oflag=seek_bytes]"
//usage: )
//usage:#define dd_full_usage "\n\n"
//usage: "Copy a file with converting and formatting\n"
@@ -84,7 +84,6 @@
//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"
@@ -141,12 +140,11 @@ 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 << 9) * ENABLE_FEATURE_DD_IBS_OBS,
FLAG_COUNT = 1 << 10,
FLAG_STATUS_NONE = 1 << 11,
FLAG_STATUS_NOXFER = 1 << 12,
FLAG_TWOBUFS = (1 << 8) * ENABLE_FEATURE_DD_IBS_OBS,
FLAG_COUNT = 1 << 9,
FLAG_STATUS_NONE = 1 << 10,
FLAG_STATUS_NOXFER = 1 << 11,
};
static void dd_output_status(int UNUSED_PARAM cur_signal)
@@ -192,15 +190,23 @@ 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;
n = full_write(ofd, buf, len);
ssize_t n = full_write_or_warn(buf, len, filename);
if (n < 0)
return 1;
#if ENABLE_FEATURE_DD_THIRD_STATUS_LINE
if (n > 0)
G.total_bytes += n;
G.total_bytes += n;
#endif
if ((size_t)n == obs) {
G.out_full++;
@@ -210,14 +216,6 @@ 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;
}
@@ -269,7 +267,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\0append\0";
"seek_bytes\0";
#endif
#if ENABLE_FEATURE_DD_STATUS
static const char status_words[] ALIGN1 =
@@ -453,8 +451,6 @@ 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");
+7 -36
View File
@@ -63,62 +63,33 @@ 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;
for (;;) {
char *line;
while ((line = xmalloc_fgets(file)) != NULL) {
unsigned char c;
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;
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;
}
while ((c = *ptr) != '\0') {
if ((opt & OPT_INITIAL) && !isblank(c)) {
/* not space or tab */
break;
}
if (c == '\t') {
unsigned len = 0; //
unsigned len;
*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
@@ -0,0 +1,60 @@
/* 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 Treat LINK as a file, not DIR"
//usage: "\n -T 2nd arg must be a DIR"
//usage: "\n -v Verbose"
//usage:
//usage:#define ln_example_usage
+1 -1
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"
IF_FEATURE_LS_COLOR("color\0" Optional_argument "\xfd")
"color\0" Optional_argument "\xfd"
;
#endif
-5
View File
@@ -68,11 +68,6 @@ 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 */
+44 -48
View File
@@ -169,42 +169,6 @@ 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)
@@ -212,22 +176,54 @@ FS_TYPE(0x62656572, "sysfs")
*/
static const char *human_fstype(uint32_t f_type)
{
# define FS_TYPE(type, name) type,
static const uint32_t fstype[] = {
FS_TYPE_LIST
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" }
};
# 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; i < ARRAY_SIZE(fstype); ++i)
if (fstype[i] == f_type)
for (i = 0; humantypes[i].type; ++i)
if (humantypes[i].type == f_type)
break;
return nth_string(humanname, i);
return humantypes[i].fs;
}
/* "man statfs" says that statfsbuf->f_fsid is a mess */
+12 -6
View File
@@ -5,7 +5,18 @@
*
* Licensed under GPLv2 or later, see file LICENSE in this source tree.
*/
/* David MacKenzie <djm@gnu.ai.mit.edu>
/* 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>
*
* Special for busybox ported by Vladimir Oleynik <dzo@simtreas.ru> 2001
*/
@@ -29,11 +40,6 @@
//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"
+32 -70
View File
@@ -20,7 +20,6 @@
//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
@@ -43,98 +42,61 @@
/* This is a NOFORK applet. Be very careful! */
#if ENABLE_FEATURE_SYNC_FANCY || ENABLE_FSYNC
static int sync_common(int opts, char **argv)
int sync_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
int sync_main(int argc UNUSED_PARAM, char **argv IF_NOT_DESKTOP(UNUSED_PARAM))
{
int ret;
#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;
enum {
OPT_DATASYNC = (1 << 0),
OPT_SYNCFS = (1 << 1),
};
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 */
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);
if (fd < 0) {
ret = EXIT_FAILURE;
goto next;
}
# if ENABLE_FEATURE_SYNC_FANCY
if (opts & OPT_DATASYNC) {
if (fdatasync(fd))
goto err;
goto do_close;
}
if (opts & OPT_SYNCFS) {
/*
* syncfs is documented to only fail with EBADF,
* which can't happen here. So, no error checks.
*/
syncfs(fd);
} else
# endif
if (((opts & OPT_DATASYNC) ? fdatasync(fd) : fsync(fd)) != 0) {
goto do_close;
}
if (fsync(fd)) {
err:
bb_simple_perror_msg(*argv);
ret = EXIT_FAILURE;
}
do_close:
close(fd);
next:
argv++;
} while (*argv);
++argv;
}
return ret;
}
#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
+32 -62
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 in /proc/PID/cmdline"
//usage: "\n command 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 = NULL;
char *startas;
char *chuid;
#if ENABLE_FEATURE_START_STOP_DAEMON_FANCY
// char *retry_arg = NULL;
@@ -425,11 +425,10 @@ 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 */
//WRONG: "start-stop-daemon -S -- sleep 5" is a valid invocation
/* -xa (at least one) is required if -S is given */
/* -q turns off -v */
"\0"
"K:S:K--S:S--K:m?p:K?xpun"
"K:S:K--S:S--K:m?p:K?xpun:S?xa"
IF_FEATURE_START_STOP_DAEMON_FANCY("q-v"),
LONGOPTS
&startas, &cmdname, &signame, &userspec, &chuid, &execname, &pidfile
@@ -443,43 +442,27 @@ int start_stop_daemon_main(int argc UNUSED_PARAM, char **argv)
if (signal_nr < 0) bb_show_usage();
}
//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 (!(opt & OPT_a))
startas = execname;
if (!execname) /* in case -a is given and -x is not */
execname = 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();
@@ -488,11 +471,9 @@ 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", execname);
printf("%s is already running\n%u\n", execname, (unsigned)G.found_procs->pid);
return !(opt & OPT_OKNODO);
}
@@ -501,51 +482,35 @@ 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);
/* 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 */
#endif
}
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);
@@ -560,10 +525,15 @@ int start_stop_daemon_main(int argc UNUSED_PARAM, char **argv)
setgroups(1, &ugid.gid);
}
}
/* 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);
#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);
bb_perror_msg_and_die("can't execute '%s'", startas);
}
-1
View File
@@ -183,7 +183,6 @@ dd compatibility options:
iflag=skip_bytes| yes | |
iflag=fullblock | yes | |
oflag=seek_bytes| yes | |
oflag=append | yes | |
df POSIX options
option | exists | compliant | remarks
+10 -31
View File
@@ -275,21 +275,18 @@ 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_REQUIRED 0x400000
#define OF_RES1 0x010000
#define OF_RES2 0x020000
#define OF_STR1 0x040000
#define OF_STR2 0x080000
#define OF_NUM1 0x100000
#define OF_CHECKED 0x200000
/* 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)
@@ -428,7 +425,7 @@ static const uint32_t tokeninfo[] = {
0,
0, /* \n */
ST_IF, ST_DO, ST_FOR, OC_BREAK,
OC_CONTINUE, OC_DELETE|Rx, OC_PRINT,
OC_CONTINUE, OC_DELETE|Vx, OC_PRINT,
OC_PRINTF, OC_NEXT, OC_NEXTFILE,
OC_RETURN|Vx, OC_EXIT|Nx,
ST_WHILE,
@@ -596,7 +593,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";
static const char EMSG_TOO_FEW_ARGS[] ALIGN1 = "Too few arguments for builtin";
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";
@@ -1268,7 +1265,7 @@ static node *parse_expr(uint32_t iexp)
debug_printf_parse("%s(%x)\n", __func__, iexp);
sn.info = PRIMASK;
sn.r.n = sn.a.n = glptr = NULL;
sn.r.n = glptr = NULL;
xtc = TC_OPERAND | TC_UOPPRE | TC_REGEXP | iexp;
while (!((tc = next_token(xtc)) & iexp)) {
@@ -1290,7 +1287,6 @@ 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);
@@ -1429,11 +1425,7 @@ 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();
}
@@ -1613,25 +1605,12 @@ static void parse_program(char *p)
f = newfunc(t_string);
f->body.first = NULL;
f->nargs = 0;
/* 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);
while (next_token(TC_VARIABLE | TC_SEQTERM) & TC_VARIABLE) {
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();
+15 -17
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)
{
const char *start;
const char *eol;
int start = 0, idx, hack = 0;
/* Skip whitespace, then grab filename to end of line */
start = skip_whitespace(filecmdstr);
eol = strchrnul(start, '\n');
if (eol == start)
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)
bb_error_msg_and_die("empty filename");
*retval = xstrndup(filecmdstr+start, idx-start+hack+1);
if (hack)
(*retval)[idx-start] = '\\';
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;
return idx;
}
static int parse_subst_cmd(sed_cmd_t *sed_cmd, const char *substr)
@@ -1097,8 +1097,6 @@ 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: */
+2235 -2108
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 does not guarantee writes to complete
writeout=0 # increase if your kernel doesn ot guarantee writes to complete
# No /usr - we are expecting all binaries to be accessible
# from root fs alone
-4
View File
@@ -55,10 +55,6 @@ 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"
+38 -49
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,14 +52,9 @@ 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 optional_hostname
#static_lease 00:60:08:11:CE:3E 192.168.0.44
# 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
@@ -79,49 +74,43 @@ option staticroutes 10.0.0.0/8 10.127.0.1, 10.11.12.0/24 10.11.12.1
option 0x08 01020304 # option 8: "cookie server IP addr: 1.2.3.4"
option 14 "dumpfile"
# Currently supported options [hex option value] (for more info, see 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
# 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
# Options specifying server(s)
#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]
#opt dns IP_LIST
#opt wins IP_LIST
#opt nissrv IP_LIST
#opt ntpsrv IP_LIST
#opt lprsrv IP_LIST
#opt swapsrv IP
# Options specifying routes
#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
#opt routes IP_PAIR_LIST
#opt staticroutes STATIC_ROUTES # RFC 3442 classless static route option
#opt msstaticroutes STATIC_ROUTES # same, using MS option number
# Obsolete options, no longer supported
#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
#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
# TODO: in development
#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
#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
@@ -26,30 +26,6 @@ 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 || exec sleep 5
ip link set dev "$if" up
echo "* Starting udhcpc on $if [$$]"
echo "* Starting udhcpc"
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 || exec sleep 5
ip link set dev $if up
>>udhcpd.leases
sed 's/^interface.*$/interface '"$if/" -i udhcpd.conf
echo "* Starting udhcpd on $if [$$]"
echo "* Starting udhcpd"
exec \
env - PATH="$PATH" \
softlimit \
+2 -3
View File
@@ -9,14 +9,14 @@ pwd="$PWD"
if="${PWD##*/ifplugd_}"
echo "* Upping iface $if"
ip link set dev "$if" up || exec sleep 5
ip link set dev "$if" up
echo "* Starting ifplugd on $if [$$]"
exec \
env - PATH="$PATH" \
softlimit \
setuidgid root \
ifplugd -aqlMns -t3 -u8 -d8 -i "$if" -r "$pwd/ifplugd_handler"
ifplugd -aqlns -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,7 +29,6 @@ ifplugd -aqlMns -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
+2 -3
View File
@@ -8,13 +8,12 @@ pwd="$PWD"
if="${PWD##*/dhcp_}"
echo "* Upping iface $if"
# "or sleep" idiom prevents rapid respawning if iface does not exist
ip link set dev "$if" up || exec sleep 5
ip link set dev "$if" up
##echo "* Powersave disable on $if"
##iw dev "$if" set power_save off
echo "* Starting wpa_supplicant on $if [$$]"
echo "* Starting wpa_supplicant"
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 || exec sleep 5
ip link set dev "$if" up
echo "* Starting zcip on $if [$$]"
echo "* Starting zcip"
exec \
env - PATH="$PATH" \
softlimit \
-6
View File
@@ -1467,12 +1467,6 @@ 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;
}
+5 -14
View File
@@ -443,23 +443,15 @@ static int grep_file(FILE *file)
}
}
}
/* 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
}
/* If it's non-inverted search, we can stop
* at first match */
if (found && !invert_search)
goto do_found;
pattern_ptr = pattern_ptr->link;
} /* while (pattern_ptr) */
if (found ^ invert_search) {
//do_found:
do_found:
/* keep track of matches */
nmatches++;
@@ -560,7 +552,6 @@ 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: 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: "\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_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,12 +235,6 @@ 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;
+11 -33
View File
@@ -688,7 +688,6 @@ 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").
@@ -882,7 +881,6 @@ 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 */
@@ -1042,11 +1040,9 @@ 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;
@@ -1205,11 +1201,11 @@ void set_task_comm(const char *comm) FAST_FUNC;
* to /dev/null if they are not.
*/
enum {
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 */
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 */
};
#if BB_MMU
enum { re_execed = 0 };
@@ -1300,13 +1296,9 @@ 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
@@ -1318,6 +1310,7 @@ 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);
@@ -1337,14 +1330,6 @@ 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
*/
@@ -1356,7 +1341,7 @@ void bb_vinfo_msg(const char *s, va_list p) FAST_FUNC;
/* Embedded script support */
char *get_script_content(unsigned n) FAST_FUNC;
int scripted_main(int argc, char** argv) MAIN_EXTERNALLY_VISIBLE;
int scripted_main(int argc, char** argv);
/* Applets which are useful from another applets */
int bb_cat(char** argv) FAST_FUNC;
@@ -1461,19 +1446,17 @@ extern void bb_warn_ignoring_args(char *arg) FAST_FUNC;
extern int get_linux_version_code(void) 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;
extern char *query_loop(const char *device) FAST_FUNC;
extern 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
*/
int set_loop(char **devname, const char *file, unsigned long long offset, unsigned flags) FAST_FUNC;
extern 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;
@@ -1845,12 +1828,7 @@ struct smaprec {
unsigned long stack;
unsigned long smap_pss, smap_swap;
unsigned long smap_size;
// 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)
unsigned long smap_start;
char smap_mode[5];
char *smap_name;
};
+5 -6
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 link in printf! */
/* Imagine that this applet is "true". Dont suck in printf! */
const char *usage_string = unpack_usage_messages();
if (usage_string) {
if (*usage_string == '\b') {
full_write2_str("No help available\n");
full_write2_str("No help available.\n\n");
} else {
full_write2_str("Usage: "SINGLE_APPLET_STR" ");
full_write2_str(usage_string);
full_write2_str("\n");
full_write2_str("\n\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"); /* common string */
full_write2_str(" multi-call binary.\n");
if (*p == '\b')
full_write2_str("\nNo help available\n");
full_write2_str("\nNo help available.\n\n");
else {
full_write2_str("\nUsage: ");
full_write2_str(applet_name);
@@ -770,7 +770,6 @@ 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);
+5 -8
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 needlesly short reads.
* or else "copy to eof" code will use neddlesly short reads.
*/
#define SENDFILE_BIGBUF (16*1024*1024)
@@ -60,13 +60,10 @@ static off_t bb_full_fd_action(int src_fd, int dst_fd, off_t size)
ssize_t rd;
if (sendfile_sz) {
/* 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;
}
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
+2 -13
View File
@@ -56,22 +56,11 @@ struct mntent* FAST_FUNC find_mount_point(const char *name, int subdir_too)
continue;
/* Is device's dev_t == name's dev_t? */
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
) {
if (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);
+1 -2
View File
@@ -11,8 +11,7 @@
/*
* Write all of the supplied buffer out to a file.
* This does multiple writes as necessary.
* Returns the amount written, or -1 if error was seen
* on the very first write.
* Returns the amount written, or -1 on an error.
*/
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_FEATURE_CLEAN_UP
#if ENABLE_DU || ENABLE_FEATURE_CLEAN_UP
/* Clear statbuf hash table */
void FAST_FUNC reset_ino_dev_hashtable(void)
{
+3 -10
View File
@@ -70,20 +70,13 @@
#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
+6 -36
View File
@@ -78,24 +78,6 @@ 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
@@ -124,24 +106,12 @@ int FAST_FUNC set_loop(char **device, const char *file, unsigned long long offse
return -errno;
}
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:
//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);
//
/* 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);
@@ -200,7 +170,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); // actually, 0 param is unnecessary
ioctl(dfd, LOOP_CLR_FD, 0);
}
}
} else {
-18
View File
@@ -38,21 +38,3 @@ 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 long fast_strtoull_16(char **endptr)
static unsigned long fast_strtoul_16(char **endptr)
{
unsigned char c;
char *str = *endptr;
unsigned long long n = 0;
unsigned 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_strtoull_16(&tp);
currec.smap_size = (fast_strtoull_16(&tp) - currec.smap_start) >> 10;
currec.smap_start = fast_strtoul_16(&tp);
currec.smap_size = (fast_strtoul_16(&tp) - currec.smap_start) >> 10;
strncpy(currec.smap_mode, tp, sizeof(currec.smap_mode)-1);
+5 -7
View File
@@ -102,9 +102,10 @@ 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_with_initial_buf(int fd, size_t *maxsz_p, char *buf, size_t total)
void* FAST_FUNC xmalloc_read(int fd, size_t *maxsz_p)
{
size_t size, rd_size;
char *buf;
size_t size, rd_size, total;
size_t to_read;
struct stat st;
@@ -117,6 +118,8 @@ void* FAST_FUNC xmalloc_read_with_initial_buf(int fd, size_t *maxsz_p, char *buf
/* 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;
@@ -145,11 +148,6 @@ void* FAST_FUNC xmalloc_read_with_initial_buf(int fd, size_t *maxsz_p, char *buf
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
+1 -7
View File
@@ -270,16 +270,10 @@ 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,
time_days, cp);
(unsigned)(time(NULL)) / (24*60*60), cp);
} else {
/* "name:" + "new_passwd" + ":rest of line" */
fprintf(new_fp, "%s%s%s\n", name_colon, new_passwd, cp);
+2 -20
View File
@@ -12,7 +12,7 @@
#endif
#if ENABLE_FEATURE_SYSLOG
static smallint syslog_level = LOG_ERR;
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(syslog_level, "%s", msgc);
syslog(LOG_ERR, "%s", msgc);
}
# endif
free(msgc);
@@ -180,21 +180,3 @@ 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
+16 -17
View File
@@ -263,6 +263,12 @@ 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
@@ -272,15 +278,8 @@ void FAST_FUNC bb_daemonize_or_rexec(int flags, char **argv)
fd = xopen("/", O_RDONLY); /* don't believe this can fail */
}
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);
}
while ((unsigned)fd < 2)
fd = dup(fd); /* have 0,1,2 open at least to /dev/null */
if (!(flags & DAEMON_ONLY_SANITIZE)) {
@@ -293,14 +292,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,9 +11,6 @@
#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)
@@ -133,7 +130,6 @@ 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;
}
@@ -416,38 +412,6 @@ 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 = xstrdup(get_shell_name()); /* might come from getpwnam(), need to make a copy */
pw.pw_shell = (char *)get_shell_name();
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_info_msg("password for '%s' changed", name);
bb_error_msg("password for '%s' changed", name);
logmode = LOGMODE_STDIO;
free(name);
free(free_me);
+4 -6
View File
@@ -245,9 +245,7 @@ static void login_pam_end(pam_handle_t *pamh)
pam_strerror(pamh, pamret), pamret);
}
}
#else
# define login_pam_end(pamh) ((void)0)
#endif
#endif /* ENABLE_PAM */
static void get_username_or_die(char *buf, int size_buf)
{
@@ -473,7 +471,6 @@ 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);
@@ -531,10 +528,11 @@ int login_main(int argc UNUSED_PARAM, char **argv)
if (child_pid < 0)
bb_perror_msg("vfork");
else {
wait_for_exitstatus(child_pid);
if (safe_waitpid(child_pid, NULL, 0) == -1)
bb_perror_msg("waitpid");
update_utmp_DEAD_PROCESS(child_pid);
}
login_pam_end(pamh);
IF_PAM(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 = NULL;
char *orig = (char*)"";
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 malloced str */
orig = bb_ask_noecho_stdin("Old password: "); /* returns ptr to static */
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 malloced str */
newp = bb_ask_noecho_stdin("New password: "); /* returns ptr to static */
if (!newp)
goto err_ret;
if (ENABLE_FEATURE_PASSWD_WEAK_CHECK
&& obscure(orig, newp, pw) /* NB: passing NULL orig is ok */
&& obscure(orig, newp, pw)
&& 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_info_msg("password for %s changed by %s", name, myname);
bb_error_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_info_msg("normal startup");
bb_error_msg("normal startup");
return 0;
}
if (r > 0) {
break;
}
bb_do_delay(LOGIN_FAIL_DELAY);
bb_info_msg("Login incorrect");
bb_error_msg("Login incorrect");
}
bb_info_msg("starting shell for system maintenance");
bb_error_msg("starting shell for system maintenance");
IF_SELINUX(renew_current_security_context());
-10
View File
@@ -72,16 +72,6 @@ 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}
+8 -16
View File
@@ -997,12 +997,10 @@ static ERRORFUNC int bc_error_bad_character(char c)
IF_ERROR_RETURN_POSSIBLE(return) bc_error("NUL character");
IF_ERROR_RETURN_POSSIBLE(return) bc_error_fmt("bad character '%c'", c);
}
#if ENABLE_BC
static ERRORFUNC int bc_error_bad_function_definition(void)
{
IF_ERROR_RETURN_POSSIBLE(return) bc_error_at("bad function definition");
}
#endif
static ERRORFUNC int bc_error_bad_expression(void)
{
IF_ERROR_RETURN_POSSIBLE(return) bc_error_at("bad expression");
@@ -1275,12 +1273,14 @@ static int bc_map_insert(BcVec *v, const void *ptr, size_t *i)
return 1; // "was inserted"
}
#if ENABLE_BC
static size_t bc_map_find_exact(const BcVec *v, const void *ptr)
{
size_t i = bc_map_find_ge(v, ptr);
if (i >= v->len) return BC_VEC_INVALID_IDX;
return bc_id_cmp(ptr, bc_vec_item(v, i)) ? BC_VEC_INVALID_IDX : i;
}
#endif
static void bc_num_setToZero(BcNum *n, size_t scale)
{
@@ -4973,9 +4973,7 @@ static void dc_parse_string(void)
xc_parse_pushInst_and_Index(XC_INST_STR, len);
bc_vec_push(&G.prog.strs, &str);
// Add an empty function so that if zdc_program_execStr ever needs to
// parse the string into code (from the 'x' command) there's somewhere
// to store the bytecode.
// Explanation needed here
xc_program_add_fn();
p->func = xc_program_func(p->fidx);
@@ -5456,13 +5454,11 @@ static void xc_program_printString(const char *str)
char *n;
c = *str++;
n = strchr(esc, c); // note: if c is NUL, n = \0 at end of esc
if (!n || !c) {
n = strchr(esc, c); // note: c can be NUL
if (!n) {
// Just print the backslash and following character
bb_putchar('\\');
++G.prog.nchars;
// But if we're at the end of the string, stop
if (!c) break;
} else {
if (n - esc == 0) // "\n" ?
G.prog.nchars = SIZE_MAX;
@@ -6402,11 +6398,7 @@ static BC_STATUS zdc_program_asciify(void)
str = xzalloc(2);
str[0] = c;
//str[1] = '\0'; - already is
idx = bc_vec_push(&G.prog.strs, &str);
// Add an empty function so that if zdc_program_execStr ever needs to
// parse the string into code (from the 'x' command) there's somewhere
// to store the bytecode.
xc_program_add_fn();
bc_vec_push(&G.prog.strs, &str);
dup:
res.t = XC_RESULT_STR;
res.d.id.idx = idx;
@@ -6529,7 +6521,7 @@ static BC_STATUS zdc_program_execStr(char *code, size_t *bgn, bool cond)
if (s || !BC_PROG_STR(n)) goto exit;
sidx = n->rdx;
} else
goto exit_nopop;
goto exit;
}
fidx = sidx + BC_PROG_REQ_FUNCS;
@@ -6569,7 +6561,6 @@ static BC_STATUS zdc_program_execStr(char *code, size_t *bgn, bool cond)
RETURN_STATUS(BC_STATUS_SUCCESS);
exit:
bc_vec_pop(&G.prog.results);
exit_nopop:
RETURN_STATUS(s);
}
#define zdc_program_execStr(...) (zdc_program_execStr(__VA_ARGS__) COMMA_SUCCESS)
@@ -7511,3 +7502,4 @@ int dc_main(int argc UNUSED_PARAM, char **argv)
#endif
#endif // DC_BIG
+5 -3
View File
@@ -181,7 +181,9 @@ static void crondlog(unsigned level, const char *msg, va_list va)
* need not touch syslog_level
* (they are ok with LOG_ERR default).
*/
bb_vinfo_msg(msg, va);
syslog_level = LOG_INFO;
bb_verror_msg(msg, va, /* strerr: */ NULL);
syslog_level = LOG_ERR;
}
}
@@ -1054,7 +1056,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_std_path_and_ext("crond");
write_pidfile(CONFIG_PID_FILE_PATH "/crond.pid");
#if ENABLE_FEATURE_CROND_SPECIAL_TIMES
if (touch_reboot_file())
start_jobs(START_ME_REBOOT); /* start @reboot entries, if any */
@@ -1106,7 +1108,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_info_msg("time disparity of %ld minutes detected", dt / 60);
bb_error_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 */
+6 -21
View File
@@ -35,12 +35,10 @@ enum { STACK_SIZE = (COMMON_BUFSIZE - offsetof(struct globals, stack)) / sizeof(
base = 10; \
} while (0)
static unsigned check_under(void)
static void check_under(void)
{
unsigned p = pointer;
if (p == 0)
if (pointer == 0)
bb_error_msg_and_die("stack underflow");
return p - 1;
}
static void push(double a)
@@ -52,9 +50,8 @@ static void push(double a)
static double pop(void)
{
unsigned p = check_under();
pointer = p;
return stack[p];
check_under();
return stack[--pointer];
}
static void add(void)
@@ -94,19 +91,6 @@ 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);
}
@@ -187,7 +171,8 @@ static void print_stack_no_pop(void)
static void print_no_pop(void)
{
print_base(stack[check_under()]);
check_under();
print_base(stack[pointer-1]);
}
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_info_msg(fmt, ## args)
#define info_logger(p, fmt, args...) bb_error_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)
+1 -175
View File
@@ -36,26 +36,17 @@
//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:
@@ -89,19 +80,12 @@
#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 */
/*
@@ -278,7 +262,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 || ENABLE_I2CTRANSFER
#if ENABLE_I2CGET || ENABLE_I2CSET || ENABLE_I2CDUMP
static int i2c_parse_bus_addr(const char *addr_str)
{
/* Slave address must be in range 0x03 - 0x77. */
@@ -1389,161 +1373,3 @@ 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 */
+18 -15
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: "Display manual page\n"
//usage: "Format and display manual page\n"
//usage: "\n -a Display all pages"
//usage: "\n -w Show page locations"
//usage: "\n"
@@ -209,9 +209,8 @@ 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);
@@ -245,8 +244,10 @@ 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];
@@ -261,6 +262,16 @@ 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 */
@@ -274,7 +285,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.col , "col", token[1]);
G.col = if_redefined(G.tbl , "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]);
@@ -291,12 +302,6 @@ 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");
@@ -313,18 +318,16 @@ 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 */
const char *cur_sect = sec_list;
cur_sect = sec_list;
do { /* for each section */
char *next_sect = strchrnul(cur_sect, ':');
int sect_len = next_sect - cur_sect;
-84
View File
@@ -1,84 +0,0 @@
/* 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_std_path_and_ext("watchdog");
remove_pidfile(CONFIG_PID_FILE_PATH "/watchdog.pid");
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_std_path_and_ext("watchdog");
write_pidfile(CONFIG_PID_FILE_PATH "/watchdog.pid");
while (1) {
/*
+1 -4
View File
@@ -66,10 +66,7 @@ static void check_tainted(void)
}
}
#else
static ALWAYS_INLINE void check_tainted(void)
{
putchar('\n');
}
static void check_tainted(void) { putchar('\n'); }
#endif
int lsmod_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
+241 -259
View File
@@ -9,6 +9,9 @@
*
* 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
@@ -41,34 +44,29 @@
//kbuild:lib-$(CONFIG_BRCTL) += brctl.o
//usage:#define brctl_trivial_usage
//usage: "COMMAND [BRIDGE [ARGS]]"
//usage: "COMMAND [BRIDGE [INTERFACE]]"
//usage:#define brctl_full_usage "\n\n"
//usage: "Manage ethernet bridges"
//usage: "Manage ethernet bridges\n"
//usage: "\nCommands:"
//usage: IF_FEATURE_BRCTL_SHOW(
//usage: "\n show [BRIDGE]... Show bridges"
//usage: "\n show Show a list of 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 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 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 setbridgeprio BRIDGE PRIO Set bridge priority"
//usage: "\n setportprio BRIDGE IFACE PRIO Set port priority"
//usage: "\n setpathcost BRIDGE IFACE COST Set path cost"
//usage: "\n stp BRIDGE [1/yes/on|0/no/off] STP on/off"
//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>
@@ -85,119 +83,122 @@
# define SIOCBRDELIF BRCTL_DEL_IF
#endif
/* Maximum number of ports supported per bridge interface. */
#ifndef MAX_PORTS
# define MAX_PORTS 32
#endif
/* Use internal number parsing and not the "exact" conversion. */
/* #define BRCTL_USE_INTERNAL 0 */ /* use exact conversion */
#define BRCTL_USE_INTERNAL 1
#if ENABLE_FEATURE_BRCTL_FANCY
static unsigned str_to_jiffies(const char *time_str)
/* #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)
{
double dd;
double secs;
# if BRCTL_USE_INTERNAL
char *endptr;
dd = /*bb_*/strtod(time_str, &endptr);
if (endptr == time_str || dd < 0)
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");
dd *= 100;
/* For purposes of brctl,
* capping SECONDS by ~20 million seconds is quite enough:
*/
if (dd > INT_MAX)
dd = INT_MAX;
return dd;
tv->tv_sec = secs;
tv->tv_usec = 1000000 * (secs - tv->tv_sec);
}
#endif
#define filedata bb_common_bufsiz1
#if ENABLE_FEATURE_BRCTL_SHOW
static int read_file(const char *name)
static ALWAYS_INLINE unsigned long tv_to_jiffies(const struct timeval *tv)
{
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;
}
unsigned long long jif;
/* NB: we are in /sys/class/net
*/
static int show_bridge(const char *name, int need_hdr)
jif = 1000000ULL * tv->tv_sec + tv->tv_usec;
return jif/10000;
}
# if 0
static void jiffies_to_tv(struct timeval *tv, unsigned long jiffies)
{
/* 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;
unsigned long long tvusec;
#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;
tvusec = 10000ULL*jiffies;
tv->tv_sec = tvusec/1000000;
tv->tv_usec = tvusec - 1000000 * tv->tv_sec;
}
#endif
#if ENABLE_FEATURE_BRCTL_FANCY
static void write_uint(const char *name, const char *leaf, unsigned val)
# endif
static unsigned long str_to_jiffies(const char *time_str)
{
char pathbuf[IFNAMSIZ + sizeof("/bridge/bridge_id") + 32];
int fd, n;
struct timeval tv;
bb_strtotimeval(&tv, time_str);
return tv_to_jiffies(&tv);
}
#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);
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;
}
#endif
int brctl_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
int brctl_main(int argc UNUSED_PARAM, char **argv)
{
@@ -206,71 +207,90 @@ 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++;
if (!*argv) {
/* bare "brctl" shows --help */
bb_show_usage();
}
xchdir("/sys/class/net");
// while (*argv)
{
smallint key;
char *br;
while (*argv) {
#if ENABLE_FEATURE_BRCTL_FANCY
int ifidx[MAX_PORTS];
unsigned long args[4];
ifr.ifr_data = (char *) &args;
#endif
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 [BR]... */
DIR *net;
struct dirent *ent;
int need_hdr = 1;
int exitcode = EXIT_SUCCESS;
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 (*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;
}
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);
/* "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;
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 (ENABLE_FEATURE_CLEAN_UP)
closedir(net);
return exitcode;
goto done;
}
#endif
@@ -279,29 +299,28 @@ int brctl_main(int argc UNUSED_PARAM, char **argv)
br = *argv++;
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);
if (key == ARG_addbr || key == ARG_delbr) { /* addbr or delbr */
ioctl_or_perror_and_die(fd,
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;
key == ARG_addbr ? SIOCBRADDBR : SIOCBRDELBR,
br, "bridge %s", br);
goto done;
}
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 =
@@ -311,102 +330,65 @@ 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;
write_uint(br, "bridge/stp_state", onoff);
//goto done_next_argv;
return EXIT_SUCCESS;
arm_ioctl(args, BRCTL_SET_BRIDGE_STP_STATE, onoff, 0);
goto fire;
}
if ((unsigned)(key - ARG_setageing) < 4) { /* time related ops */
/* 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;
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;
}
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
) {
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;
}
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;
/* 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
/* always true: if (key == ARG_addif || key == ARG_delif) */ {
/* addif or delif */
struct ifreq ifr;
int fd = xsocket(AF_INET, SOCK_STREAM, 0);
if (key != ARG_setbridgeprio) {
/* get portnum */
unsigned i;
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);
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;
}
}
}
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;
arg1 = port;
arg2 = xatoi_positive(*argv);
if (key == ARG_setbridgeprio) {
arg1 = arg2;
arg2 = 0;
}
arm_ioctl(args, ops[key - ARG_setpathcost], arg1, arg2);
}
// done_next_argv:
// argv++;
// done:
fire:
/* Execute the previously set command */
xioctl(fd, SIOCDEVPRIVATE, &ifr);
#endif
done_next_argv:
argv++;
done:
close(fd);
}
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_info_msg("name:%s, ip:%s", token[0], token[1]);
bb_error_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_info_msg("'%s'->'%s'", query_string, answstr);
bb_error_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_info_msg("returning positive reply");
bb_error_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_info_msg("accepting UDP packets on %s", p);
bb_error_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_info_msg("got UDP packet");
bb_error_msg("got UDP packet");
buf[r] = '\0'; /* paranoia */
r = process_packet(conf_data, conf_ttl, buf);
if (r <= 0)
+271 -313
View File
@@ -95,7 +95,9 @@
* 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
@@ -244,8 +246,6 @@
//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,11 +259,17 @@
#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
#define MAX_HTTP_HEADERS_SIZE (32*1024)
#if PIPE_BUF >= IOBUF_SIZE
# error "PIPE_BUF >= IOBUF_SIZE"
#endif
#define HEADER_READ_TIMEOUT 60
@@ -299,13 +305,6 @@ 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,
@@ -317,7 +316,6 @@ 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,
@@ -349,7 +347,6 @@ 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,
@@ -380,7 +377,6 @@ 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" },
@@ -400,11 +396,12 @@ 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;
char *g_query;
const char *g_query;
const char *opt_c_configFile;
const char *home_httpd;
const char *index_page;
@@ -415,6 +412,11 @@ 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
@@ -450,6 +452,7 @@ 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 )
@@ -1143,61 +1146,18 @@ 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"
/* 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",
"%s-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");
@@ -1234,39 +1194,37 @@ 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 unsigned get_line(void)
static int get_line(void)
{
unsigned count;
int count = 0;
char c;
count = 0;
alarm(HEADER_READ_TIMEOUT);
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)
goto ret;
break;
hdr_ptr = hdr_buf;
}
iobuf[count] = c = *hdr_ptr++;
hdr_cnt--;
c = *hdr_ptr++;
if (c == '\r')
continue;
if (c == '\n')
if (c == '\n') {
iobuf[count] = '\0';
break;
iobuf[count] = c;
}
if (count < (IOBUF_SIZE - 1)) /* check overflow */
count++;
}
ret:
iobuf[count] = '\0';
return count;
}
@@ -1406,10 +1364,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, IOBUF_SIZE - 8);
count = safe_read(fromCgi_rd, rbuf + out_cnt, PIPE_BUF - 8);
if (count <= 0) {
/* eof (or error) and there was no "HTTP",
* send "HTTP/1.0 200 OK\r\n", then send received data */
* so write it, then write received data */
if (out_cnt) {
full_write(STDOUT_FILENO, HTTP_200, sizeof(HTTP_200)-1);
full_write(STDOUT_FILENO, rbuf, out_cnt);
@@ -1447,7 +1405,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, IOBUF_SIZE);
count = safe_read(fromCgi_rd, rbuf, PIPE_BUF);
if (count <= 0)
break; /* eof (or error) */
}
@@ -1479,17 +1437,23 @@ 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) NORETURN;
int post_len,
const char *cookie,
const char *content_type) NORETURN;
static void send_cgi_and_exit(
const char *url,
const char *orig_uri,
const char *request,
int post_len)
int post_len,
const char *cookie,
const char *content_type)
{
struct fd_pair fromCgi; /* CGI -> httpd pipe */
struct fd_pair toCgi; /* httpd -> CGI pipe */
@@ -1567,14 +1531,26 @@ 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 */
@@ -1726,10 +1702,8 @@ 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"
@@ -1843,7 +1817,7 @@ static NOINLINE void send_file_and_exit(const char *url, int what)
log_and_exit();
}
static void if_ip_denied_send_HTTP_FORBIDDEN_and_exit(unsigned remote_ip)
static int checkPermIP(void)
{
Htaccess_IP *cur;
@@ -1862,15 +1836,11 @@ static void if_ip_denied_send_HTTP_FORBIDDEN_and_exit(unsigned remote_ip)
(unsigned char)(cur->mask)
);
#endif
if ((remote_ip & cur->mask) == cur->ip) {
if (cur->allow_deny == 'A')
return;
send_headers_and_exit(HTTP_FORBIDDEN);
}
if ((rmt_ip & cur->mask) == cur->ip)
return (cur->allow_deny == 'A'); /* A -> 1 */
}
if (flg_deny_all) /* depends on whether we saw "D:*" */
send_headers_and_exit(HTTP_FORBIDDEN);
return !flg_deny_all; /* depends on whether we saw "D:*" */
}
#if ENABLE_FEATURE_HTTPD_BASIC_AUTH
@@ -2107,15 +2077,12 @@ 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;
@@ -2123,22 +2090,29 @@ static void handle_incoming_and_exit(const len_and_sockaddr *fromAddr)
#if ENABLE_FEATURE_HTTPD_BASIC_AUTH
smallint authorized = -1;
#endif
char *HTTP_slash;
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
/* Allocation of iobuf is postponed until now
* (IOW, server process doesn't need to waste 8k) */
iobuf = xmalloc(IOBUF_SIZE);
remote_ip = 0;
rmt_ip = 0;
if (fromAddr->u.sa.sa_family == AF_INET) {
remote_ip = ntohl(fromAddr->u.sin.sin_addr.s_addr);
rmt_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)
remote_ip = ntohl(fromAddr->u.sin6.sin6_addr.s6_addr32[3]);
rmt_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?) */
@@ -2151,7 +2125,6 @@ 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);
@@ -2185,59 +2158,31 @@ 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 */
HTTP_slash = strchr(urlp, ' ');
/* 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, ' ');
/* Is it " HTTP/"? */
if (!HTTP_slash || strncmp(HTTP_slash + 1, HTTP_200, 5) != 0)
send_headers_and_exit(HTTP_BAD_REQUEST);
*HTTP_slash++ = '\0';
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';
/* Copy URL from after "GET "/"POST " to stack-allocated char[] */
urlcopy = alloca((HTTP_slash - urlp) + 2 + strlen(index_page));
urlcopy = alloca((tptr - 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 */
#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';
/* g_query = NULL; - already is */
tptr = strchr(urlcopy, '?');
if (tptr) {
*tptr++ = '\0';
g_query = tptr;
}
/* Decode URL escape sequences */
tptr = percent_decode_in_place(urlcopy, /*strict:*/ 1);
@@ -2277,7 +2222,7 @@ static void handle_incoming_and_exit(const len_and_sockaddr *fromAddr)
}
}
*++urlp = *tptr;
if (*tptr == '\0')
if (*urlp == '\0')
break;
next_char:
tptr++;
@@ -2295,17 +2240,193 @@ static void handle_incoming_and_exit(const len_and_sockaddr *fromAddr)
bb_error_msg("url:%s", urlcopy);
tptr = urlcopy;
while ((tptr = strchr(tptr + 1, '/')) != NULL) {
ip_allowed = checkPermIP();
while (ip_allowed && (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);
if_ip_denied_send_HTTP_FORBIDDEN_and_exit(remote_ip);
ip_allowed = checkPermIP();
}
*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
@@ -2314,7 +2435,7 @@ static void handle_incoming_and_exit(const len_and_sockaddr *fromAddr)
/* protect listing "cgi-bin/" */
send_headers_and_exit(HTTP_FORBIDDEN);
}
cgi_type = CGI_NORMAL;
send_cgi_and_exit(urlcopy, urlcopy, prequest, length, cookie, content_type);
}
#endif
@@ -2335,186 +2456,25 @@ 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) {
cgi_type = CGI_INTERPRETER;
break;
send_cgi_and_exit(urlcopy, urlcopy, prequest, length, cookie, content_type);
}
}
}
#endif
if (!found_moved_temporarily) {
file_size = sb.st_size;
last_mod = sb.st_mtime;
}
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) {
cgi_type = CGI_INDEX;
urlp[0] = '\0'; /* remove index_page */
send_cgi_and_exit("/cgi-bin/index.cgi", urlcopy, prequest, length, cookie, content_type);
}
}
#endif
urlp[0] = '\0';
/* else fall through to send_file, it errors out if open fails: */
#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);
@@ -2633,9 +2593,7 @@ 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 {
+19 -11
View File
@@ -326,7 +326,7 @@ static int run_script(const char *action)
char *argv[5];
int r;
bb_info_msg("executing '%s %s %s'", G.script_name, G.iface, action);
bb_error_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_info_msg("exit code: %d", r & 0xff);
bb_error_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_info_msg("upping interface");
bb_error_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_info_msg("using interface %s%s with driver<%s> (version: %s)",
bb_error_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_info_msg("using %s detection mode", method_table[i].name);
bb_error_msg("using %s detection mode", method_table[i].name);
break;
}
}
@@ -604,7 +604,15 @@ int ifplugd_main(int argc UNUSED_PARAM, char **argv)
xmove_fd(xsocket(AF_INET, SOCK_DGRAM, 0), ioctl_fd);
if (opts & FLAG_MONITOR) {
int fd = create_and_bind_to_netlink(NETLINK_ROUTE, RTMGRP_LINK, 0);
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));
xmove_fd(fd, netlink_fd);
}
@@ -624,7 +632,7 @@ int ifplugd_main(int argc UNUSED_PARAM, char **argv)
/* | (1 << SIGCHLD) - run_script does not use it anymore */
, record_signo);
bb_info_msg("started: %s", bb_banner);
bb_error_msg("started: %s", bb_banner);
if (opts & FLAG_MONITOR) {
struct ifreq ifrequest;
@@ -641,7 +649,7 @@ int ifplugd_main(int argc UNUSED_PARAM, char **argv)
iface_status_str = strstatus(iface_status);
if (opts & FLAG_MONITOR) {
bb_info_msg("interface %s",
bb_error_msg("interface %s",
G.iface_exists ? "exists"
: "doesn't exist, waiting");
}
@@ -649,7 +657,7 @@ int ifplugd_main(int argc UNUSED_PARAM, char **argv)
* by potentially lying that it really exists */
if (G.iface_exists) {
bb_info_msg("link is %s", iface_status_str);
bb_error_msg("link is %s", iface_status_str);
}
if ((!(opts & FLAG_NO_STARTUP)
@@ -704,7 +712,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_info_msg("interface %sappeared",
bb_error_msg("interface %sappeared",
G.iface_exists ? "" : "dis");
if (G.iface_exists)
maybe_up_new_iface();
@@ -722,7 +730,7 @@ int ifplugd_main(int argc UNUSED_PARAM, char **argv)
iface_status_str = strstatus(iface_status);
if (iface_status_old != iface_status) {
bb_info_msg("link is %s", iface_status_str);
bb_error_msg("link is %s", iface_status_str);
if (delay_time) {
/* link restored its old status before
+3 -9
View File
@@ -1177,15 +1177,8 @@ 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)) {
@@ -1199,7 +1192,8 @@ 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).
*/
sprintf(buf, "run-parts /etc/network/if-%s.d", opt);
buf = xasprintf("run-parts /etc/network/if-%s.d", opt);
/* heh, we don't bother free'ing it */
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_std_path_and_ext("inetd");
remove_pidfile(CONFIG_PID_FILE_PATH "/inetd.pid");
exit(EXIT_SUCCESS);
}
@@ -1256,7 +1256,7 @@ int inetd_main(int argc UNUSED_PARAM, char **argv)
setgroups(1, &gid);
}
write_pidfile_std_path_and_ext("inetd");
write_pidfile(CONFIG_PID_FILE_PATH "/inetd.pid");
/* never fails under Linux (except if you pass it bad arguments) */
getrlimit(RLIMIT_NOFILE, &rlim_ofile);
+8 -10
View File
@@ -23,7 +23,6 @@
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;
@@ -35,8 +34,6 @@ 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;
@@ -204,7 +201,7 @@ static NOINLINE int print_linkinfo(const struct nlmsghdr *n)
static int flush_update(void)
{
if (rtnl_send_check(G_filter.rth, G_filter.flushb, G_filter.flushp) < 0) {
if (rtnl_send(G_filter.rth, G_filter.flushb, G_filter.flushp) < 0) {
bb_perror_msg("can't send flush request");
return -1;
}
@@ -330,10 +327,6 @@ 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 ");
@@ -427,6 +420,7 @@ 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;
@@ -513,10 +507,14 @@ 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);
@@ -572,9 +570,9 @@ int FAST_FUNC ipaddr_list_or_flush(char **argv, int flush)
}
for (l = linfo; l; l = l->next) {
if ((oneline && G_filter.family != AF_PACKET)
if (no_link
|| (oneline || print_linkinfo(&l->h) == 0)
/* ^^^^^^^^^ "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)
+4 -5
View File
@@ -32,10 +32,7 @@ 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;
@@ -48,7 +45,7 @@ typedef struct filter_t filter_t;
static int flush_update(void)
{
if (rtnl_send_check(G_filter.rth, G_filter.flushb, G_filter.flushp) < 0) {
if (rtnl_send(G_filter.rth, G_filter.flushb, G_filter.flushp) < 0) {
bb_perror_msg("can't send flush request");
return -1;
}
@@ -302,7 +299,9 @@ static int FAST_FUNC ipneigh_list_or_flush(char **argv, int flush)
G_filter.rth = &rth;
while (round < MAX_ROUNDS) {
xrtnl_wilddump_request(&rth, G_filter.family, RTM_GETNEIGH);
if (xrtnl_wilddump_request(&rth, G_filter.family, RTM_GETNEIGH) < 0) {
bb_perror_msg_and_die("can't send dump request");
}
G_filter.flushed = 0;
if (xrtnl_dump_filter(&rth, print_neigh, NULL) < 0) {
bb_perror_msg_and_die("flush terminated");
+1 -4
View File
@@ -26,10 +26,7 @@
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;
@@ -56,7 +53,7 @@ typedef struct filter_t filter_t;
static int flush_update(void)
{
if (rtnl_send_check(G_filter.rth, G_filter.flushb, G_filter.flushp) < 0) {
if (rtnl_send(G_filter.rth, G_filter.flushb, G_filter.flushp) < 0) {
bb_perror_msg("can't send flush request");
return -1;
}
+8 -35
View File
@@ -34,7 +34,7 @@ void FAST_FUNC xrtnl_open(struct rtnl_handle *rth/*, unsigned subscriptions*/)
rth->seq = time(NULL);
}
void FAST_FUNC xrtnl_wilddump_request(struct rtnl_handle *rth, int family, int type)
int FAST_FUNC xrtnl_wilddump_request(struct rtnl_handle *rth, int family, int type)
{
struct {
struct nlmsghdr nlh;
@@ -48,45 +48,18 @@ void FAST_FUNC xrtnl_wilddump_request(struct rtnl_handle *rth, int family, int t
req.nlh.nlmsg_seq = rth->dump = ++rth->seq;
req.g.rtgen_family = family;
rtnl_send(rth, (void*)&req, sizeof(req));
return rtnl_send(rth, (void*)&req, sizeof(req));
}
/* 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)
//TODO: pass rth->fd instead of full rth?
int FAST_FUNC rtnl_send(struct rtnl_handle *rth, char *buf, int len)
{
struct nlmsghdr *h;
int status;
char resp[1024];
struct sockaddr_nl nladdr;
status = write(rth->fd, buf, len);
if (status < 0)
return status;
memset(&nladdr, 0, sizeof(nladdr));
nladdr.nl_family = AF_NETLINK;
/* 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;
return xsendto(rth->fd, buf, len, (struct sockaddr*)&nladdr, sizeof(nladdr));
}
int FAST_FUNC rtnl_dump_request(struct rtnl_handle *rth, int type, void *req, int len)
+2 -17
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 void xrtnl_wilddump_request(struct rtnl_handle *rth, int fam, int type) FAST_FUNC;
extern int 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,23 +34,8 @@ 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;
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));
extern int rtnl_send(struct rtnl_handle *rth, char *buf, int) FAST_FUNC;
// 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[] ALIGN2 = {
static const uint16_t llproto_ids[] = {
#define __PF(f,n) ETH_P_##f,
__PF(LOOP,loop)
__PF(PUP,pup)
+4 -8
View File
@@ -257,7 +257,7 @@ int nslookup_main(int argc, char **argv)
struct ns {
const char *name;
len_and_sockaddr *lsa;
//UNUSED: int failures;
int failures;
int replies;
};
@@ -320,7 +320,6 @@ 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 { \
@@ -594,7 +593,7 @@ static int send_queries(struct ns *ns)
/* Retry immediately on SERVFAIL */
if (rcode == 2) {
//UNUSED: ns->failures++;
ns->failures++;
if (servfail_retry) {
servfail_retry--;
write(pfd.fd, G.query[qn].query, G.query[qn].qlen);
@@ -613,12 +612,9 @@ 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++;
@@ -992,7 +988,7 @@ int nslookup_main(int argc UNUSED_PARAM, char **argv)
free(G.query);
}
return G.exitcode;
return EXIT_SUCCESS;
}
#endif
+10 -11
View File
@@ -177,11 +177,12 @@
*/
#define STEP_THRESHOLD 1
/* Slew threshold (sec): adjtimex() won't accept offsets larger than this.
* Using exact power of 2 (1/8, 1/2 etc) results in smaller code
* Using exact power of 2 (1/8) results in smaller code
*/
#define SLEW_THRESHOLD 0.5
// ^^^^ used to be 0.125.
// Since Linux 2.6.26 (circa 2006), kernel accepts (-0.5s, +0.5s) range
#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?
/* Stepout threshold (sec). std ntpd uses 900 (11 mins (!)) */
//UNUSED: #define WATCH_THRESHOLD 128
@@ -1130,7 +1131,7 @@ step_time(double offset)
}
tval = tvn.tv_sec;
strftime_YYYYMMDDHHMMSS(buf, sizeof(buf), &tval);
bb_info_msg("setting time to %s.%06u (offset %+fs)", buf, (unsigned)tvn.tv_usec, offset);
bb_error_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: */
@@ -2132,7 +2133,7 @@ recv_and_process_peer_pkt(peer_t *p)
p->reachable_bits |= 1;
if ((MAX_VERBOSE && G.verbose) || (option_mask32 & OPT_w)) {
bb_info_msg("reply from %s: offset:%+f delay:%f status:0x%02x strat:%d refid:0x%08x rootdelay:%f reach:0x%02x",
bb_error_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,
@@ -2585,10 +2586,6 @@ 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.
@@ -2645,6 +2642,8 @@ 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;
@@ -2816,7 +2815,7 @@ int ntpd_main(int argc UNUSED_PARAM, char **argv)
}
} /* while (!bb_got_signal) */
remove_pidfile_std_path_and_ext("ntpd");
remove_pidfile(CONFIG_PID_FILE_PATH "/ntpd.pid");
kill_myself_with_sig(bb_got_signal);
}
+2 -4
View File
@@ -124,8 +124,7 @@ 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;
@@ -144,8 +143,7 @@ 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;
+106 -97
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,10 +152,8 @@ static void subneg(byte c);
static void iac_flush(void)
{
if (G.iaclen != 0) {
full_write(netfd, G.iacbuf, G.iaclen);
G.iaclen = 0;
}
full_write(netfd, G.iacbuf, G.iaclen);
G.iaclen = 0;
}
static void doexit(int ev) NORETURN;
@@ -246,34 +244,25 @@ static void handle_net_output(int len)
static void handle_net_input(int len)
{
byte c;
int i;
int cstart = 0;
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 = 0; i < len; i++) {
byte c = G.buf[i];
for (; i < len; i++) {
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;
}
switch (G.telstate) {
case TS_CR:
@@ -289,19 +278,20 @@ 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 */
switch (c) {
case IAC: /* IAC IAC -> one IAC */
if (c == IAC) { /* IAC IAC -> one IAC */
G.buf[cstart++] = c;
G.telstate = TS_COPY;
break;
}
/* else */
switch (c) {
case SB:
G.telstate = TS_SUB1;
break;
@@ -330,83 +320,103 @@ static void handle_net_input(int 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);
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);
}
static void put_iac(int c)
{
int iaclen = G.iaclen;
if (iaclen >= IACBUFSIZE) {
G.iacbuf[G.iaclen++] = c;
}
static void put_iac2_merged(unsigned wwdd_and_c)
{
if (G.iaclen + 3 > IACBUFSIZE)
iac_flush();
iaclen = 0;
}
G.iacbuf[iaclen] = c; /* "... & 0xff" is implicit */
G.iaclen = iaclen + 1;
}
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);
put_iac(wwdd_and_c >> 8);
put_iac(wwdd_and_c & 0xff);
}
#define put_iac3_IAC_x_y(wwdd,c) put_iac3_IAC_x_y_merged(((wwdd)<<8) + (c))
#define put_iac2(wwdd,c) put_iac2_merged(((wwdd)<<8) + (c))
#if ENABLE_FEATURE_TELNET_TTYPE
static void put_iac_subopt(byte c, char *str)
{
put_iac4_x_y_z_t(IAC, SB, c, 0);
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);
while (*str)
put_iac(*str++);
put_iac2_x_y(IAC, SE);
put_iac(IAC);
put_iac(SE);
}
#endif
#if ENABLE_FEATURE_TELNET_AUTOLOGIN
static void put_iac_subopt_autologin(void)
{
const char *p;
int len = strlen(G.autologin) + 6; // (2 + 1 + 1 + strlen + 2)
const char *p = "USER";
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);
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);
p = G.autologin;
while (*p)
put_iac(*p++);
put_iac2_x_y(IAC, SE);
put_iac(IAC);
put_iac(SE);
}
#endif
#if ENABLE_FEATURE_TELNET_WIDTH
static void put_iac_naws(byte c, int x, int y)
{
put_iac3_IAC_x_y(SB, c);
if (G.iaclen + 9 > IACBUFSIZE)
iac_flush();
put_iac4_msb_lsb((x << 16) + y);
put_iac(IAC);
put_iac(SB);
put_iac(c);
put_iac2_x_y(IAC, SE);
/* "... & 0xff" implicitly done below */
put_iac(x >> 8);
put_iac(x);
put_iac(y >> 8);
put_iac(y);
put_iac(IAC);
put_iac(SE);
}
#endif
@@ -435,8 +445,8 @@ static void will_charmode(void)
G.telflags |= (UF_ECHO | UF_SGA);
setConMode();
put_iac3_IAC_x_y(DO, TELOPT_ECHO);
put_iac3_IAC_x_y(DO, TELOPT_SGA);
put_iac2(DO, TELOPT_ECHO);
put_iac2(DO, TELOPT_SGA);
iac_flush();
}
@@ -446,24 +456,24 @@ static void do_linemode(void)
G.telflags &= ~(UF_ECHO | UF_SGA);
setConMode();
put_iac3_IAC_x_y(DONT, TELOPT_ECHO);
put_iac3_IAC_x_y(DONT, TELOPT_SGA);
put_iac2(DONT, TELOPT_ECHO);
put_iac2(DONT, TELOPT_SGA);
iac_flush();
}
static void to_notsup(char c)
{
if (G.telwish == WILL)
put_iac3_IAC_x_y(DONT, c);
put_iac2(DONT, c);
else if (G.telwish == DO)
put_iac3_IAC_x_y(WONT, c);
put_iac2(WONT, c);
}
static void to_echo(void)
{
/* if server requests ECHO, don't agree */
if (G.telwish == DO) {
put_iac3_IAC_x_y(WONT, TELOPT_ECHO);
put_iac2(WONT, TELOPT_ECHO);
return;
}
if (G.telwish == DONT)
@@ -479,9 +489,9 @@ static void to_echo(void)
G.telflags ^= UF_ECHO;
if (G.telflags & UF_ECHO)
put_iac3_IAC_x_y(DO, TELOPT_ECHO);
put_iac2(DO, TELOPT_ECHO);
else
put_iac3_IAC_x_y(DONT, TELOPT_ECHO);
put_iac2(DONT, TELOPT_ECHO);
setConMode();
full_write1_str("\r\n"); /* sudden modec */
@@ -499,9 +509,9 @@ static void to_sga(void)
G.telflags ^= UF_SGA; /* toggle */
if (G.telflags & UF_SGA)
put_iac3_IAC_x_y(DO, TELOPT_SGA);
put_iac2(DO, TELOPT_SGA);
else
put_iac3_IAC_x_y(DONT, TELOPT_SGA);
put_iac2(DONT, TELOPT_SGA);
}
#if ENABLE_FEATURE_TELNET_TTYPE
@@ -509,9 +519,9 @@ static void to_ttype(void)
{
/* Tell server we will (or won't) do TTYPE */
if (G.ttype)
put_iac3_IAC_x_y(WILL, TELOPT_TTYPE);
put_iac2(WILL, TELOPT_TTYPE);
else
put_iac3_IAC_x_y(WONT, TELOPT_TTYPE);
put_iac2(WONT, TELOPT_TTYPE);
}
#endif
@@ -520,9 +530,9 @@ static void to_new_environ(void)
{
/* Tell server we will (or will not) do AUTOLOGIN */
if (G.autologin)
put_iac3_IAC_x_y(WILL, TELOPT_NEW_ENVIRON);
put_iac2(WILL, TELOPT_NEW_ENVIRON);
else
put_iac3_IAC_x_y(WONT, TELOPT_NEW_ENVIRON);
put_iac2(WONT, TELOPT_NEW_ENVIRON);
}
#endif
@@ -530,7 +540,7 @@ static void to_new_environ(void)
static void to_naws(void)
{
/* Tell server we will do NAWS */
put_iac3_IAC_x_y(WILL, TELOPT_NAWS);
put_iac2(WILL, TELOPT_NAWS);
}
#endif
@@ -639,7 +649,6 @@ 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);
+3 -29
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.
* IAC AYT (246) Are you there. Send back evidence that AYT was seen. TODO (send NOP back)?
* 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,18 +277,6 @@ 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 */
@@ -877,25 +865,11 @@ 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) {
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;
}
}
if (count < 0 && errno == EAGAIN)
goto skip4;
goto kill_session;
}
ts->size2 += count;
+3 -50
View File
@@ -31,11 +31,6 @@
//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
@@ -106,10 +101,9 @@
//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: "[-crl] [-u USER] [DIR]"
//usage: "[-cr] [-u USER] [DIR]"
//usage:#define tftpd_full_usage "\n\n"
//usage: "Transfer a file on tftp client's request\n"
//usage: "\n"
@@ -251,7 +245,7 @@ static int tftp_blksize_check(const char *blksize_str, int maxsize)
return -1;
}
# if ENABLE_TFTP_DEBUG
bb_info_msg("using blksize %u", blksize);
bb_error_msg("using blksize %u", blksize);
# endif
return blksize;
}
@@ -765,54 +759,15 @@ 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;
@@ -942,7 +897,6 @@ 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
@@ -990,8 +944,7 @@ 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)
);
+3 -11
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[] ALIGN1 = {
static const uint8_t OID_RSA_KEY_ALG[] = {
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[] ALIGN1 = {
static const uint8_t OID_ECDSA_KEY_ALG[] = {
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,17 +1531,9 @@ 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
@@ -2083,7 +2075,7 @@ static void send_client_key_exchange(tls_state_t *tls)
}
}
static const uint8_t rec_CHANGE_CIPHER_SPEC[] ALIGN1 = {
static const uint8_t rec_CHANGE_CIPHER_SPEC[] = {
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[] ALIGN1 = {
static const uint8_t Rcon[] = {
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
+11 -7
View File
@@ -43,13 +43,17 @@ typedef uint32_t word32;
#if 0 //UNUSED
static void fprime_copy(byte *x, const byte *a)
{
memcpy(x, a, F25519_SIZE);
int i;
for (i = 0; i < F25519_SIZE; i++)
x[i] = a[i];
}
#endif
static void lm_copy(byte* x, const byte* a)
{
memcpy(x, a, F25519_SIZE);
int i;
for (i = 0; i < F25519_SIZE; i++)
x[i] = a[i];
}
#if 0 //UNUSED
@@ -196,7 +200,7 @@ static void fe_load(byte *x, word32 c)
static void fe_normalize(byte *x)
{
byte minusp[F25519_SIZE];
unsigned c;
word16 c;
int i;
/* Reduce using 2^255 = 19 mod p */
@@ -215,13 +219,13 @@ static void fe_normalize(byte *x)
*/
c = 19;
for (i = 0; i < F25519_SIZE - 1; i++) {
for (i = 0; i + 1 < F25519_SIZE; i++) {
c += x[i];
minusp[i] = (byte)c;
c >>= 8;
}
c += ((unsigned)x[i]) - 128;
c += ((word16)x[i]) - 128;
minusp[31] = (byte)c;
/* Load x-p if no underflow */
@@ -230,13 +234,13 @@ static void fe_normalize(byte *x)
static void lm_add(byte* r, const byte* a, const byte* b)
{
unsigned c = 0;
word16 c = 0;
int i;
/* Add */
for (i = 0; i < F25519_SIZE; i++) {
c >>= 8;
c += ((unsigned)a[i]) + ((unsigned)b[i]);
c += ((word16)a[i]) + ((word16)b[i]);
r[i] = (byte)c;
}
+32 -77
View File
@@ -47,18 +47,13 @@
//#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
*/
#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)
int32 pstm_init_size(psPool_t *pool, pstm_int * a, uint32 size)
{
//bbox
// uint16 x;
@@ -80,17 +75,12 @@ int32 FAST_FUNC 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.
*/
#undef pstm_init
#define pstm_init(pool, a) \
pstm_init( a)
static int32 pstm_init(psPool_t *pool, pstm_int * a)
int32 pstm_init(psPool_t *pool, pstm_int * a)
{
//bbox
// int32 i;
@@ -116,15 +106,12 @@ static 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
*/
#undef pstm_grow
int32 FAST_FUNC pstm_grow(pstm_int * a, int size)
int32 pstm_grow(pstm_int * a, int size)
{
int i; //bbox: was int16
pstm_digit *tmp;
@@ -155,13 +142,11 @@ int32 FAST_FUNC 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;
@@ -210,7 +195,6 @@ 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)
/******************************************************************************/
/*
@@ -220,7 +204,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 FAST_FUNC pstm_clamp(pstm_int * a)
void pstm_clamp(pstm_int * a)
{
/* decrease used while the most significant digit is zero. */
while (a->used > 0 && a->dp[a->used - 1] == 0) {
@@ -236,7 +220,7 @@ void FAST_FUNC pstm_clamp(pstm_int * a)
/*
clear one (frees).
*/
void FAST_FUNC pstm_clear(pstm_int * a)
void pstm_clear(pstm_int * a)
{
int32 i;
/*
@@ -264,7 +248,6 @@ void FAST_FUNC 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)
@@ -289,13 +272,12 @@ void pstm_clear_multi(pstm_int *mp0, pstm_int *mp1, pstm_int *mp2,
}
}
}
#endif
/******************************************************************************/
/*
Set to zero.
*/
static void pstm_zero(pstm_int * a)
void pstm_zero(pstm_int * a)
{
int32 n;
pstm_digit *tmp;
@@ -314,7 +296,7 @@ static void pstm_zero(pstm_int * a)
/*
Compare maginitude of two ints (unsigned).
*/
int32 FAST_FUNC pstm_cmp_mag(pstm_int * a, pstm_int * b)
int32 pstm_cmp_mag(pstm_int * a, pstm_int * b)
{
int n; //bbox: was int16
pstm_digit *tmpa, *tmpb;
@@ -354,7 +336,7 @@ int32 FAST_FUNC pstm_cmp_mag(pstm_int * a, pstm_int * b)
/*
Compare two ints (signed)
*/
int32 FAST_FUNC pstm_cmp(pstm_int * a, pstm_int * b)
int32 pstm_cmp(pstm_int * a, pstm_int * b)
{
/*
compare based on sign
@@ -382,7 +364,7 @@ int32 FAST_FUNC 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 FAST_FUNC pstm_init_for_read_unsigned_bin(psPool_t *pool, pstm_int *a, uint32 len)
int32 pstm_init_for_read_unsigned_bin(psPool_t *pool, pstm_int *a, uint32 len)
{
int32 size;
/*
@@ -403,7 +385,7 @@ int32 FAST_FUNC pstm_init_for_read_unsigned_bin(psPool_t *pool, pstm_int *a, uin
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 FAST_FUNC pstm_read_unsigned_bin(pstm_int *a, unsigned char *b, int32 c)
int32 pstm_read_unsigned_bin(pstm_int *a, unsigned char *b, int32 c)
{
/* zero the int */
pstm_zero (a);
@@ -478,7 +460,7 @@ int32 FAST_FUNC pstm_read_unsigned_bin(pstm_int *a, unsigned char *b, int32 c)
/******************************************************************************/
/*
*/
static int pstm_count_bits(pstm_int * a)
int pstm_count_bits (pstm_int * a)
{
int r; //bbox: was int16
pstm_digit q;
@@ -500,14 +482,14 @@ static int pstm_count_bits(pstm_int * a)
}
/******************************************************************************/
int32 FAST_FUNC pstm_unsigned_bin_size(pstm_int *a)
int32 pstm_unsigned_bin_size(pstm_int *a)
{
int32 size = pstm_count_bits (a);
return (size / 8 + ((size & 7) != 0 ? 1 : 0));
}
/******************************************************************************/
static void pstm_set(pstm_int *a, pstm_digit b)
void pstm_set(pstm_int *a, pstm_digit b)
{
pstm_zero(a);
a->dp[0] = b;
@@ -518,7 +500,7 @@ static void pstm_set(pstm_int *a, pstm_digit b)
/*
Right shift
*/
static void pstm_rshd(pstm_int *a, int x)
void pstm_rshd(pstm_int *a, int x)
{
int y; //bbox: was int16
@@ -547,8 +529,7 @@ static void pstm_rshd(pstm_int *a, int x)
/*
Shift left a certain amount of digits.
*/
#undef pstm_lshd
static int32 pstm_lshd(pstm_int * a, int b)
int32 pstm_lshd(pstm_int * a, int b)
{
int x; //bbox: was int16
int32 res;
@@ -596,13 +577,12 @@ static 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
*/
static int32 pstm_2expt(pstm_int *a, int b)
int32 pstm_2expt(pstm_int *a, int b)
{
int z; //bbox: was int16
@@ -636,7 +616,7 @@ static int32 pstm_2expt(pstm_int *a, int b)
/*
*/
int32 FAST_FUNC pstm_mul_2(pstm_int * a, pstm_int * b)
int32 pstm_mul_2(pstm_int * a, pstm_int * b)
{
int32 res;
int x, oldused; //bbox: was int16
@@ -702,7 +682,7 @@ int32 FAST_FUNC pstm_mul_2(pstm_int * a, pstm_int * b)
/*
unsigned subtraction ||a|| >= ||b|| ALWAYS!
*/
int32 FAST_FUNC s_pstm_sub(pstm_int *a, pstm_int *b, pstm_int *c)
int32 s_pstm_sub(pstm_int *a, pstm_int *b, pstm_int *c)
{
int oldbused, oldused; //bbox: was int16
int32 x;
@@ -799,7 +779,7 @@ static int32 s_pstm_add(pstm_int *a, pstm_int *b, pstm_int *c)
/*
*/
int32 FAST_FUNC pstm_sub(pstm_int *a, pstm_int *b, pstm_int *c)
int32 pstm_sub(pstm_int *a, pstm_int *b, pstm_int *c)
{
int32 res;
int sa, sb; //bbox: was int16
@@ -844,7 +824,6 @@ int32 FAST_FUNC 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;
@@ -858,13 +837,12 @@ 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
*/
static int32 pstm_montgomery_setup(pstm_int *a, pstm_digit *rho)
int32 pstm_montgomery_setup(pstm_int *a, pstm_digit *rho)
{
pstm_digit x, b;
@@ -900,7 +878,7 @@ static 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.
*/
static int32 pstm_montgomery_calc_normalization(pstm_int *a, pstm_int *b)
int32 pstm_montgomery_calc_normalization(pstm_int *a, pstm_int *b)
{
int32 x;
int bits; //bbox: was int16
@@ -938,7 +916,6 @@ static 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;
@@ -979,13 +956,11 @@ 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
@@ -1016,15 +991,13 @@ 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
*/
#undef pstm_mul_d
static int32 pstm_mul_d(pstm_int *a, pstm_digit b, pstm_int *c)
int32 pstm_mul_d(pstm_int *a, pstm_digit b, pstm_int *c)
{
pstm_word w;
int32 res;
@@ -1054,16 +1027,12 @@ static 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
*/
#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,
int32 pstm_div_2d(psPool_t *pool, pstm_int *a, int b, pstm_int *c,
pstm_int *d)
{
pstm_digit D, r, rr;
@@ -1144,14 +1113,11 @@ 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
@@ -1195,16 +1161,12 @@ int32 pstm_div_2(pstm_int * a, pstm_int * b)
pstm_clamp (b);
return PSTM_OKAY;
}
#endif
/******************************************************************************/
/*
Creates "a" then copies b into it
*/
#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)
int32 pstm_init_copy(psPool_t *pool, pstm_int * a, pstm_int * b, int toSqr)
{
int x; //bbox: was int16
int32 res;
@@ -1229,8 +1191,6 @@ static int32 pstm_init_copy(psPool_t *pool, pstm_int * a, pstm_int * b, int toSq
}
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)
/******************************************************************************/
/*
@@ -1314,7 +1274,7 @@ static uint64 psDiv128(uint128 *numerator, uint64 denominator)
/*
a/b => cb + d == a
*/
static int32 pstm_div(psPool_t *pool, pstm_int *a, pstm_int *b, pstm_int *c,
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;
@@ -1527,7 +1487,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
*/
static void pstm_exch(pstm_int * a, pstm_int * b)
void pstm_exch(pstm_int * a, pstm_int * b)
{
pstm_int t;
@@ -1540,7 +1500,7 @@ static void pstm_exch(pstm_int * a, pstm_int * b)
/*
c = a mod b, 0 <= c < b
*/
static int32 pstm_mod(psPool_t *pool, pstm_int *a, pstm_int *b, pstm_int *c)
int32 pstm_mod(psPool_t *pool, pstm_int *a, pstm_int *b, pstm_int *c)
{
pstm_int t;
int32 err;
@@ -1567,7 +1527,7 @@ static int32 pstm_mod(psPool_t *pool, pstm_int *a, pstm_int *b, pstm_int *c)
/*
d = a * b (mod c)
*/
int32 FAST_FUNC pstm_mulmod(psPool_t *pool, pstm_int *a, pstm_int *b, pstm_int *c,
int32 pstm_mulmod(psPool_t *pool, pstm_int *a, pstm_int *b, pstm_int *c,
pstm_int *d)
{
int32 res;
@@ -1600,7 +1560,7 @@ int32 FAST_FUNC pstm_mulmod(psPool_t *pool, pstm_int *a, pstm_int *b, pstm_int *
* y = g**x (mod b)
* Some restrictions... x must be positive and < b
*/
int32 FAST_FUNC pstm_exptmod(psPool_t *pool, pstm_int *G, pstm_int *X, pstm_int *P,
int32 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) */
@@ -1841,7 +1801,7 @@ LBL_RES:pstm_clear(&res);
/*
*/
int32 FAST_FUNC pstm_add(pstm_int *a, pstm_int *b, pstm_int *c)
int32 pstm_add(pstm_int *a, pstm_int *b, pstm_int *c)
{
int32 res;
int sa, sb; //bbox: was int16
@@ -1902,7 +1862,6 @@ 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;
@@ -1924,12 +1883,11 @@ int32 pstm_to_unsigned_bin_nr(psPool_t *pool, pstm_int *a, unsigned char *b)
pstm_clear(&t);
return PS_SUCCESS;
}
#endif
/******************************************************************************/
/*
*/
int32 FAST_FUNC pstm_to_unsigned_bin(psPool_t *pool, pstm_int *a, unsigned char *b)
int32 pstm_to_unsigned_bin(psPool_t *pool, pstm_int *a, unsigned char *b)
{
int32 res;
int x; //bbox: was int16
@@ -1952,12 +1910,11 @@ int32 FAST_FUNC pstm_to_unsigned_bin(psPool_t *pool, pstm_int *a, unsigned char
return PS_SUCCESS;
}
#if 0 //UNUSED
/******************************************************************************/
/*
compare against a single digit
*/
static int32 pstm_cmp_d(pstm_int *a, pstm_digit b)
int32 pstm_cmp_d(pstm_int *a, pstm_digit b)
{
/* compare based on sign */
if ((b && a->used == 0) || a->sign == PSTM_NEG) {
@@ -2302,7 +2259,5 @@ 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; }
//made static:extern void pstm_set(pstm_int *a, pstm_digit b);
extern void pstm_set(pstm_int *a, pstm_digit b);
//made static:extern void pstm_zero(pstm_int * a);
extern void pstm_zero(pstm_int * a);
//bbox: pool unused
#define pstm_init(pool, a) \
pstm_init( a)
//made static:extern int32 pstm_init(psPool_t *pool, pstm_int * a);
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) FAST_FUNC;
extern int32 pstm_init_size(psPool_t *pool, pstm_int * a, uint32 size);
//bbox: pool unused
#define pstm_init_copy(pool, a, b, toSqr) \
pstm_init_copy( a, b, 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 int32 pstm_init_copy(psPool_t *pool, pstm_int * a, pstm_int * b,
int toSqr); //bbox: was int16 toSqr
//made static:extern int pstm_count_bits (pstm_int * a) FAST_FUNC; //bbox: was returning int16
extern int pstm_count_bits (pstm_int * a); //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) FAST_FUNC;
uint32 len);
extern int32 pstm_read_unsigned_bin(pstm_int *a, unsigned char *b, int32 c) FAST_FUNC;
extern int32 pstm_read_unsigned_bin(pstm_int *a, unsigned char *b, int32 c);
extern int32 pstm_unsigned_bin_size(pstm_int *a) FAST_FUNC;
extern int32 pstm_unsigned_bin_size(pstm_int *a);
extern int32 pstm_copy(pstm_int * a, pstm_int * b);
//made static:extern void pstm_exch(pstm_int * a, pstm_int * b);
extern void pstm_exch(pstm_int * a, pstm_int * b);
extern void pstm_clear(pstm_int * a) FAST_FUNC;
extern void pstm_clear(pstm_int * a);
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) FAST_FUNC;
pstm_int *mp7);
extern int32 pstm_grow(pstm_int * a, int size) FAST_FUNC; //bbox: was int16 size
extern int32 pstm_grow(pstm_int * a, int size); //bbox: was int16 size
extern void pstm_clamp(pstm_int * a) FAST_FUNC;
extern void pstm_clamp(pstm_int * a);
extern int32 pstm_cmp(pstm_int * a, pstm_int * b) FAST_FUNC;
extern int32 pstm_cmp(pstm_int * a, pstm_int * b);
extern int32 pstm_cmp_mag(pstm_int * a, pstm_int * b) FAST_FUNC;
extern int32 pstm_cmp_mag(pstm_int * a, pstm_int * b);
//made static:extern void pstm_rshd(pstm_int *a, int x); //bbox: was int16 x
extern void pstm_rshd(pstm_int *a, int x); //bbox: was int16 x
//made static:extern int32 pstm_lshd(pstm_int * a, int b); //bbox: was int16 b
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)
//made static:extern int32 pstm_div(psPool_t *pool, pstm_int *a, pstm_int *b, pstm_int *c,
//made static: pstm_int *d);
extern int32 pstm_div(psPool_t *pool, pstm_int *a, pstm_int *b, pstm_int *c,
pstm_int *d);
//bbox: pool unused
#define pstm_div_2d(pool, a, b, c, d) \
pstm_div_2d( a, b, c, d)
//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_2d(psPool_t *pool, pstm_int *a, int b, pstm_int *c,
pstm_int *d); //bbox: was int16 b
extern int32 pstm_div_2(pstm_int * a, pstm_int * b) FAST_FUNC;
extern int32 pstm_div_2(pstm_int * a, pstm_int * b);
extern int32 s_pstm_sub(pstm_int *a, pstm_int *b, pstm_int *c) FAST_FUNC;
extern int32 s_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;
extern int32 pstm_sub(pstm_int *a, pstm_int *b, pstm_int *c);
//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) FAST_FUNC;
extern int32 pstm_sub_d(psPool_t *pool, pstm_int *a, pstm_digit b, pstm_int *c);
extern int32 pstm_mul_2(pstm_int * a, pstm_int * b) FAST_FUNC;
extern int32 pstm_mul_2(pstm_int * a, pstm_int * b);
//bbox: pool unused
#define pstm_mod(pool, a, b, c) \
pstm_mod( a, b, c)
//made static:extern int32 pstm_mod(psPool_t *pool, pstm_int *a, pstm_int *b, pstm_int *c);
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) FAST_FUNC;
pstm_int *d);
//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) FAST_FUNC;
pstm_int *Y);
//made static:extern int32 pstm_2expt(pstm_int *a, int b); //bbox: was int16 b
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) FAST_FUNC;
extern int32 pstm_add(pstm_int *a, pstm_int *b, pstm_int *c);
//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) FAST_FUNC;
unsigned char *b);
//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) FAST_FUNC;
unsigned char *b);
//made static:extern int32 pstm_montgomery_setup(pstm_int *a, pstm_digit *rho);
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) FAST_FUNC;
pstm_digit mp, pstm_digit *paD, uint32 paDlen);
#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) FAST_FUNC;
pstm_int *C, pstm_digit *paD, uint32 paDlen);
//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) FAST_FUNC;
pstm_digit *paD, uint32 paDlen);
//made static:extern int32 pstm_cmp_d(pstm_int *a, pstm_digit b);
extern int32 pstm_cmp_d(pstm_int *a, pstm_digit b);
//made static:extern int32 pstm_montgomery_calc_normalization(pstm_int *a, pstm_int *b);
extern int32 pstm_montgomery_calc_normalization(pstm_int *a, pstm_int *b);
//made static:extern int32 pstm_mul_d(pstm_int *a, pstm_digit b, pstm_int *c);
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) FAST_FUNC;
pstm_int * c);
#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 FAST_FUNC pstm_montgomery_reduce(psPool_t *pool, pstm_int *a, pstm_int *m,
int32 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 FAST_FUNC pstm_mul_comba(psPool_t *pool, 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,
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 FAST_FUNC pstm_sqr_comba(psPool_t *pool, pstm_int *A, pstm_int *B, pstm_digit *paD,
int32 pstm_sqr_comba(psPool_t *pool, pstm_int *A, pstm_int *B, pstm_digit *paD,
uint32 paDlen)
{
#ifdef USE_1024_KEY_SPEED_OPTIMIZATIONS
+1 -3
View File
@@ -173,9 +173,7 @@ error:
res = PS_FAILURE;
done:
if (type == PRIVKEY_TYPE && key->optimized) {
//pstm_clear_multi(&tmpa, &tmpb, NULL, NULL, NULL, NULL, NULL, NULL);
pstm_clear(&tmpa);
pstm_clear(&tmpb);
pstm_clear_multi(&tmpa, &tmpb, NULL, NULL, NULL, NULL, NULL, NULL);
}
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 2
default 9
range 0 9
depends on UDHCPD || UDHCPC || UDHCPC6 || DHCPRELAY
help
+7 -15
View File
@@ -54,8 +54,6 @@ 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 */
@@ -123,8 +121,6 @@ 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
@@ -191,7 +187,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_info_msg("%s: 0x%02x %s", pfx, opt[OPT_CODE], buf);
bb_error_msg("%s: 0x%02x %s", pfx, opt[OPT_CODE], buf);
}
}
#else
@@ -306,7 +302,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[-OPT_DATA + OPT_LEN] != 4)
if (r[-1] != 4)
r = NULL;
}
return r;
@@ -426,7 +422,6 @@ 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) {
@@ -446,14 +441,15 @@ 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, buffer, length);
memcpy(new->data + OPT_DATA, (allocated ? allocated : 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, buffer,
memcpy(new->data + D6_OPT_DATA, (allocated ? allocated : buffer),
length);
}
@@ -476,8 +472,6 @@ 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
) {
@@ -485,9 +479,7 @@ static NOINLINE void attach_option(
existing->data[OPT_DATA + old_len] = ' ';
old_len++;
}
#endif
memcpy(existing->data + OPT_DATA + old_len, buffer, length);
memcpy(existing->data + OPT_DATA + old_len, (allocated ? allocated : 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 */
@@ -561,7 +553,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
+36 -30
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; /* aka 'giaddr': relay agent IP address */
uint32_t gateway_nip; /* 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,15 +149,13 @@ 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 Path prefix */
//#define DHCP_PXE_CONF_FILE 0xd1 /* 209: RFC 5071 Configuration File */
//#define DHCP_PXE_PATH_PREFIX 0xd2 /* 210: RFC 5071 Configuration File */
//#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 */
@@ -222,9 +220,10 @@ 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, 'chaddr' is always client's MAC
// Fields 'hops', 'yiaddr', 'siaddr', 'giaddr' are always zero
//
// Field DHCPDISCOVER DHCPINFORM DHCPREQUEST DHCPDECLINE DHCPRELEASE
// ----- ------------ ------------ ----------- ----------- -----------
@@ -233,49 +232,56 @@ 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 needs flag if client needs flag if client needs
// broadcast reply broadcast reply broadcast reply
// flag if client flag if client flag if client
// requires broadcast requires broadcast requires broadcast
// reply reply 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 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
// 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)
// 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_info_msg(__VA_ARGS__); } while (0)
# define log1(...) do { if (dhcp_verbose >= 1) bb_error_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_info_msg(__VA_ARGS__); } while (0)
# define log2(...) do { if (dhcp_verbose >= 2) bb_error_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_info_msg(__VA_ARGS__); } while (0)
# define log3(...) do { if (dhcp_verbose >= 3) bb_error_msg(__VA_ARGS__); } while (0)
# else
# define log3(...) ((void)0)
# endif
+2 -7
View File
@@ -141,16 +141,11 @@ 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);
+113 -114
View File
@@ -2,13 +2,15 @@
/*
* 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 y
//config: default n # not yet ready
//config: depends on FEATURE_IPV6
//config: help
//config: udhcpc6 is a DHCPv6 client
@@ -63,7 +65,7 @@
#include <netpacket/packet.h>
#include <linux/filter.h>
/* "struct client_data_t client_data" is in bb_common_bufsiz1 */
/* "struct client_config_t client_config" is in bb_common_bufsiz1 */
static const struct dhcp_optflag d6_optflags[] = {
#if ENABLE_FEATURE_UDHCPC6_RFC3646
@@ -204,6 +206,7 @@ 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)
@@ -427,7 +430,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_data.interface);
*new_env() = xasprintf("interface=%s", client_config.interface);
if (option)
option_to_env(option, option_end);
@@ -449,8 +452,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_data.script, name);
argv[0] = (char*) client_data.script;
log1("executing %s %s", client_config.script, name);
argv[0] = (char*) client_config.script;
argv[1] = (char*) name;
argv[2] = NULL;
spawn_and_wait(argv);
@@ -486,7 +489,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_data.clientid;
clientid = (void*)client_config.clientid;
return mempcpy(packet->d6_options, clientid, clientid->len + 2+2);
}
@@ -499,7 +502,7 @@ static uint8_t *add_d6_client_options(uint8_t *ptr)
ptr += 4;
for (option = 1; option < 256; option++) {
if (client_data.opt_mask[option >> 3] & (1 << (option & 7))) {
if (client_config.opt_mask[option >> 3] & (1 << (option & 7))) {
ptr[0] = (option >> 8);
ptr[1] = option;
ptr += 2;
@@ -518,7 +521,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_data.options;
curr = client_config.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);
@@ -528,9 +531,8 @@ static uint8_t *add_d6_client_options(uint8_t *ptr)
return ptr;
}
static int d6_mcast_from_client_data_ifindex(struct d6_packet *packet, uint8_t *end)
static int d6_mcast_from_client_config_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,
@@ -540,7 +542,7 @@ static int d6_mcast_from_client_data_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_data.ifindex
client_config.ifindex
);
}
@@ -670,8 +672,8 @@ static NOINLINE int send_d6_discover(uint32_t xid, struct in6_addr *requested_ip
*/
opt_ptr = add_d6_client_options(opt_ptr);
bb_info_msg("sending %s", "discover");
return d6_mcast_from_client_data_ifindex(&packet, opt_ptr);
bb_error_msg("sending %s", "discover");
return d6_mcast_from_client_config_ifindex(&packet, opt_ptr);
}
/* Multicast a DHCPv6 request message
@@ -727,8 +729,8 @@ static NOINLINE int send_d6_select(uint32_t xid)
*/
opt_ptr = add_d6_client_options(opt_ptr);
bb_info_msg("sending %s", "select");
return d6_mcast_from_client_data_ifindex(&packet, opt_ptr);
bb_error_msg("sending %s", "select");
return d6_mcast_from_client_config_ifindex(&packet, opt_ptr);
}
/* Unicast or broadcast a DHCP renew message
@@ -800,15 +802,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_info_msg("sending %s", "renew");
bb_error_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_data.ifindex
client_config.ifindex
);
return d6_mcast_from_client_data_ifindex(&packet, opt_ptr);
return d6_mcast_from_client_config_ifindex(&packet, opt_ptr);
}
/* Unicast a DHCP release message */
@@ -830,12 +832,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_info_msg("sending %s", "release");
bb_error_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_data.ifindex
client_config.ifindex
);
}
@@ -901,14 +903,16 @@ static NOINLINE int d6_recv_raw_packet(struct in6_addr *peer_ipv6, struct d6_pac
return bytes;
}
/*** Main ***/
/* Values for client_data.listen_mode */
static int sockfd = -1;
#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 */
@@ -923,6 +927,7 @@ static NOINLINE int d6_recv_raw_packet(struct in6_addr *peer_ipv6, struct d6_pac
#define RENEW_REQUESTED 5
/* release, possibly manually requested (SIGUSR2) */
#define RELEASED 6
static smallint state;
static int d6_raw_socket(int ifindex)
{
@@ -981,7 +986,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));
log3("got raw socket fd %d", fd);
log2("got raw socket fd %d", fd);
memset(&sock, 0, sizeof(sock)); /* let's be deterministic */
sock.sll_family = AF_PACKET;
@@ -1016,35 +1021,35 @@ static void change_listen_mode(int new_mode)
: "none"
);
client_data.listen_mode = new_mode;
if (client_data.sockfd >= 0) {
close(client_data.sockfd);
client_data.sockfd = -1;
listen_mode = new_mode;
if (sockfd >= 0) {
close(sockfd);
sockfd = -1;
}
if (new_mode == LISTEN_KERNEL)
client_data.sockfd = udhcp_listen_socket(/*INADDR_ANY,*/ CLIENT_PORT6, client_data.interface);
sockfd = udhcp_listen_socket(/*INADDR_ANY,*/ CLIENT_PORT6, client_config.interface);
else if (new_mode != LISTEN_NONE)
client_data.sockfd = d6_raw_socket(client_data.ifindex);
/* else LISTEN_NONE: client_data.sockfd stays closed */
sockfd = d6_raw_socket(client_config.ifindex);
/* else LISTEN_NONE: sockfd stays closed */
}
/* Called only on SIGUSR1 */
static void perform_renew(void)
{
bb_info_msg("performing DHCP renew");
switch (client_data.state) {
bb_error_msg("performing DHCP renew");
switch (state) {
case BOUND:
change_listen_mode(LISTEN_KERNEL);
case RENEWING:
case REBINDING:
client_data.state = RENEW_REQUESTED;
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);
client_data.state = INIT_SELECTING;
state = INIT_SELECTING;
break;
case INIT_SELECTING:
break;
@@ -1054,15 +1059,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 (client_data.state == BOUND
|| client_data.state == RENEWING
|| client_data.state == REBINDING
|| client_data.state == RENEW_REQUESTED
if (state == BOUND
|| state == RENEWING
|| state == REBINDING
|| state == RENEW_REQUESTED
) {
bb_info_msg("unicasting a release");
bb_error_msg("unicasting a release");
send_d6_release(server_ipv6, our_cur_ipv6); /* unicast */
}
bb_info_msg("entering released state");
bb_error_msg("entering released state");
/*
* We can be here on: SIGUSR2,
* or on exit (SIGTERM) and -R "release on quit" is specified.
@@ -1071,7 +1076,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);
client_data.state = RELEASED;
state = RELEASED;
}
///static uint8_t* alloc_dhcp_option(int code, const char *str, int extra)
@@ -1091,7 +1096,7 @@ static void client_background(void)
bb_daemonize(0);
logmode &= ~LOGMODE_STDIO;
/* rewrite pidfile, as our pid is different now */
write_pidfile(client_data.pidfile);
write_pidfile(client_config.pidfile);
}
#endif
@@ -1142,6 +1147,7 @@ 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)
{
@@ -1170,13 +1176,8 @@ 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_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();
client_config.interface = "eth0";
client_config.script = CONFIG_UDHCPC_DEFAULT_SCRIPT;
/* Parse command line */
opt = getopt32long(argv, "^"
@@ -1188,8 +1189,8 @@ int udhcpc6_main(int argc UNUSED_PARAM, char **argv)
"v"
"\0" IF_UDHCP_VERBOSE("vv") /* -v is a counter */
, udhcpc6_longopts
, &client_data.interface, &client_data.pidfile, &str_r /* i,p */
, &client_data.script /* s */
, &client_config.interface, &client_config.pidfile, &str_r /* i,p */
, &client_config.script /* s */
, &discover_timeout, &discover_retries, &tryagain_timeout /* T,t,A */
, &list_O
, &list_x
@@ -1220,29 +1221,29 @@ int udhcpc6_main(int argc UNUSED_PARAM, char **argv)
n = udhcp_option_idx(optstr, d6_option_strings);
n = d6_optflags[n].code;
}
client_data.opt_mask[n >> 3] |= 1 << (n & 7);
client_config.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_data.opt_mask[n >> 3] |= 1 << (n & 7);
client_config.opt_mask[n >> 3] |= 1 << (n & 7);
}
}
}
while (list_x) {
char *optstr = xstrdup(llist_pop(&list_x));
udhcp_str2optset(optstr, &client_data.options,
udhcp_str2optset(optstr, &client_config.options,
d6_optflags, d6_option_strings,
/*dhcpv6:*/ 1
);
free(optstr);
}
if (d6_read_interface(client_data.interface,
&client_data.ifindex,
if (d6_read_interface(client_config.interface,
&client_config.ifindex,
&client6_data.ll_ip6,
client_data.client_mac)
client_config.client_mac)
) {
return 1;
}
@@ -1256,8 +1257,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_data.client_mac, 6);
client_data.clientid = (void*)clientid;
memcpy(clientid_mac_ptr, client_config.client_mac, 6);
client_config.clientid = (void*)clientid;
}
#if !BB_MMU
@@ -1272,12 +1273,16 @@ 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_data.pidfile);
write_pidfile(client_config.pidfile);
/* Goes to stdout (unless NOMMU) and possibly syslog */
bb_info_msg("started, v"BB_VER);
bb_error_msg("started, v"BB_VER);
/* Set up the signal pipe */
udhcp_sp_setup();
client_data.state = INIT_SELECTING;
state = INIT_SELECTING;
d6_run_script_no_option("deconfig");
change_listen_mode(LISTEN_RAW);
packet_num = 0;
@@ -1296,16 +1301,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", client_data.sockfd, client_data.listen_mode);
//bb_error_msg("sockfd:%d, listen_mode:%d", sockfd, listen_mode);
/* Was opening raw or udp socket here
* if (client_data.listen_mode != LISTEN_NONE && client_data.sockfd < 0),
* if (listen_mode != LISTEN_NONE && 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, client_data.sockfd);
udhcp_sp_fd_set(pfds, sockfd);
tv = timeout - already_waited_sec;
retval = 0;
@@ -1334,20 +1339,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_data.interface,
&client_data.ifindex,
if (d6_read_interface(client_config.interface,
&client_config.ifindex,
&client6_data.ll_ip6,
client_data.client_mac)
client_config.client_mac)
) {
goto ret0; /* iface is gone? */
}
memcpy(clientid_mac_ptr, client_data.client_mac, 6);
memcpy(clientid_mac_ptr, client_config.client_mac, 6);
/* We will restart the wait in any case */
already_waited_sec = 0;
switch (client_data.state) {
switch (state) {
case INIT_SELECTING:
if (!discover_retries || packet_num < discover_retries) {
if (packet_num == 0)
@@ -1362,20 +1367,14 @@ 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_info_msg("no lease, forking to background");
bb_error_msg("no lease, forking to background");
client_background();
/* do not background again! */
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_.
*/
opt = ((opt & ~OPT_b) | OPT_f);
} else
#endif
if (opt & OPT_n) { /* abort if no lease */
bb_info_msg("no lease, failing");
bb_error_msg("no lease, failing");
retval = 1;
goto ret;
}
@@ -1396,12 +1395,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);
client_data.state = INIT_SELECTING;
state = INIT_SELECTING;
goto leasefail;
case BOUND:
/* 1/2 lease passed, enter renewing state */
client_data.state = RENEWING;
client_data.first_secs = 0; /* make secs field count from 0 */
state = RENEWING;
client_config.first_secs = 0; /* make secs field count from 0 */
change_listen_mode(LISTEN_KERNEL);
log1("entering renew state");
/* fall right through */
@@ -1424,7 +1423,7 @@ int udhcpc6_main(int argc UNUSED_PARAM, char **argv)
}
/* Timed out, enter rebinding state */
log1("entering rebinding state");
client_data.state = REBINDING;
state = REBINDING;
/* fall right through */
case REBINDING:
/* Switch to bcast receive */
@@ -1438,10 +1437,10 @@ int udhcpc6_main(int argc UNUSED_PARAM, char **argv)
continue;
}
/* Timed out, enter init state */
bb_info_msg("lease lost, entering init state");
bb_error_msg("lease lost, entering init state");
d6_run_script_no_option("deconfig");
client_data.state = INIT_SELECTING;
client_data.first_secs = 0; /* make secs field count from 0 */
state = INIT_SELECTING;
client_config.first_secs = 0; /* make secs field count from 0 */
/*timeout = 0; - already is */
packet_num = 0;
continue;
@@ -1457,10 +1456,10 @@ int udhcpc6_main(int argc UNUSED_PARAM, char **argv)
/* Is it a signal? */
switch (udhcp_sp_read()) {
case SIGUSR1:
client_data.first_secs = 0; /* make secs field count from 0 */
client_config.first_secs = 0; /* make secs field count from 0 */
already_waited_sec = 0;
perform_renew();
if (client_data.state == RENEW_REQUESTED) {
if (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
@@ -1483,7 +1482,7 @@ int udhcpc6_main(int argc UNUSED_PARAM, char **argv)
timeout = INT_MAX;
continue;
case SIGTERM:
bb_info_msg("received %s", "SIGTERM");
bb_error_msg("received %s", "SIGTERM");
goto ret0;
}
@@ -1495,15 +1494,15 @@ int udhcpc6_main(int argc UNUSED_PARAM, char **argv)
int len;
/* A packet is ready, read it */
if (client_data.listen_mode == LISTEN_KERNEL)
len = d6_recv_kernel_packet(&srv6_buf, &packet, client_data.sockfd);
if (listen_mode == LISTEN_KERNEL)
len = d6_recv_kernel_packet(&srv6_buf, &packet, sockfd);
else
len = d6_recv_raw_packet(&srv6_buf, &packet, client_data.sockfd);
len = d6_recv_raw_packet(&srv6_buf, &packet, 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(client_data.listen_mode); /* just close and reopen */
change_listen_mode(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.
@@ -1520,7 +1519,7 @@ int udhcpc6_main(int argc UNUSED_PARAM, char **argv)
continue;
}
switch (client_data.state) {
switch (state) {
case INIT_SELECTING:
if (packet.d6_msg_type == D6_MSG_ADVERTISE)
goto type_is_ok;
@@ -1543,15 +1542,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_info_msg("received DHCP NAK (%u)", option->data[4]);
bb_error_msg("received DHCP NAK (%u)", option->data[4]);
d6_run_script(packet.d6_options,
packet_end, "nak");
if (client_data.state != REQUESTING)
if (state != REQUESTING)
d6_run_script_no_option("deconfig");
change_listen_mode(LISTEN_RAW);
sleep(3); /* avoid excessive network traffic */
client_data.state = INIT_SELECTING;
client_data.first_secs = 0; /* make secs field count from 0 */
state = INIT_SELECTING;
client_config.first_secs = 0; /* make secs field count from 0 */
requested_ipv6 = NULL;
timeout = 0;
packet_num = 0;
@@ -1560,7 +1559,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_info_msg("no server ID, ignoring packet");
bb_error_msg("no server ID, ignoring packet");
continue;
/* still selecting - this server looks bad */
}
@@ -1571,7 +1570,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 */
client_data.state = REQUESTING;
state = REQUESTING;
timeout = 0;
packet_num = 0;
already_waited_sec = 0;
@@ -1669,11 +1668,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_info_msg("no %s option, ignoring packet", "IA_NA");
bb_error_msg("no %s option, ignoring packet", "IA_NA");
continue;
}
if (client6_data.ia_na->len < (4 + 4 + 4) + (2 + 2 + 16 + 4 + 4)) {
bb_info_msg("%s option is too short:%d bytes",
bb_error_msg("%s option is too short:%d bytes",
"IA_NA", client6_data.ia_na->len);
continue;
}
@@ -1682,11 +1681,11 @@ int udhcpc6_main(int argc UNUSED_PARAM, char **argv)
D6_OPT_IAADDR
);
if (!iaaddr) {
bb_info_msg("no %s option, ignoring packet", "IAADDR");
bb_error_msg("no %s option, ignoring packet", "IAADDR");
continue;
}
if (iaaddr->len < (16 + 4 + 4)) {
bb_info_msg("%s option is too short:%d bytes",
bb_error_msg("%s option is too short:%d bytes",
"IAADDR", iaaddr->len);
continue;
}
@@ -1697,7 +1696,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_info_msg("%s obtained, lease time %u",
bb_error_msg("%s obtained, lease time %u",
"IPv6", /*inet_ntoa(temp_addr),*/ (unsigned)lease_seconds);
address_timeout = lease_seconds;
}
@@ -1707,11 +1706,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_info_msg("no %s option, ignoring packet", "IA_PD");
bb_error_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_info_msg("%s option is too short:%d bytes",
bb_error_msg("%s option is too short:%d bytes",
"IA_PD", client6_data.ia_pd->len);
continue;
}
@@ -1720,17 +1719,17 @@ int udhcpc6_main(int argc UNUSED_PARAM, char **argv)
D6_OPT_IAPREFIX
);
if (!iaprefix) {
bb_info_msg("no %s option, ignoring packet", "IAPREFIX");
bb_error_msg("no %s option, ignoring packet", "IAPREFIX");
continue;
}
if (iaprefix->len < (4 + 4 + 1 + 16)) {
bb_info_msg("%s option is too short:%d bytes",
bb_error_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_info_msg("%s obtained, lease time %u",
bb_error_msg("%s obtained, lease time %u",
"prefix", /*inet_ntoa(temp_addr),*/ (unsigned)lease_seconds);
prefix_timeout = lease_seconds;
}
@@ -1746,9 +1745,9 @@ int udhcpc6_main(int argc UNUSED_PARAM, char **argv)
timeout = 61;
/* enter bound state */
d6_run_script(packet.d6_options, packet_end,
(client_data.state == REQUESTING ? "bound" : "renew"));
(state == REQUESTING ? "bound" : "renew"));
client_data.state = BOUND;
state = BOUND;
change_listen_mode(LISTEN_NONE);
if (opt & OPT_q) { /* quit after lease */
goto ret0;
@@ -1777,7 +1776,7 @@ int udhcpc6_main(int argc UNUSED_PARAM, char **argv)
perform_d6_release(&srv6_buf, requested_ipv6);
retval = 0;
ret:
/*if (client_data.pidfile) - remove_pidfile has its own check */
remove_pidfile(client_data.pidfile);
/*if (client_config.pidfile) - remove_pidfile has its own check */
remove_pidfile(client_config.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_info_msg(
bb_error_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_info_msg("packet with bad magic, ignoring");
bb_error_msg("packet with bad magic, ignoring");
return -2;
}
log1("received %s", "a packet");
+6 -21
View File
@@ -10,11 +10,7 @@
#include <ifaddrs.h>
#include <netpacket/packet.h>
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 retval = 3;
struct ifaddrs *ifap, *ifa;
@@ -26,12 +22,12 @@ int FAST_FUNC d6_read_interface(
if (!ifa->ifa_addr || (strcmp(ifa->ifa_name, interface) != 0))
continue;
sip6 = (struct sockaddr_in6*)(ifa->ifa_addr);
if (ifa->ifa_addr->sa_family == AF_PACKET) {
struct sockaddr_ll *sll = (void*)(ifa->ifa_addr);
struct sockaddr_ll *sll = (struct sockaddr_ll*)(ifa->ifa_addr);
memcpy(mac, sll->sll_addr, 6);
log2("MAC %02x:%02x:%02x:%02x:%02x:%02x",
mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]
);
log2("MAC %02x:%02x:%02x:%02x:%02x:%02x", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
*ifindex = sll->sll_ifindex;
log2("ifindex %d", *ifindex);
retval &= (3 - (1<<0));
@@ -42,17 +38,6 @@ int FAST_FUNC d6_read_interface(
log1("IP %s", inet_ntoa(((struct sockaddr_in *)ifa->ifa_addr)->sin_addr));
}
#endif
/* RFC 3315
* 16. Client Source Address and Interface Selection
*
* "When a client sends a DHCP message to the
* All_DHCP_Relay_Agents_and_Servers address, ... ... The client
* MUST use a link-local address assigned to the interface for which it
* is requesting configuration information as the source address in the
* header of the IP datagram."
*/
sip6 = (void*)(ifa->ifa_addr);
if (ifa->ifa_addr->sa_family == AF_INET6
&& IN6_IS_ADDR_LINKLOCAL(&sip6->sin6_addr)
) {
@@ -102,7 +87,7 @@ int FAST_FUNC d6_read_interface(
bb_error_msg("can't get %s", "MAC");
if (retval & (1<<1))
bb_error_msg("can't get %s", "link-local IPv6 address");
return retval;
return -1;
}
int FAST_FUNC d6_listen_socket(int port, const char *inf)
+139 -144
View File
@@ -49,7 +49,7 @@ struct tpacket_auxdata {
#endif
/* "struct client_data_t client_data" is in bb_common_bufsiz1 */
/* "struct client_config_t client_config" is in bb_common_bufsiz1 */
#if ENABLE_LONG_OPTS
@@ -477,7 +477,7 @@ static char **fill_envp(struct dhcp_packet *packet)
}
curr = envp = xzalloc(sizeof(envp[0]) * envc);
*curr = xasprintf("interface=%s", client_data.interface);
*curr = xasprintf("interface=%s", client_config.interface);
putenv(*curr++);
if (!packet)
@@ -531,7 +531,7 @@ static char **fill_envp(struct dhcp_packet *packet)
temp = udhcp_get_option(packet, code);
*curr = xmalloc_optname_optval(temp, &dhcp_optflags[i], opt_name);
putenv(*curr++);
if (code == DHCP_SUBNET && temp[-OPT_DATA + OPT_LEN] == 4) {
if (code == DHCP_SUBNET) {
/* Subnet option: make things like "$ip/$mask" possible */
uint32_t subnet;
move_from_unaligned32(subnet, temp);
@@ -577,8 +577,8 @@ static void udhcp_run_script(struct dhcp_packet *packet, const char *name)
envp = fill_envp(packet);
/* call script */
log1("executing %s %s", client_data.script, name);
argv[0] = (char*) client_data.script;
log1("executing %s %s", client_config.script, name);
argv[0] = (char*) client_config.script;
argv[1] = (char*) name;
argv[2] = NULL;
spawn_and_wait(argv);
@@ -608,15 +608,15 @@ static void init_packet(struct dhcp_packet *packet, char type)
packet->xid = random_xid();
client_data.last_secs = monotonic_sec();
if (client_data.first_secs == 0)
client_data.first_secs = client_data.last_secs;
secs = client_data.last_secs - client_data.first_secs;
client_config.last_secs = monotonic_sec();
if (client_config.first_secs == 0)
client_config.first_secs = client_config.last_secs;
secs = client_config.last_secs - client_config.first_secs;
packet->secs = htons(secs);
memcpy(packet->chaddr, client_data.client_mac, 6);
if (client_data.clientid)
udhcp_add_binary_option(packet, client_data.clientid);
memcpy(packet->chaddr, client_config.client_mac, 6);
if (client_config.clientid)
udhcp_add_binary_option(packet, client_config.clientid);
}
static void add_client_options(struct dhcp_packet *packet)
@@ -631,7 +631,7 @@ static void add_client_options(struct dhcp_packet *packet)
end = udhcp_end_option(packet->options);
len = 0;
for (i = 1; i < DHCP_END; i++) {
if (client_data.opt_mask[i >> 3] & (1 << (i & 7))) {
if (client_config.opt_mask[i >> 3] & (1 << (i & 7))) {
packet->options[end + OPT_DATA + len] = i;
len++;
}
@@ -642,12 +642,12 @@ static void add_client_options(struct dhcp_packet *packet)
packet->options[end + OPT_DATA + len] = DHCP_END;
}
if (client_data.vendorclass)
udhcp_add_binary_option(packet, client_data.vendorclass);
if (client_data.hostname)
udhcp_add_binary_option(packet, client_data.hostname);
if (client_data.fqdn)
udhcp_add_binary_option(packet, client_data.fqdn);
if (client_config.vendorclass)
udhcp_add_binary_option(packet, client_config.vendorclass);
if (client_config.hostname)
udhcp_add_binary_option(packet, client_config.hostname);
if (client_config.fqdn)
udhcp_add_binary_option(packet, client_config.fqdn);
/* Request broadcast replies if we have no IP addr */
if ((option_mask32 & OPT_B) && packet->ciaddr == 0)
@@ -655,15 +655,15 @@ static void add_client_options(struct dhcp_packet *packet)
/* Add -x options if any */
{
struct option_set *curr = client_data.options;
struct option_set *curr = client_config.options;
while (curr) {
udhcp_add_binary_option(packet, curr->data);
curr = curr->next;
}
// if (client_data.sname)
// strncpy((char*)packet->sname, client_data.sname, sizeof(packet->sname) - 1);
// if (client_data.boot_file)
// strncpy((char*)packet->file, client_data.boot_file, sizeof(packet->file) - 1);
// if (client_config.sname)
// strncpy((char*)packet->sname, client_config.sname, sizeof(packet->sname) - 1);
// if (client_config.boot_file)
// strncpy((char*)packet->file, client_config.boot_file, sizeof(packet->file) - 1);
}
// This will be needed if we remove -V VENDOR_STR in favor of
@@ -691,12 +691,12 @@ static void add_client_options(struct dhcp_packet *packet)
* client reverts to using the IP broadcast address.
*/
static int raw_bcast_from_client_data_ifindex(struct dhcp_packet *packet, uint32_t src_nip)
static int raw_bcast_from_client_config_ifindex(struct dhcp_packet *packet, uint32_t src_nip)
{
return udhcp_send_raw_packet(packet,
/*src*/ src_nip, CLIENT_PORT,
/*dst*/ INADDR_BROADCAST, SERVER_PORT, MAC_BCAST_ADDR,
client_data.ifindex);
client_config.ifindex);
}
static int bcast_or_ucast(struct dhcp_packet *packet, uint32_t ciaddr, uint32_t server)
@@ -705,7 +705,7 @@ static int bcast_or_ucast(struct dhcp_packet *packet, uint32_t ciaddr, uint32_t
return udhcp_send_kernel_packet(packet,
ciaddr, CLIENT_PORT,
server, SERVER_PORT);
return raw_bcast_from_client_data_ifindex(packet, ciaddr);
return raw_bcast_from_client_config_ifindex(packet, ciaddr);
}
/* Broadcast a DHCP discover packet to the network, with an optionally requested IP */
@@ -730,8 +730,8 @@ static NOINLINE int send_discover(uint32_t xid, uint32_t requested)
*/
add_client_options(&packet);
bb_info_msg("sending %s", "discover");
return raw_bcast_from_client_data_ifindex(&packet, INADDR_ANY);
bb_error_msg("sending %s", "discover");
return raw_bcast_from_client_config_ifindex(&packet, INADDR_ANY);
}
/* Broadcast a DHCP request message */
@@ -774,8 +774,8 @@ static NOINLINE int send_select(uint32_t xid, uint32_t server, uint32_t requeste
add_client_options(&packet);
temp_addr.s_addr = requested;
bb_info_msg("sending select for %s", inet_ntoa(temp_addr));
return raw_bcast_from_client_data_ifindex(&packet, INADDR_ANY);
bb_error_msg("sending select for %s", inet_ntoa(temp_addr));
return raw_bcast_from_client_config_ifindex(&packet, INADDR_ANY);
}
/* Unicast or broadcast a DHCP renew message */
@@ -815,7 +815,7 @@ static NOINLINE int send_renew(uint32_t xid, uint32_t server, uint32_t ciaddr)
add_client_options(&packet);
temp_addr.s_addr = server;
bb_info_msg("sending renew to %s", inet_ntoa(temp_addr));
bb_error_msg("sending renew to %s", inet_ntoa(temp_addr));
return bcast_or_ucast(&packet, ciaddr, server);
}
@@ -844,8 +844,8 @@ static NOINLINE int send_decline(/*uint32_t xid,*/ uint32_t server, uint32_t req
udhcp_add_simple_option(&packet, DHCP_SERVER_ID, server);
bb_info_msg("sending %s", "decline");
return raw_bcast_from_client_data_ifindex(&packet, INADDR_ANY);
bb_error_msg("sending %s", "decline");
return raw_bcast_from_client_config_ifindex(&packet, INADDR_ANY);
}
#endif
@@ -866,7 +866,7 @@ int send_release(uint32_t server, uint32_t ciaddr)
udhcp_add_simple_option(&packet, DHCP_SERVER_ID, server);
bb_info_msg("sending %s", "release");
bb_error_msg("sending %s", "release");
/* Note: normally we unicast here since "server" is not zero.
* However, there _are_ people who run "address-less" DHCP servers,
* and reportedly ISC dhcp client and Windows allow that.
@@ -969,7 +969,7 @@ static NOINLINE int udhcp_recv_raw_packet(struct dhcp_packet *dhcp_pkt, int fd)
skip_udp_sum_check:
if (packet.data.cookie != htonl(DHCP_MAGIC)) {
bb_info_msg("packet with bad magic, ignoring");
bb_error_msg("packet with bad magic, ignoring");
return -2;
}
@@ -984,12 +984,13 @@ static NOINLINE int udhcp_recv_raw_packet(struct dhcp_packet *dhcp_pkt, int fd)
/*** Main ***/
/* Values for client_data.listen_mode */
static int sockfd = -1;
#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 */
@@ -1004,6 +1005,7 @@ static NOINLINE int udhcp_recv_raw_packet(struct dhcp_packet *dhcp_pkt, int fd)
#define RENEW_REQUESTED 5
/* release, possibly manually requested (SIGUSR2) */
#define RELEASED 6
static smallint state;
static int udhcp_raw_socket(int ifindex)
{
@@ -1017,7 +1019,7 @@ static int udhcp_raw_socket(int ifindex)
* SOCK_DGRAM: remove link-layer headers on input (SOCK_RAW keeps them)
* ETH_P_IP: want to receive only packets with IPv4 eth type
*/
log3("got raw socket fd %d", fd);
log2("got raw socket fd");
memset(&sock, 0, sizeof(sock)); /* let's be deterministic */
sock.sll_family = AF_PACKET;
@@ -1100,35 +1102,35 @@ static void change_listen_mode(int new_mode)
: "none"
);
client_data.listen_mode = new_mode;
if (client_data.sockfd >= 0) {
close(client_data.sockfd);
client_data.sockfd = -1;
listen_mode = new_mode;
if (sockfd >= 0) {
close(sockfd);
sockfd = -1;
}
if (new_mode == LISTEN_KERNEL)
client_data.sockfd = udhcp_listen_socket(/*INADDR_ANY,*/ CLIENT_PORT, client_data.interface);
sockfd = udhcp_listen_socket(/*INADDR_ANY,*/ CLIENT_PORT, client_config.interface);
else if (new_mode != LISTEN_NONE)
client_data.sockfd = udhcp_raw_socket(client_data.ifindex);
/* else LISTEN_NONE: client_data.sockfd stays closed */
sockfd = udhcp_raw_socket(client_config.ifindex);
/* else LISTEN_NONE: sockfd stays closed */
}
/* Called only on SIGUSR1 */
static void perform_renew(void)
{
bb_info_msg("performing DHCP renew");
switch (client_data.state) {
bb_error_msg("performing DHCP renew");
switch (state) {
case BOUND:
change_listen_mode(LISTEN_KERNEL);
case RENEWING:
case REBINDING:
client_data.state = RENEW_REQUESTED;
state = RENEW_REQUESTED;
break;
case RENEW_REQUESTED: /* impatient are we? fine, square 1 */
udhcp_run_script(NULL, "deconfig");
case REQUESTING:
case RELEASED:
change_listen_mode(LISTEN_RAW);
client_data.state = INIT_SELECTING;
state = INIT_SELECTING;
break;
case INIT_SELECTING:
break;
@@ -1141,19 +1143,19 @@ static void perform_release(uint32_t server_addr, uint32_t requested_ip)
struct in_addr temp_addr;
/* send release packet */
if (client_data.state == BOUND
|| client_data.state == RENEWING
|| client_data.state == REBINDING
|| client_data.state == RENEW_REQUESTED
if (state == BOUND
|| state == RENEWING
|| state == REBINDING
|| state == RENEW_REQUESTED
) {
temp_addr.s_addr = server_addr;
strcpy(buffer, inet_ntoa(temp_addr));
temp_addr.s_addr = requested_ip;
bb_info_msg("unicasting a release of %s to %s",
bb_error_msg("unicasting a release of %s to %s",
inet_ntoa(temp_addr), buffer);
send_release(server_addr, requested_ip); /* unicast */
}
bb_info_msg("entering released state");
bb_error_msg("entering released state");
/*
* We can be here on: SIGUSR2,
* or on exit (SIGTERM) and -R "release on quit" is specified.
@@ -1163,7 +1165,7 @@ static void perform_release(uint32_t server_addr, uint32_t requested_ip)
udhcp_run_script(NULL, "deconfig");
change_listen_mode(LISTEN_NONE);
client_data.state = RELEASED;
state = RELEASED;
}
static uint8_t* alloc_dhcp_option(int code, const char *str, int extra)
@@ -1183,7 +1185,7 @@ static void client_background(void)
bb_daemonize(0);
logmode &= ~LOGMODE_STDIO;
/* rewrite pidfile, as our pid is different now */
write_pidfile(client_data.pidfile);
write_pidfile(client_config.pidfile);
}
#endif
@@ -1207,13 +1209,13 @@ static void client_background(void)
//usage: "\n -t N Send up to N discover packets (default 3)"
//usage: "\n -T SEC Pause between packets (default 3)"
//usage: "\n -A SEC Wait if lease is not obtained (default 20)"
//usage: USE_FOR_MMU(
//usage: "\n -b Background if lease is not obtained"
//usage: )
//usage: "\n -n Exit if lease is not obtained"
//usage: "\n -q Exit after obtaining lease"
//usage: "\n -R Release IP on exit"
//usage: "\n -f Run in foreground"
//usage: USE_FOR_MMU(
//usage: "\n -b Background if lease is not obtained"
//usage: )
//usage: "\n -S Log to syslog too"
//usage: IF_FEATURE_UDHCPC_ARPING(
//usage: "\n -a[MSEC] Validate offered address with ARP ping"
@@ -1266,15 +1268,10 @@ int udhcpc_main(int argc UNUSED_PARAM, char **argv)
/* Default options */
IF_FEATURE_UDHCP_PORT(SERVER_PORT = 67;)
IF_FEATURE_UDHCP_PORT(CLIENT_PORT = 68;)
client_data.interface = "eth0";
client_data.script = CONFIG_UDHCPC_DEFAULT_SCRIPT;
client_data.sockfd = -1;
client_config.interface = "eth0";
client_config.script = CONFIG_UDHCPC_DEFAULT_SCRIPT;
str_V = "udhcp "BB_VER;
/* 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, "^"
/* O,x: list; -T,-t,-A take numeric param */
@@ -1286,9 +1283,9 @@ int udhcpc_main(int argc UNUSED_PARAM, char **argv)
"\0" IF_UDHCP_VERBOSE("vv") /* -v is a counter */
, udhcpc_longopts
, &str_V, &str_h, &str_h, &str_F
, &client_data.interface, &client_data.pidfile /* i,p */
, &client_config.interface, &client_config.pidfile /* i,p */
, &str_r /* r */
, &client_data.script /* s */
, &client_config.script /* s */
, &discover_timeout, &discover_retries, &tryagain_timeout /* T,t,A */
, &list_O
, &list_x
@@ -1299,11 +1296,11 @@ int udhcpc_main(int argc UNUSED_PARAM, char **argv)
if (opt & (OPT_h|OPT_H)) {
//msg added 2011-11
bb_error_msg("option -h NAME is deprecated, use -x hostname:NAME");
client_data.hostname = alloc_dhcp_option(DHCP_HOST_NAME, str_h, 0);
client_config.hostname = alloc_dhcp_option(DHCP_HOST_NAME, str_h, 0);
}
if (opt & OPT_F) {
/* FQDN option format: [0x51][len][flags][0][0]<fqdn> */
client_data.fqdn = alloc_dhcp_option(DHCP_FQDN, str_F, 3);
client_config.fqdn = alloc_dhcp_option(DHCP_FQDN, str_F, 3);
/* Flag bits: 0000NEOS
* S: 1 = Client requests server to update A RR in DNS as well as PTR
* O: 1 = Server indicates to client that DNS has been updated regardless
@@ -1312,9 +1309,9 @@ int udhcpc_main(int argc UNUSED_PARAM, char **argv)
* N: 1 = Client requests server to not update DNS (S must be 0 then)
* Two [0] bytes which follow are deprecated and must be 0.
*/
client_data.fqdn[OPT_DATA + 0] = 0x1;
/*client_data.fqdn[OPT_DATA + 1] = 0; - xzalloc did it */
/*client_data.fqdn[OPT_DATA + 2] = 0; */
client_config.fqdn[OPT_DATA + 0] = 0x1;
/*client_config.fqdn[OPT_DATA + 1] = 0; - xzalloc did it */
/*client_config.fqdn[OPT_DATA + 2] = 0; */
}
if (opt & OPT_r)
requested_ip = inet_addr(str_r);
@@ -1332,49 +1329,49 @@ int udhcpc_main(int argc UNUSED_PARAM, char **argv)
n = udhcp_option_idx(optstr, dhcp_option_strings);
n = dhcp_optflags[n].code;
}
client_data.opt_mask[n >> 3] |= 1 << (n & 7);
client_config.opt_mask[n >> 3] |= 1 << (n & 7);
}
if (!(opt & OPT_o)) {
unsigned i, n;
for (i = 0; (n = dhcp_optflags[i].code) != 0; i++) {
if (dhcp_optflags[i].flags & OPTION_REQ) {
client_data.opt_mask[n >> 3] |= 1 << (n & 7);
client_config.opt_mask[n >> 3] |= 1 << (n & 7);
}
}
}
while (list_x) {
char *optstr = xstrdup(llist_pop(&list_x));
udhcp_str2optset(optstr, &client_data.options,
udhcp_str2optset(optstr, &client_config.options,
dhcp_optflags, dhcp_option_strings,
/*dhcpv6:*/ 0
);
free(optstr);
}
if (udhcp_read_interface(client_data.interface,
&client_data.ifindex,
if (udhcp_read_interface(client_config.interface,
&client_config.ifindex,
NULL,
client_data.client_mac)
client_config.client_mac)
) {
return 1;
}
clientid_mac_ptr = NULL;
if (!(opt & OPT_C) && !udhcp_find_option(client_data.options, DHCP_CLIENT_ID)) {
if (!(opt & OPT_C) && !udhcp_find_option(client_config.options, DHCP_CLIENT_ID)) {
/* not suppressed and not set, set the default client ID */
client_data.clientid = alloc_dhcp_option(DHCP_CLIENT_ID, "", 7);
client_data.clientid[OPT_DATA] = 1; /* type: ethernet */
clientid_mac_ptr = client_data.clientid + OPT_DATA+1;
memcpy(clientid_mac_ptr, client_data.client_mac, 6);
client_config.clientid = alloc_dhcp_option(DHCP_CLIENT_ID, "", 7);
client_config.clientid[OPT_DATA] = 1; /* type: ethernet */
clientid_mac_ptr = client_config.clientid + OPT_DATA+1;
memcpy(clientid_mac_ptr, client_config.client_mac, 6);
}
if (str_V[0] != '\0') {
// can drop -V, str_V, client_data.vendorclass,
// can drop -V, str_V, client_config.vendorclass,
// but need to add "vendor" to the list of recognized
// string opts for this to work;
// and need to tweak add_client_options() too...
// ...so the question is, should we?
//bb_error_msg("option -V VENDOR is deprecated, use -x vendor:VENDOR");
client_data.vendorclass = alloc_dhcp_option(DHCP_VENDOR, str_V, 0);
client_config.vendorclass = alloc_dhcp_option(DHCP_VENDOR, str_V, 0);
}
#if !BB_MMU
@@ -1389,14 +1386,18 @@ int udhcpc_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_data.pidfile);
write_pidfile(client_config.pidfile);
/* Goes to stdout (unless NOMMU) and possibly syslog */
bb_info_msg("started, v"BB_VER);
bb_error_msg("started, v"BB_VER);
/* Set up the signal pipe */
udhcp_sp_setup();
/* We want random_xid to be random... */
srand(monotonic_us());
client_data.state = INIT_SELECTING;
state = INIT_SELECTING;
udhcp_run_script(NULL, "deconfig");
change_listen_mode(LISTEN_RAW);
packet_num = 0;
@@ -1414,16 +1415,16 @@ int udhcpc_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", client_data.sockfd, client_data.listen_mode);
//bb_error_msg("sockfd:%d, listen_mode:%d", sockfd, listen_mode);
/* Was opening raw or udp socket here
* if (client_data.listen_mode != LISTEN_NONE && client_data.sockfd < 0),
* if (listen_mode != LISTEN_NONE && 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, client_data.sockfd);
udhcp_sp_fd_set(pfds, sockfd);
tv = timeout - already_waited_sec;
retval = 0;
@@ -1452,20 +1453,20 @@ int udhcpc_main(int argc UNUSED_PARAM, char **argv)
* or if the status of the bridge changed).
* Refresh ifindex and client_mac:
*/
if (udhcp_read_interface(client_data.interface,
&client_data.ifindex,
if (udhcp_read_interface(client_config.interface,
&client_config.ifindex,
NULL,
client_data.client_mac)
client_config.client_mac)
) {
goto ret0; /* iface is gone? */
}
if (clientid_mac_ptr)
memcpy(clientid_mac_ptr, client_data.client_mac, 6);
memcpy(clientid_mac_ptr, client_config.client_mac, 6);
/* We will restart the wait in any case */
already_waited_sec = 0;
switch (client_data.state) {
switch (state) {
case INIT_SELECTING:
if (!discover_retries || packet_num < discover_retries) {
if (packet_num == 0)
@@ -1480,20 +1481,14 @@ int udhcpc_main(int argc UNUSED_PARAM, char **argv)
udhcp_run_script(NULL, "leasefail");
#if BB_MMU /* -b is not supported on NOMMU */
if (opt & OPT_b) { /* background if no lease */
bb_info_msg("no lease, forking to background");
bb_error_msg("no lease, forking to background");
client_background();
/* do not background again! */
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_.
*/
opt = ((opt & ~OPT_b) | OPT_f);
} else
#endif
if (opt & OPT_n) { /* abort if no lease */
bb_info_msg("no lease, failing");
bb_error_msg("no lease, failing");
retval = 1;
goto ret;
}
@@ -1514,12 +1509,12 @@ int udhcpc_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);
client_data.state = INIT_SELECTING;
state = INIT_SELECTING;
goto leasefail;
case BOUND:
/* 1/2 lease passed, enter renewing state */
client_data.state = RENEWING;
client_data.first_secs = 0; /* make secs field count from 0 */
state = RENEWING;
client_config.first_secs = 0; /* make secs field count from 0 */
change_listen_mode(LISTEN_KERNEL);
log1("entering renew state");
/* fall right through */
@@ -1555,7 +1550,7 @@ int udhcpc_main(int argc UNUSED_PARAM, char **argv)
}
/* Timed out or error, enter rebinding state */
log1("entering rebinding state");
client_data.state = REBINDING;
state = REBINDING;
/* fall right through */
case REBINDING:
/* Switch to bcast receive */
@@ -1569,10 +1564,10 @@ int udhcpc_main(int argc UNUSED_PARAM, char **argv)
continue;
}
/* Timed out, enter init state */
bb_info_msg("lease lost, entering init state");
bb_error_msg("lease lost, entering init state");
udhcp_run_script(NULL, "deconfig");
client_data.state = INIT_SELECTING;
client_data.first_secs = 0; /* make secs field count from 0 */
state = INIT_SELECTING;
client_config.first_secs = 0; /* make secs field count from 0 */
/*timeout = 0; - already is */
packet_num = 0;
continue;
@@ -1588,10 +1583,10 @@ int udhcpc_main(int argc UNUSED_PARAM, char **argv)
/* Is it a signal? */
switch (udhcp_sp_read()) {
case SIGUSR1:
client_data.first_secs = 0; /* make secs field count from 0 */
client_config.first_secs = 0; /* make secs field count from 0 */
already_waited_sec = 0;
perform_renew();
if (client_data.state == RENEW_REQUESTED) {
if (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
@@ -1614,7 +1609,7 @@ int udhcpc_main(int argc UNUSED_PARAM, char **argv)
timeout = INT_MAX;
continue;
case SIGTERM:
bb_info_msg("received %s", "SIGTERM");
bb_error_msg("received %s", "SIGTERM");
goto ret0;
}
@@ -1626,15 +1621,15 @@ int udhcpc_main(int argc UNUSED_PARAM, char **argv)
int len;
/* A packet is ready, read it */
if (client_data.listen_mode == LISTEN_KERNEL)
len = udhcp_recv_kernel_packet(&packet, client_data.sockfd);
if (listen_mode == LISTEN_KERNEL)
len = udhcp_recv_kernel_packet(&packet, sockfd);
else
len = udhcp_recv_raw_packet(&packet, client_data.sockfd);
len = udhcp_recv_raw_packet(&packet, 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(client_data.listen_mode); /* just close and reopen */
change_listen_mode(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.
@@ -1652,7 +1647,7 @@ int udhcpc_main(int argc UNUSED_PARAM, char **argv)
/* Ignore packets that aren't for us */
if (packet.hlen != 6
|| memcmp(packet.chaddr, client_data.client_mac, 6) != 0
|| memcmp(packet.chaddr, client_config.client_mac, 6) != 0
) {
//FIXME: need to also check that last 10 bytes are zero
log1("chaddr does not match, ignoring packet"); // log2?
@@ -1661,11 +1656,11 @@ int udhcpc_main(int argc UNUSED_PARAM, char **argv)
message = udhcp_get_option(&packet, DHCP_MESSAGE_TYPE);
if (message == NULL) {
bb_info_msg("no message type option, ignoring packet");
bb_error_msg("no message type option, ignoring packet");
continue;
}
switch (client_data.state) {
switch (state) {
case INIT_SELECTING:
/* Must be a DHCPOFFER */
if (*message == DHCPOFFER) {
@@ -1690,7 +1685,7 @@ int udhcpc_main(int argc UNUSED_PARAM, char **argv)
* might work too.
* "Next server" and router are definitely wrong ones to use, though...
*/
/* We used to ignore packets without DHCP_SERVER_ID.
/* We used to ignore pcakets without DHCP_SERVER_ID.
* I've got user reports from people who run "address-less" servers.
* They either supply DHCP_SERVER_ID of 0.0.0.0 or don't supply it at all.
* They say ISC DHCP client supports this case.
@@ -1698,7 +1693,7 @@ int udhcpc_main(int argc UNUSED_PARAM, char **argv)
server_addr = 0;
temp = udhcp_get_option32(&packet, DHCP_SERVER_ID);
if (!temp) {
bb_info_msg("no server ID, using 0.0.0.0");
bb_error_msg("no server ID, using 0.0.0.0");
} else {
/* it IS unaligned sometimes, don't "optimize" */
move_from_unaligned32(server_addr, temp);
@@ -1707,7 +1702,7 @@ int udhcpc_main(int argc UNUSED_PARAM, char **argv)
requested_ip = packet.yiaddr;
/* enter requesting state */
client_data.state = REQUESTING;
state = REQUESTING;
timeout = 0;
packet_num = 0;
already_waited_sec = 0;
@@ -1725,7 +1720,7 @@ int udhcpc_main(int argc UNUSED_PARAM, char **argv)
temp = udhcp_get_option32(&packet, DHCP_LEASE_TIME);
if (!temp) {
bb_info_msg("no lease time with ACK, using 1 hour lease");
bb_error_msg("no lease time with ACK, using 1 hour lease");
lease_seconds = 60 * 60;
} else {
/* it IS unaligned sometimes, don't "optimize" */
@@ -1754,19 +1749,19 @@ int udhcpc_main(int argc UNUSED_PARAM, char **argv)
if (!arpping(packet.yiaddr,
NULL,
(uint32_t) 0,
client_data.client_mac,
client_data.interface,
client_config.client_mac,
client_config.interface,
arpping_ms)
) {
bb_info_msg("offered address is in use "
bb_error_msg("offered address is in use "
"(got ARP reply), declining");
send_decline(/*xid,*/ server_addr, packet.yiaddr);
if (client_data.state != REQUESTING)
if (state != REQUESTING)
udhcp_run_script(NULL, "deconfig");
change_listen_mode(LISTEN_RAW);
client_data.state = INIT_SELECTING;
client_data.first_secs = 0; /* make secs field count from 0 */
state = INIT_SELECTING;
client_config.first_secs = 0; /* make secs field count from 0 */
requested_ip = 0;
timeout = tryagain_timeout;
packet_num = 0;
@@ -1777,12 +1772,12 @@ int udhcpc_main(int argc UNUSED_PARAM, char **argv)
#endif
/* enter bound state */
temp_addr.s_addr = packet.yiaddr;
bb_info_msg("lease of %s obtained, lease time %u",
bb_error_msg("lease of %s obtained, lease time %u",
inet_ntoa(temp_addr), (unsigned)lease_seconds);
requested_ip = packet.yiaddr;
start = monotonic_sec();
udhcp_run_script(&packet, client_data.state == REQUESTING ? "bound" : "renew");
udhcp_run_script(&packet, state == REQUESTING ? "bound" : "renew");
already_waited_sec = (unsigned)monotonic_sec() - start;
timeout = lease_seconds / 2;
if ((unsigned)timeout < already_waited_sec) {
@@ -1790,7 +1785,7 @@ int udhcpc_main(int argc UNUSED_PARAM, char **argv)
timeout = already_waited_sec = 0;
}
client_data.state = BOUND;
state = BOUND;
change_listen_mode(LISTEN_NONE);
if (opt & OPT_q) { /* quit after lease */
goto ret0;
@@ -1830,14 +1825,14 @@ int udhcpc_main(int argc UNUSED_PARAM, char **argv)
goto non_matching_svid;
}
/* return to init state */
bb_info_msg("received %s", "DHCP NAK");
bb_error_msg("received %s", "DHCP NAK");
udhcp_run_script(&packet, "nak");
if (client_data.state != REQUESTING)
if (state != REQUESTING)
udhcp_run_script(NULL, "deconfig");
change_listen_mode(LISTEN_RAW);
sleep(3); /* avoid excessive network traffic */
client_data.state = INIT_SELECTING;
client_data.first_secs = 0; /* make secs field count from 0 */
state = INIT_SELECTING;
client_config.first_secs = 0; /* make secs field count from 0 */
requested_ip = 0;
timeout = 0;
packet_num = 0;
@@ -1855,7 +1850,7 @@ int udhcpc_main(int argc UNUSED_PARAM, char **argv)
perform_release(server_addr, requested_ip);
retval = 0;
ret:
/*if (client_data.pidfile) - remove_pidfile has its own check */
remove_pidfile(client_data.pidfile);
/*if (client_config.pidfile) - remove_pidfile has its own check */
remove_pidfile(client_config.pidfile);
return retval;
}
Loaded 100 of 150 files, more files were not shown because too many files have changed in this diff. Show more