From 1385899416a4396385ad421ae1f532be7103738a Mon Sep 17 00:00:00 2001 From: Denis Vlasenko Date: Sun, 8 Oct 2006 12:49:22 +0000 Subject: [PATCH] attempt to regularize atoi mess. --- TODO | 3 - applets/applets.c | 4 +- archival/cpio.c | 2 +- archival/libunarchive/Kbuild | 2 +- archival/libunarchive/get_header_ar.c | 12 +- archival/libunarchive/get_header_tar.c | 45 ++-- archival/libunarchive/get_header_tar_bz2.c | 6 +- archival/libunarchive/get_header_tar_gz.c | 6 +- archival/libunarchive/get_header_tar_lzma.c | 5 +- archival/libunarchive/seek_by_jump.c | 2 +- .../{seek_by_char.c => seek_by_read.c} | 8 +- archival/rpm.c | 2 +- archival/tar.c | 4 +- archival/unzip.c | 11 +- console-tools/chvt.c | 7 +- console-tools/deallocvt.c | 19 +- console-tools/openvt.c | 12 +- console-tools/setkeycodes.c | 13 +- console-tools/setlogcons.c | 2 +- coreutils/cal.c | 4 +- coreutils/cut.c | 16 +- coreutils/dd.c | 12 +- coreutils/diff.c | 2 +- coreutils/du.c | 2 +- coreutils/fold.c | 2 +- coreutils/head.c | 36 ++- coreutils/ls.c | 8 +- coreutils/mknod.c | 9 +- coreutils/nice.c | 2 +- coreutils/printf.c | 40 ++-- coreutils/sleep.c | 12 +- coreutils/stty.c | 36 ++- coreutils/tail.c | 4 +- coreutils/uniq.c | 2 +- coreutils/usleep.c | 2 +- coreutils/watch.c | 2 +- debianutils/run_parts.c | 44 ++-- debianutils/start_stop_daemon.c | 2 +- editors/patch.c | 2 +- findutils/find.c | 45 ++-- findutils/xargs.c | 4 +- include/libbb.h | 68 ++++-- include/unarchive.h | 2 +- init/halt.c | 2 +- libbb/Kbuild | 6 +- libbb/loop.c | 60 +++-- libbb/parse_number.c | 50 ----- libbb/safe_strtol.c | 102 ++++++--- libbb/xatol.c | 210 ++++++++++++++++++ libbb/xgetlarg.c | 32 --- libbb/xgetularg.c | 127 ----------- loginutils/addgroup.c | 5 +- loginutils/getty.c | 17 +- loginutils/sulogin.c | 6 +- loginutils/vlock.c | 2 +- miscutils/adjtimex.c | 12 +- miscutils/crond.c | 8 +- miscutils/dc.c | 2 +- miscutils/hdparm.c | 6 +- miscutils/makedevs.c | 8 +- miscutils/mt.c | 2 +- miscutils/strings.c | 5 +- miscutils/watchdog.c | 4 +- modutils/insmod.c | 2 +- networking/arping.c | 8 +- networking/ftpgetput.c | 14 +- networking/httpd.c | 2 +- networking/ifconfig.c | 3 +- networking/inetd.c | 29 +-- networking/interface.c | 2 +- networking/ipcalc.c | 48 ++-- networking/nc.c | 22 +- networking/ping.c | 16 +- networking/ping6.c | 16 +- networking/route.c | 14 +- networking/telnetd.c | 4 +- networking/tftp.c | 4 +- networking/traceroute.c | 74 ++---- networking/udhcp/dhcpc.c | 4 +- networking/udhcp/files.c | 8 +- networking/vconfig.c | 10 +- networking/wget.c | 10 +- procps/kill.c | 4 +- procps/pidof.c | 10 +- procps/renice.c | 18 +- procps/top.c | 8 +- runit/chpst.c | 42 ++-- sysklogd/klogd.c | 3 +- sysklogd/logger.c | 9 +- sysklogd/syslogd.c | 14 +- util-linux/dmesg.c | 4 +- util-linux/fbset.c | 30 +-- util-linux/fdisk.c | 13 +- util-linux/hexdump.c | 4 +- util-linux/ipcs.c | 2 +- util-linux/losetup.c | 4 +- util-linux/mount.c | 2 +- util-linux/readprofile.c | 6 +- 98 files changed, 803 insertions(+), 849 deletions(-) rename archival/libunarchive/{seek_by_char.c => seek_by_read.c} (66%) delete mode 100644 libbb/parse_number.c create mode 100644 libbb/xatol.c delete mode 100644 libbb/xgetlarg.c delete mode 100644 libbb/xgetularg.c diff --git a/TODO b/TODO index 844a504d7..937302522 100644 --- a/TODO +++ b/TODO @@ -295,9 +295,6 @@ Minor stuff: -> fprintf(stderr, "unalias: %s not found\n", *argptr); --- possible code duplication ingroup() and is_a_group_member() ---- - unify itoa: netstat.c, hush.c, lash.c, msh.c - Put one single, robust version into e.g. safe_strtol.c --- Move __get_hz() to a better place and (re)use it in route.c, ash.c, msh.c --- diff --git a/applets/applets.c b/applets/applets.c index b1f580953..5d8b80881 100644 --- a/applets/applets.c +++ b/applets/applets.c @@ -264,8 +264,8 @@ static void parse_config_file(void) sct->m_uid = strtoul(s, &e2, 10); if (*e2 || (s == e2)) { - struct passwd *pwd; - if (!(pwd = getpwnam(s))) { + struct passwd *pwd = getpwnam(s); + if (!pwd) { parse_error("user"); } sct->m_uid = pwd->pw_uid; diff --git a/archival/cpio.c b/archival/cpio.c index d0d3288ff..751e87952 100644 --- a/archival/cpio.c +++ b/archival/cpio.c @@ -35,7 +35,7 @@ int cpio_main(int argc, char **argv) /* Initialise */ archive_handle = init_handle(); archive_handle->src_fd = STDIN_FILENO; - archive_handle->seek = seek_by_char; + archive_handle->seek = seek_by_read; archive_handle->flags = ARCHIVE_EXTRACT_NEWER | ARCHIVE_PRESERVE_DATE; opt = getopt32(argc, argv, "ituvF:dm", &cpio_filename); diff --git a/archival/libunarchive/Kbuild b/archival/libunarchive/Kbuild index c5f1bfbfe..4e1454184 100644 --- a/archival/libunarchive/Kbuild +++ b/archival/libunarchive/Kbuild @@ -21,7 +21,7 @@ lib-y:= \ \ archive_xread_all_eof.o \ \ - seek_by_char.o \ + seek_by_read.o \ seek_by_jump.o \ \ data_align.o \ diff --git a/archival/libunarchive/get_header_ar.c b/archival/libunarchive/get_header_ar.c index cabb4101b..7372ada32 100644 --- a/archival/libunarchive/get_header_ar.c +++ b/archival/libunarchive/get_header_ar.c @@ -46,14 +46,14 @@ char get_header_ar(archive_handle_t *archive_handle) /* align the headers based on the header magic */ if ((ar.formatted.magic[0] != '`') || (ar.formatted.magic[1] != '\n')) { - bb_error_msg_and_die("Invalid ar header"); + bb_error_msg_and_die("invalid ar header"); } - typed->mode = strtol(ar.formatted.mode, NULL, 8); - typed->mtime = atoi(ar.formatted.date); - typed->uid = atoi(ar.formatted.uid); - typed->gid = atoi(ar.formatted.gid); - typed->size = atoi(ar.formatted.size); + typed->mode = xstrtoul(ar.formatted.mode, 8); + typed->mtime = xatou(ar.formatted.date); + typed->uid = xatou(ar.formatted.uid); + typed->gid = xatou(ar.formatted.gid); + typed->size = xatoul(ar.formatted.size); /* long filenames have '/' as the first character */ if (ar.formatted.name[0] == '/') { diff --git a/archival/libunarchive/get_header_tar.c b/archival/libunarchive/get_header_tar.c index 0c622f44a..d3cd96d0c 100644 --- a/archival/libunarchive/get_header_tar.c +++ b/archival/libunarchive/get_header_tar.c @@ -62,10 +62,10 @@ char get_header_tar(archive_handle_t *archive_handle) * Read until the end to empty the pipe from gz or bz2 */ while (full_read(archive_handle->src_fd, tar.raw, 512) == 512); - return(EXIT_FAILURE); + return EXIT_FAILURE; } end = 1; - return(EXIT_SUCCESS); + return EXIT_SUCCESS; } end = 0; @@ -76,19 +76,18 @@ char get_header_tar(archive_handle_t *archive_handle) #ifdef CONFIG_FEATURE_TAR_OLDGNU_COMPATIBILITY if (strncmp(tar.formatted.magic, "\0\0\0\0\0", 5) != 0) #endif - bb_error_msg_and_die("Invalid tar magic"); + bb_error_msg_and_die("invalid tar magic"); } /* Do checksum on headers */ for (i = 0; i < 148 ; i++) { sum += tar.raw[i]; } sum += ' ' * 8; - for (i = 156; i < 512 ; i++) { + for (i = 156; i < 512 ; i++) { sum += tar.raw[i]; } - if (sum != strtol(tar.formatted.chksum, NULL, 8)) { - bb_error_msg("Invalid tar header checksum"); - return(EXIT_FAILURE); + if (sum != xstrtoul(tar.formatted.chksum, 8)) { + bb_error_msg_and_die("invalid tar header checksum"); } #ifdef CONFIG_FEATURE_TAR_GNU_EXTENSIONS @@ -102,8 +101,7 @@ char get_header_tar(archive_handle_t *archive_handle) } else #endif { - file_header->name = xstrndup(tar.formatted.name,100); - + file_header->name = xstrndup(tar.formatted.name, 100); if (tar.formatted.prefix[0]) { char *temp = file_header->name; file_header->name = concat_path_file(tar.formatted.prefix, temp); @@ -111,17 +109,18 @@ char get_header_tar(archive_handle_t *archive_handle) } } - file_header->uid = strtol(tar.formatted.uid, NULL, 8); - file_header->gid = strtol(tar.formatted.gid, NULL, 8); - file_header->size = strtol(tar.formatted.size, NULL, 8); - file_header->mtime = strtol(tar.formatted.mtime, NULL, 8); - file_header->link_name = (tar.formatted.linkname[0] != '\0') ? - xstrdup(tar.formatted.linkname) : NULL; - file_header->device = makedev(strtol(tar.formatted.devmajor, NULL, 8), - strtol(tar.formatted.devminor, NULL, 8)); + file_header->uid = xstrtoul(tar.formatted.uid, 8); + file_header->gid = xstrtoul(tar.formatted.gid, 8); + // TODO: LFS support + file_header->size = xstrtoul(tar.formatted.size, 8); + file_header->mtime = xstrtoul(tar.formatted.mtime, 8); + file_header->link_name = tar.formatted.linkname[0] ? + xstrdup(tar.formatted.linkname) : NULL; + file_header->device = makedev(xstrtoul(tar.formatted.devmajor, 8), + xstrtoul(tar.formatted.devminor, 8)); /* Set bits 0-11 of the files mode */ - file_header->mode = 07777 & strtol(tar.formatted.mode, NULL, 8); + file_header->mode = 07777 & xstrtoul(tar.formatted.mode, 8); /* Set bits 12-15 of the files mode */ switch (tar.formatted.typeflag) { @@ -161,7 +160,7 @@ char get_header_tar(archive_handle_t *archive_handle) xread(archive_handle->src_fd, longname, file_header->size); archive_handle->offset += file_header->size; - return(get_header_tar(archive_handle)); + return get_header_tar(archive_handle); } case 'K': { linkname = xzalloc(file_header->size + 1); @@ -169,7 +168,7 @@ char get_header_tar(archive_handle_t *archive_handle) archive_handle->offset += file_header->size; file_header->name = linkname; - return(get_header_tar(archive_handle)); + return get_header_tar(archive_handle); } case 'D': /* GNU dump dir */ case 'M': /* Continuation of multi volume archive*/ @@ -179,10 +178,10 @@ char get_header_tar(archive_handle_t *archive_handle) #endif case 'g': /* pax global header */ case 'x': /* pax extended header */ - bb_error_msg("Ignoring extension type %c", tar.formatted.typeflag); + bb_error_msg("ignoring extension type %c", tar.formatted.typeflag); break; default: - bb_error_msg("Unknown typeflag: 0x%x", tar.formatted.typeflag); + bb_error_msg("unknown typeflag: 0x%x", tar.formatted.typeflag); } { /* Strip trailing '/' in directories */ /* Must be done after mode is set as '/' is used to check if its a directory */ @@ -204,5 +203,5 @@ char get_header_tar(archive_handle_t *archive_handle) free(file_header->link_name); - return(EXIT_SUCCESS); + return EXIT_SUCCESS; } diff --git a/archival/libunarchive/get_header_tar_bz2.c b/archival/libunarchive/get_header_tar_bz2.c index a8b630814..e3cb328fc 100644 --- a/archival/libunarchive/get_header_tar_bz2.c +++ b/archival/libunarchive/get_header_tar_bz2.c @@ -16,12 +16,12 @@ char get_header_tar_bz2(archive_handle_t *archive_handle) { /* Cant lseek over pipe's */ - archive_handle->seek = seek_by_char; + archive_handle->seek = seek_by_read; archive_handle->src_fd = open_transformer(archive_handle->src_fd, uncompressStream); archive_handle->offset = 0; - while (get_header_tar(archive_handle) == EXIT_SUCCESS); + while (get_header_tar(archive_handle) == EXIT_SUCCESS) /**/; /* Can only do one file at a time */ - return(EXIT_FAILURE); + return EXIT_FAILURE; } diff --git a/archival/libunarchive/get_header_tar_gz.c b/archival/libunarchive/get_header_tar_gz.c index 24e4f9c9f..af059a187 100644 --- a/archival/libunarchive/get_header_tar_gz.c +++ b/archival/libunarchive/get_header_tar_gz.c @@ -13,7 +13,7 @@ char get_header_tar_gz(archive_handle_t *archive_handle) unsigned char magic[2]; /* Cant lseek over pipe's */ - archive_handle->seek = seek_by_char; + archive_handle->seek = seek_by_read; xread(archive_handle->src_fd, &magic, 2); if ((magic[0] != 0x1f) || (magic[1] != 0x8b)) { @@ -24,8 +24,8 @@ char get_header_tar_gz(archive_handle_t *archive_handle) archive_handle->src_fd = open_transformer(archive_handle->src_fd, inflate_gunzip); archive_handle->offset = 0; - while (get_header_tar(archive_handle) == EXIT_SUCCESS); + while (get_header_tar(archive_handle) == EXIT_SUCCESS) /**/; /* Can only do one file at a time */ - return(EXIT_FAILURE); + return EXIT_FAILURE; } diff --git a/archival/libunarchive/get_header_tar_lzma.c b/archival/libunarchive/get_header_tar_lzma.c index e38583fef..06b8daa0f 100644 --- a/archival/libunarchive/get_header_tar_lzma.c +++ b/archival/libunarchive/get_header_tar_lzma.c @@ -11,13 +11,12 @@ char get_header_tar_lzma(archive_handle_t * archive_handle) { /* Can't lseek over pipes */ - archive_handle->seek = seek_by_char; + archive_handle->seek = seek_by_read; archive_handle->src_fd = open_transformer(archive_handle->src_fd, unlzma); archive_handle->offset = 0; - while (get_header_tar(archive_handle) == EXIT_SUCCESS); + while (get_header_tar(archive_handle) == EXIT_SUCCESS) /**/; /* Can only do one file at a time */ return EXIT_FAILURE; } - diff --git a/archival/libunarchive/seek_by_jump.c b/archival/libunarchive/seek_by_jump.c index 231360fa3..e1917dd2a 100644 --- a/archival/libunarchive/seek_by_jump.c +++ b/archival/libunarchive/seek_by_jump.c @@ -16,7 +16,7 @@ void seek_by_jump(const archive_handle_t *archive_handle, const unsigned int amo if (lseek(archive_handle->src_fd, (off_t) amount, SEEK_CUR) == (off_t) -1) { #ifdef CONFIG_FEATURE_UNARCHIVE_TAPE if (errno == ESPIPE) { - seek_by_char(archive_handle, amount); + seek_by_read(archive_handle, amount); } else #endif bb_perror_msg_and_die("Seek failure"); diff --git a/archival/libunarchive/seek_by_char.c b/archival/libunarchive/seek_by_read.c similarity index 66% rename from archival/libunarchive/seek_by_char.c rename to archival/libunarchive/seek_by_read.c index f4d8c2f2b..03cbb9ecc 100644 --- a/archival/libunarchive/seek_by_char.c +++ b/archival/libunarchive/seek_by_read.c @@ -8,14 +8,10 @@ #include "unarchive.h" #include "libbb.h" - - -/* If we are reading through a pipe(), or from stdin then we cant lseek, +/* If we are reading through a pipe(), or from stdin then we cant lseek, * we must read and discard the data to skip over it. - * - * TODO: rename to seek_by_read */ -void seek_by_char(const archive_handle_t *archive_handle, const unsigned int jump_size) +void seek_by_read(const archive_handle_t *archive_handle, const unsigned int jump_size) { if (jump_size) { bb_copyfd_size(archive_handle->src_fd, -1, jump_size); diff --git a/archival/rpm.c b/archival/rpm.c index dc37e0edb..448a479a0 100644 --- a/archival/rpm.c +++ b/archival/rpm.c @@ -173,7 +173,7 @@ static void extract_cpio_gz(int fd) { /* Initialise */ archive_handle = init_handle(); - archive_handle->seek = seek_by_char; + archive_handle->seek = seek_by_read; //archive_handle->action_header = header_list; archive_handle->action_data = data_extract_all; archive_handle->flags |= ARCHIVE_PRESERVE_DATE; diff --git a/archival/tar.c b/archival/tar.c index 3775598cc..b2ae3b2af 100644 --- a/archival/tar.c +++ b/archival/tar.c @@ -541,7 +541,7 @@ static llist_t *append_file_list_to_list(llist_t *list) static char get_header_tar_Z(archive_handle_t *archive_handle) { /* Cant lseek over pipe's */ - archive_handle->seek = seek_by_char; + archive_handle->seek = seek_by_read; /* do the decompression, and cleanup */ if (xread_char(archive_handle->src_fd) != 0x1f || @@ -805,7 +805,7 @@ int tar_main(int argc, char **argv) if ((tar_filename[0] == '-') && (tar_filename[1] == '\0')) { tar_handle->src_fd = fileno(tar_stream); - tar_handle->seek = seek_by_char; + tar_handle->seek = seek_by_read; } else { tar_handle->src_fd = xopen3(tar_filename, flags, 0666); } diff --git a/archival/unzip.c b/archival/unzip.c index f63925739..f70baebf9 100644 --- a/archival/unzip.c +++ b/archival/unzip.c @@ -51,11 +51,12 @@ typedef union { } formatted ATTRIBUTE_PACKED; } zip_header_t; +/* This one never works with LARGEFILE-sized skips */ static void unzip_skip(int fd, off_t skip) { if (lseek(fd, skip, SEEK_CUR) == (off_t)-1) { if ((errno != ESPIPE) || (bb_copyfd_size(fd, -1, skip) != skip)) { - bb_error_msg_and_die("Seek failure"); + bb_error_msg_and_die("seek failure"); } } } @@ -65,7 +66,7 @@ static void unzip_create_leading_dirs(char *fn) /* Create all leading directories */ char *name = xstrdup(fn); if (bb_make_directory(dirname(name), 0777, FILEUTILS_RECUR)) { - bb_error_msg_and_die("Exiting"); /* bb_make_directory is noisy */ + bb_error_msg_and_die("exiting"); /* bb_make_directory is noisy */ } free(name); } @@ -76,7 +77,7 @@ static int unzip_extract(zip_header_t *zip_header, int src_fd, int dst_fd) /* Method 0 - stored (not compressed) */ int size = zip_header->formatted.ucmpsize; if (size && (bb_copyfd_size(src_fd, dst_fd, size) != size)) { - bb_error_msg_and_die("Cannot complete extraction"); + bb_error_msg_and_die("cannot complete extraction"); } } else { @@ -86,12 +87,12 @@ static int unzip_extract(zip_header_t *zip_header, int src_fd, int dst_fd) inflate_cleanup(); /* Validate decompression - crc */ if (zip_header->formatted.crc32 != (gunzip_crc ^ 0xffffffffL)) { - bb_error_msg("Invalid compressed data--crc error"); + bb_error_msg("invalid compressed data--%s error", "crc"); return 1; } /* Validate decompression - size */ if (zip_header->formatted.ucmpsize != gunzip_bytes_out) { - bb_error_msg("Invalid compressed data--length error"); + bb_error_msg("invalid compressed data--%s error", "length"); return 1; } } diff --git a/console-tools/chvt.c b/console-tools/chvt.c index aff66e007..bbc5a9c31 100644 --- a/console-tools/chvt.c +++ b/console-tools/chvt.c @@ -7,11 +7,6 @@ * Licensed under GPLv2 or later, see file LICENSE in this tarball for details. */ -#include -#include -#include -#include -#include #include "busybox.h" /* From */ @@ -29,7 +24,7 @@ int chvt_main(int argc, char **argv) } fd = get_console_fd(); - num = bb_xgetlarg(argv[1], 10, 0, INT_MAX); + num = xatoul_range(argv[1], 1, 63); if ((-1 == ioctl(fd, VT_ACTIVATE, num)) || (-1 == ioctl(fd, VT_WAITACTIVE, num))) { bb_perror_msg_and_die("ioctl"); diff --git a/console-tools/deallocvt.c b/console-tools/deallocvt.c index b2e8e2bef..cd581b1c8 100644 --- a/console-tools/deallocvt.c +++ b/console-tools/deallocvt.c @@ -10,11 +10,6 @@ /* no options, no getopt */ -#include -#include -#include -#include -#include #include "busybox.h" /* From */ @@ -26,15 +21,13 @@ int deallocvt_main(int argc, char *argv[]) int num = 0; switch (argc) { - case 2: - if ((num = bb_xgetlarg(argv[1], 10, 0, INT_MAX)) == 0) { - bb_error_msg_and_die("0: illegal VT number"); - } + case 2: + num = xatoul_range(argv[1], 1, 63); /* Fallthrough */ - case 1: - break; - default: - bb_show_usage(); + case 1: + break; + default: + bb_show_usage(); } if (-1 == ioctl(get_console_fd(), VT_DISALLOCATE, num)) { diff --git a/console-tools/openvt.c b/console-tools/openvt.c index 0c0cef23c..f1cf5645b 100644 --- a/console-tools/openvt.c +++ b/console-tools/openvt.c @@ -10,14 +10,6 @@ /* getopt not needed */ -#include -#include -#include -#include -#include -#include -#include - #include "busybox.h" int openvt_main(int argc, char **argv) @@ -29,8 +21,8 @@ int openvt_main(int argc, char **argv) if (argc < 3) { bb_show_usage(); } - /* check for Illegal vt number: < 1 or > 12 */ - sprintf(vtname, VC_FORMAT, (int)bb_xgetlarg(argv[1], 10, 1, 12)); + /* check for illegal vt number: < 1 or > 63 */ + sprintf(vtname, VC_FORMAT, (int)xatoul_range(argv[1], 1, 63)); if (fork() == 0) { /* leave current vt */ diff --git a/console-tools/setkeycodes.c b/console-tools/setkeycodes.c index 607b8c785..d82525786 100644 --- a/console-tools/setkeycodes.c +++ b/console-tools/setkeycodes.c @@ -27,7 +27,6 @@ enum { extern int setkeycodes_main(int argc, char** argv) { - char *ep; int fd, sc; struct kbkeycode a; @@ -38,19 +37,13 @@ setkeycodes_main(int argc, char** argv) fd = get_console_fd(); while (argc > 2) { - a.keycode = atoi(argv[2]); - a.scancode = sc = strtol(argv[1], &ep, 16); - if (*ep) { - bb_error_msg_and_die("error reading SCANCODE: '%s'", argv[1]); - } + a.keycode = xatoul_range(argv[2], 0, 127); + a.scancode = sc = xstrtoul_range(argv[1], 16, 0, 255); if (a.scancode > 127) { a.scancode -= 0xe000; a.scancode += 128; } - if (a.scancode > 255 || a.keycode > 127) { - bb_error_msg_and_die("SCANCODE or KEYCODE outside bounds"); - } - if (ioctl(fd,KDSETKEYCODE,&a)) { + if (ioctl(fd, KDSETKEYCODE, &a)) { bb_perror_msg_and_die("failed to set SCANCODE %x to KEYCODE %d", sc, a.keycode); } argc -= 2; diff --git a/console-tools/setlogcons.c b/console-tools/setlogcons.c index 90f24ce9c..ae15b9b28 100644 --- a/console-tools/setlogcons.c +++ b/console-tools/setlogcons.c @@ -22,7 +22,7 @@ extern int setlogcons_main(int argc, char **argv) arg.subarg = 0; /* to specified console (current as default) */ if (argc == 2) - arg.subarg = atoi(argv[1]); + arg.subarg = xatoul_range(argv[1], 0, 63); if (ioctl(xopen(VC_1, O_RDONLY), TIOCLINUX, &arg)) bb_perror_msg_and_die("TIOCLINUX"); diff --git a/coreutils/cal.c b/coreutils/cal.c index ef914128c..e2bc5ab12 100644 --- a/coreutils/cal.c +++ b/coreutils/cal.c @@ -112,9 +112,9 @@ int cal_main(int argc, char **argv) } } else { if (argc == 2) { - month = bb_xgetularg10_bnd(*argv++, 1, 12); + month = xatoul_range(*argv++, 1, 12); } - year = bb_xgetularg10_bnd(*argv, 1, 9999); + year = xatoul_range(*argv, 1, 9999); } blank_string(day_headings, sizeof(day_headings) - 7 + 7*julian); diff --git a/coreutils/cut.c b/coreutils/cut.c index 69f28fa8d..7ba947fae 100644 --- a/coreutils/cut.c +++ b/coreutils/cut.c @@ -163,17 +163,7 @@ static void cut_file(FILE * file) } } -static int getval(char *ntok) -{ - char *junk; - int i = strtoul(ntok, &junk, 10); - - if (*junk != '\0' || i < 0) - bb_error_msg_and_die("invalid byte or field list"); - return i; -} - -static const char * const _op_on_field = " only when operating on fields"; +static const char _op_on_field[] = " only when operating on fields"; int cut_main(int argc, char **argv) { @@ -231,7 +221,7 @@ int cut_main(int argc, char **argv) } else if (strlen(ntok) == 0) { s = BOL; } else { - s = getval(ntok); + s = xatoi_u(ntok); /* account for the fact that arrays are zero based, while * the user expects the first char on the line to be char #1 */ if (s != 0) @@ -245,7 +235,7 @@ int cut_main(int argc, char **argv) } else if (strlen(ntok) == 0) { e = EOL; } else { - e = getval(ntok); + e = xatoi_u(ntok); /* if the user specified and end position of 0, that means "til the * end of the line */ if (e == 0) diff --git a/coreutils/dd.c b/coreutils/dd.c index e63244d81..d557ae46d 100644 --- a/coreutils/dd.c +++ b/coreutils/dd.c @@ -62,19 +62,19 @@ int dd_main(int argc, char **argv) for (n = 1; n < argc; n++) { // FIXME: make them capable of eating LARGE numbers if (ENABLE_FEATURE_DD_IBS_OBS && !strncmp("ibs=", argv[n], 4)) { - ibs = bb_xparse_number(argv[n]+4, dd_suffixes); + ibs = xatoul_sfx(argv[n]+4, dd_suffixes); flags |= twobufs_flag; } else if (ENABLE_FEATURE_DD_IBS_OBS && !strncmp("obs=", argv[n], 4)) { - obs = bb_xparse_number(argv[n]+4, dd_suffixes); + obs = xatoul_sfx(argv[n]+4, dd_suffixes); flags |= twobufs_flag; } else if (!strncmp("bs=", argv[n], 3)) - ibs = obs = bb_xparse_number(argv[n]+3, dd_suffixes); + ibs = obs = xatoul_sfx(argv[n]+3, dd_suffixes); else if (!strncmp("count=", argv[n], 6)) - count = bb_xparse_number(argv[n]+6, dd_suffixes); + count = xatoul_sfx(argv[n]+6, dd_suffixes); else if (!strncmp("seek=", argv[n], 5)) - seek = bb_xparse_number(argv[n]+5, dd_suffixes); + seek = xatoul_sfx(argv[n]+5, dd_suffixes); else if (!strncmp("skip=", argv[n], 5)) - skip = bb_xparse_number(argv[n]+5, dd_suffixes); + skip = xatoul_sfx(argv[n]+5, dd_suffixes); else if (!strncmp("if=", argv[n], 3)) infile = argv[n]+3; else if (!strncmp("of=", argv[n], 3)) diff --git a/coreutils/diff.c b/coreutils/diff.c index b30aad5a7..65757d7d1 100644 --- a/coreutils/diff.c +++ b/coreutils/diff.c @@ -1192,7 +1192,7 @@ int diff_main(int argc, char **argv) context = 3; /* This is the default number of lines of context. */ if (cmd_flags & FLAG_U) { - context = bb_xgetlarg(U_opt, 10, 1, INT_MAX); + context = xatoul_range(U_opt, 1, INT_MAX); } argc -= optind; argv += optind; diff --git a/coreutils/du.c b/coreutils/du.c index 1452e5883..f61d978b7 100644 --- a/coreutils/du.c +++ b/coreutils/du.c @@ -215,7 +215,7 @@ int du_main(int argc, char **argv) one_file_system = opt & (1 << 5); /* -x opt */ if((opt & (1 << 6))) { /* -d opt */ - max_print_depth = bb_xgetularg10_bnd(smax_print_depth, 0, INT_MAX); + max_print_depth = xatoi_u(smax_print_depth); } if((opt & (1 << 7))) { /* -l opt */ diff --git a/coreutils/fold.c b/coreutils/fold.c index 3b5be64fe..45f4472e4 100644 --- a/coreutils/fold.c +++ b/coreutils/fold.c @@ -62,7 +62,7 @@ int fold_main(int argc, char **argv) flags = getopt32(argc, argv, "bsw:", &w_opt); if (flags & FLAG_WIDTH) - width = bb_xgetlarg(w_opt, 10, 1, 10000); + width = xatoul_range(w_opt, 1, 10000); argv += optind; if (!*argv) { diff --git a/coreutils/head.c b/coreutils/head.c index 7d5f219d2..060febcf7 100644 --- a/coreutils/head.c +++ b/coreutils/head.c @@ -64,32 +64,30 @@ int head_main(int argc, char **argv) while ((opt = getopt(argc, argv, head_opts)) > 0) { switch (opt) { #if ENABLE_FEATURE_FANCY_HEAD - case 'q': - header_threshhold = INT_MAX; - break; - case 'v': - header_threshhold = -1; - break; - case 'c': - count_bytes = 1; - /* fall through */ + case 'q': + header_threshhold = INT_MAX; + break; + case 'v': + header_threshhold = -1; + break; + case 'c': + count_bytes = 1; + /* fall through */ #endif - case 'n': - p = optarg; + case 'n': + p = optarg; #if !ENABLE_DEBUG_YANK_SUSv2 || ENABLE_FEATURE_FANCY_HEAD - GET_COUNT: + GET_COUNT: #endif #if !ENABLE_FEATURE_FANCY_HEAD - count = bb_xgetularg10(p); + count = xatoul(p); #else - count = bb_xgetularg_bnd_sfx(p, 10, - 0, ULONG_MAX, - head_suffixes); + count = xatoul_sfx(p, head_suffixes); #endif - break; - default: - bb_show_usage(); + break; + default: + bb_show_usage(); } } diff --git a/coreutils/ls.c b/coreutils/ls.c index 8ba4ab758..f34e83ebe 100644 --- a/coreutils/ls.c +++ b/coreutils/ls.c @@ -163,8 +163,8 @@ static int list_single(struct dnode *); static unsigned int all_fmt; #ifdef CONFIG_FEATURE_AUTOWIDTH -static int terminal_width = TERMINAL_WIDTH; -static unsigned short tabstops = COLUMN_GAP; +static unsigned terminal_width = TERMINAL_WIDTH; +static unsigned tabstops = COLUMN_GAP; #else #define tabstops COLUMN_GAP #define terminal_width TERMINAL_WIDTH @@ -915,10 +915,10 @@ int ls_main(int argc, char **argv) #endif ); if (tabstops_str) { - tabstops = atoi(tabstops_str); + tabstops = xatou(tabstops_str); } if (terminal_width_str) { - terminal_width = atoi(terminal_width_str); + terminal_width = xatou(terminal_width_str); } #else opt = getopt32(argc, argv, ls_options diff --git a/coreutils/mknod.c b/coreutils/mknod.c index 9c97b0302..7cc478f17 100644 --- a/coreutils/mknod.c +++ b/coreutils/mknod.c @@ -9,11 +9,8 @@ /* BB_AUDIT SUSv3 N/A -- Matches GNU behavior. */ -#include -#include -#include #include // For makedev -#include + #include "busybox.h" #include "libcoreutils/coreutils.h" @@ -37,8 +34,8 @@ int mknod_main(int argc, char **argv) if ((*name != 'p') && ((argc -= 2) == 2)) { /* Autodetect what the system supports; thexe macros should * optimize out to two constants. */ - dev = makedev(bb_xgetularg10_bnd(argv[2], 0, major(UINT_MAX)), - bb_xgetularg10_bnd(argv[3], 0, minor(UINT_MAX))); + dev = makedev(xatoul_range(argv[2], 0, major(UINT_MAX)), + xatoul_range(argv[3], 0, minor(UINT_MAX))); } if (argc == 2) { diff --git a/coreutils/nice.c b/coreutils/nice.c index 4c54dddbb..a347001e3 100644 --- a/coreutils/nice.c +++ b/coreutils/nice.c @@ -52,7 +52,7 @@ int nice_main(int argc, char **argv) if (argc < 4) { /* Missing priority and/or utility! */ bb_show_usage(); } - adjustment = bb_xgetlarg(argv[1], 10, INT_MIN, INT_MAX); + adjustment = xatoi(argv[1]); argv += 2; } diff --git a/coreutils/printf.c b/coreutils/printf.c index 4a208040f..1511034a1 100644 --- a/coreutils/printf.c +++ b/coreutils/printf.c @@ -30,7 +30,7 @@ %b = print an argument string, interpreting backslash escapes - The `format' argument is re-used as many times as necessary + The 'format' argument is re-used as many times as necessary to convert all of the given arguments. David MacKenzie */ @@ -57,7 +57,7 @@ static void multiconvert(char *arg, void *result, converter convert) fputs(arg, stderr); } -static unsigned long xstrtoul(char *arg) +static unsigned long my_xstrtoul(char *arg) { unsigned long result; @@ -65,14 +65,14 @@ static unsigned long xstrtoul(char *arg) return result; } -static long xstrtol(char *arg) +static long my_xstrtol(char *arg) { long result; multiconvert(arg, &result, (converter)safe_strtol); return result; } -static double xstrtod(char *arg) +static double my_xstrtod(char *arg) { double result; multiconvert(arg, &result, (converter)safe_strtod); @@ -120,13 +120,13 @@ int printf_main(int argc, char **argv) } /* Print the text in FORMAT, using ARGV (with ARGC elements) for - arguments to any `%' directives. + arguments to any '%' directives. Return the number of elements of ARGV used. */ static int print_formatted(char *format, int argc, char **argv) { int save_argc = argc; /* Preserve original value. */ - char *f; /* Pointer into `format'. */ + char *f; /* Pointer into 'format'. */ char *direc_start; /* Start of % directive. */ size_t direc_length; /* Length of % directive. */ int field_width; /* Arg to first '*', or -1 if none. */ @@ -158,7 +158,7 @@ static int print_formatted(char *format, int argc, char **argv) ++f; ++direc_length; if (argc > 0) { - field_width = xstrtoul(*argv); + field_width = my_xstrtoul(*argv); ++argv; --argc; } else @@ -175,7 +175,7 @@ static int print_formatted(char *format, int argc, char **argv) ++f; ++direc_length; if (argc > 0) { - precision = xstrtoul(*argv); + precision = my_xstrtoul(*argv); ++argv; --argc; } else @@ -235,14 +235,14 @@ print_direc(char *start, size_t length, int field_width, int precision, case 'i': if (field_width < 0) { if (precision < 0) - printf(p, xstrtol(argument)); + printf(p, my_xstrtol(argument)); else - printf(p, precision, xstrtol(argument)); + printf(p, precision, my_xstrtol(argument)); } else { if (precision < 0) - printf(p, field_width, xstrtol(argument)); + printf(p, field_width, my_xstrtol(argument)); else - printf(p, field_width, precision, xstrtol(argument)); + printf(p, field_width, precision, my_xstrtol(argument)); } break; @@ -252,14 +252,14 @@ print_direc(char *start, size_t length, int field_width, int precision, case 'X': if (field_width < 0) { if (precision < 0) - printf(p, xstrtoul(argument)); + printf(p, my_xstrtoul(argument)); else - printf(p, precision, xstrtoul(argument)); + printf(p, precision, my_xstrtoul(argument)); } else { if (precision < 0) - printf(p, field_width, xstrtoul(argument)); + printf(p, field_width, my_xstrtoul(argument)); else - printf(p, field_width, precision, xstrtoul(argument)); + printf(p, field_width, precision, my_xstrtoul(argument)); } break; @@ -270,14 +270,14 @@ print_direc(char *start, size_t length, int field_width, int precision, case 'G': if (field_width < 0) { if (precision < 0) - printf(p, xstrtod(argument)); + printf(p, my_xstrtod(argument)); else - printf(p, precision, xstrtod(argument)); + printf(p, precision, my_xstrtod(argument)); } else { if (precision < 0) - printf(p, field_width, xstrtod(argument)); + printf(p, field_width, my_xstrtod(argument)); else - printf(p, field_width, precision, xstrtod(argument)); + printf(p, field_width, precision, my_xstrtod(argument)); } break; diff --git a/coreutils/sleep.c b/coreutils/sleep.c index 3946c3433..e32e2157d 100644 --- a/coreutils/sleep.c +++ b/coreutils/sleep.c @@ -24,7 +24,7 @@ #include "busybox.h" #ifdef CONFIG_FEATURE_FANCY_SLEEP -static const struct suffix_mult sleep_suffixes[] = { +static const struct suffix_mult sfx[] = { { "s", 1 }, { "m", 60 }, { "h", 60*60 }, @@ -46,9 +46,7 @@ int sleep_main(int argc, char **argv) ++argv; duration = 0; do { - duration += bb_xgetularg_bnd_sfx(*argv, 10, - 0, UINT_MAX-duration, - sleep_suffixes); + duration += xatoul_range_sfx(*argv, 0, UINT_MAX-duration, sfx); } while (*++argv); #else /* CONFIG_FEATURE_FANCY_SLEEP */ @@ -57,11 +55,7 @@ int sleep_main(int argc, char **argv) bb_show_usage(); } -#if UINT_MAX == ULONG_MAX - duration = bb_xgetularg10(argv[1]); -#else - duration = bb_xgetularg10_bnd(argv[1], 0, UINT_MAX); -#endif + duration = xatou(argv[1]); #endif /* CONFIG_FEATURE_FANCY_SLEEP */ diff --git a/coreutils/stty.c b/coreutils/stty.c index a41faaf1e..8c16c27a9 100644 --- a/coreutils/stty.c +++ b/coreutils/stty.c @@ -370,9 +370,9 @@ enum { }; /* The width of the screen, for output wrapping */ -static int max_col; +static unsigned max_col = 80; /* default */ /* Current position, to know when to wrap */ -static int current_col; +static unsigned current_col; static const char *device_name = bb_msg_standard_input; /* Return a string that is the printable representation of character CH */ @@ -422,7 +422,7 @@ static tcflag_t *mode_type_flag(unsigned type, const struct termios *mode) static speed_t string_to_baud_or_die(const char *arg) { - return tty_value_to_baud(bb_xparse_number(arg, 0)); + return tty_value_to_baud(xatou(arg)); } static void set_speed_or_die(enum speed_setting type, const char *arg, @@ -556,9 +556,8 @@ static inline void display_window_size(int fancy) {} #endif /* !TIOCGWINSZ */ -static int screen_columns(void) +static int screen_columns_or_die(void) { - int columns; const char *s; #ifdef TIOCGWINSZ @@ -574,11 +573,10 @@ static int screen_columns(void) return win.ws_col; #endif - columns = 80; - if ((s = getenv("COLUMNS"))) { - columns = atoi(s); - } - return columns; + s = getenv("COLUMNS"); + if (s) + return xatoi_u(s); + return 80; } static const struct suffix_mult stty_suffixes[] = { @@ -745,14 +743,14 @@ end_option: #ifdef HAVE_C_LINE case param_line: # ifndef TIOCGWINSZ - bb_xparse_number(argnext, stty_suffixes); + xatoul_range_sfx(argnext, 1, INT_MAX, stty_suffixes); break; # endif /* else fall-through */ #endif #ifdef TIOCGWINSZ case param_rows: case param_cols: - bb_xparse_number(argnext, stty_suffixes); + xatoul_range_sfx(argnext, 1, INT_MAX, stty_suffixes); break; case param_size: #endif @@ -802,7 +800,7 @@ end_option: perror_on_device_and_die("%s"); if (verbose_output || recoverable_output || noargs) { - max_col = screen_columns(); + max_col = screen_columns_or_die(); output_func(&mode); return EXIT_SUCCESS; } @@ -846,24 +844,22 @@ end_option: switch (param) { #ifdef HAVE_C_LINE case param_line: - mode.c_line = bb_xparse_number(argnext, stty_suffixes); + mode.c_line = xatoul_sfx(argnext, stty_suffixes); require_set_attr = 1; break; #endif #ifdef TIOCGWINSZ case param_cols: - set_window_size(-1, (int) bb_xparse_number(argnext, stty_suffixes)); + set_window_size(-1, xatoul_sfx(argnext, stty_suffixes)); break; case param_size: - max_col = screen_columns(); display_window_size(0); break; case param_rows: - set_window_size((int) bb_xparse_number(argnext, stty_suffixes), -1); + set_window_size(xatoul_sfx(argnext, stty_suffixes), -1); break; #endif case param_speed: - max_col = screen_columns(); display_speed(&mode, 0); break; case param_ispeed: @@ -1096,7 +1092,7 @@ static void set_control_char_or_die(const struct control_info *info, unsigned char value; if (info->name == stty_min || info->name == stty_time) - value = bb_xparse_number(arg, stty_suffixes); + value = xatoul_range_sfx(arg, 0, 0xff, stty_suffixes); else if (arg[0] == '\0' || arg[1] == '\0') value = arg[0]; else if (streq(arg, "^-") || streq(arg, "undef")) @@ -1106,7 +1102,7 @@ static void set_control_char_or_die(const struct control_info *info, if (arg[1] == '?') value = 127; } else - value = bb_xparse_number(arg, stty_suffixes); + value = xatoul_range_sfx(arg, 0, 0xff, stty_suffixes); mode->c_cc[info->offset] = value; } diff --git a/coreutils/tail.c b/coreutils/tail.c index 49f1bcd6a..82c0d99bc 100644 --- a/coreutils/tail.c +++ b/coreutils/tail.c @@ -132,7 +132,7 @@ int tail_main(int argc, char **argv) #if !ENABLE_DEBUG_YANK_SUSv2 || ENABLE_FEATURE_FANCY_TAIL GET_COUNT: #endif - count = bb_xgetlarg10_sfx(optarg, tail_suffixes); + count = xatol_sfx(optarg, tail_suffixes); /* Note: Leading whitespace is an error trapped above. */ if (*optarg == '+') { from_top = 1; @@ -148,7 +148,7 @@ int tail_main(int argc, char **argv) header_threshhold = INT_MAX; break; case 's': - sleep_period =bb_xgetularg10_bnd(optarg, 0, UINT_MAX); + sleep_period = xatou(optarg); break; case 'v': header_threshhold = 0; diff --git a/coreutils/uniq.c b/coreutils/uniq.c index 26afc00f4..1b201af24 100644 --- a/coreutils/uniq.c +++ b/coreutils/uniq.c @@ -37,7 +37,7 @@ int uniq_main(int argc, char **argv) while ((opt = getopt(argc, argv, uniq_opts)) > 0) { if ((opt == 'f') || (opt == 's')) { - int t = bb_xgetularg10(optarg); + int t = xatoul(optarg); if (opt == 'f') { skip_fields = t; } else { diff --git a/coreutils/usleep.c b/coreutils/usleep.c index 90ddc5a57..de473a7b2 100644 --- a/coreutils/usleep.c +++ b/coreutils/usleep.c @@ -20,7 +20,7 @@ int usleep_main(int argc, char **argv) bb_show_usage(); } - if (usleep(bb_xgetularg10_bnd(argv[1], 0, UINT_MAX))) { + if (usleep(xatou(argv[1]))) { bb_perror_nomsg_and_die(); } diff --git a/coreutils/watch.c b/coreutils/watch.c index 7b9c6698a..b1a7d9086 100644 --- a/coreutils/watch.c +++ b/coreutils/watch.c @@ -28,7 +28,7 @@ int watch_main(int argc, char **argv) /* don't use getopt, because it permutes the arguments */ ++argv; if ((argc > 3) && argv[0][0] == '-' && argv[0][1] == 'n') { - period = bb_xgetularg10_bnd(argv[1], 1, UINT_MAX); + period = xatou(argv[1]); argv += 2; } watched_argv = argv; diff --git a/debianutils/run_parts.c b/debianutils/run_parts.c index 964a221a8..f2d90b64d 100644 --- a/debianutils/run_parts.c +++ b/debianutils/run_parts.c @@ -60,31 +60,31 @@ int run_parts_main(int argc, char **argv) umask(022); - while ((opt = getopt_long (argc, argv, "tu:a:", + while ((opt = getopt_long(argc, argv, "tu:a:", runparts_long_options, NULL)) > 0) { switch (opt) { - /* Enable test mode */ - case 't': - test_mode++; - break; - /* Set the umask of the programs executed */ - case 'u': - /* Check and set the umask of the program executed. As stated in the original - * run-parts, the octal conversion in libc is not foolproof; it will take the - * 8 and 9 digits under some circumstances. We'll just have to live with it. - */ - umask(bb_xgetlarg(optarg, 8, 0, 07777)); - break; - /* Pass an argument to the programs */ - case 'a': - /* Add an argument to the commands that we will call. - * Called once for every argument. */ - args = xrealloc(args, (argcount + 2) * (sizeof(char *))); - args[argcount++] = optarg; - break; - default: - bb_show_usage(); + /* Enable test mode */ + case 't': + test_mode++; + break; + /* Set the umask of the programs executed */ + case 'u': + /* Check and set the umask of the program executed. As stated in the original + * run-parts, the octal conversion in libc is not foolproof; it will take the + * 8 and 9 digits under some circumstances. We'll just have to live with it. + */ + umask(xstrtoul_range(optarg, 8, 0, 07777)); + break; + /* Pass an argument to the programs */ + case 'a': + /* Add an argument to the commands that we will call. + * Called once for every argument. */ + args = xrealloc(args, (argcount + 2) * (sizeof(char *))); + args[argcount++] = optarg; + break; + default: + bb_show_usage(); } } diff --git a/debianutils/start_stop_daemon.c b/debianutils/start_stop_daemon.c index 57f42d8ef..6ced9caad 100644 --- a/debianutils/start_stop_daemon.c +++ b/debianutils/start_stop_daemon.c @@ -260,7 +260,7 @@ int start_stop_daemon_main(int argc, char **argv) // USE_FEATURE_START_STOP_DAEMON_FANCY( // if (retry_arg) -// retries = bb_xgetlarg(retry_arg, 10, 0, INT_MAX); +// retries = xatoi_u(retry_arg); // ) argc -= optind; argv += optind; diff --git a/editors/patch.c b/editors/patch.c index c18659eda..047de9e57 100644 --- a/editors/patch.c +++ b/editors/patch.c @@ -87,7 +87,7 @@ int patch_main(int argc, char **argv) char *p, *i; ret = getopt32(argc, argv, "p:i:", &p, &i); if (ret & 1) - patch_level = bb_xgetlarg(p, 10, -1, USHRT_MAX); + patch_level = xatol_range(p, -1, USHRT_MAX); if (ret & 2) { patch_file = xfopen(i, "r"); } else { diff --git a/findutils/find.c b/findutils/find.c index 7e3613af4..913a778eb 100644 --- a/findutils/find.c +++ b/findutils/find.c @@ -216,53 +216,47 @@ int find_main(int argc, char **argv) #endif #ifdef CONFIG_FEATURE_FIND_PERM } else if (strcmp(argv[i], "-perm") == 0) { - char *end; if (++i == argc) bb_error_msg_and_die(bb_msg_requires_arg, "-perm"); - perm_mask = strtol(argv[i], &end, 8); - if ((end[0] != '\0') || (perm_mask > 07777)) - bb_error_msg_and_die(bb_msg_invalid_arg, argv[i], "-perm"); - if ((perm_char = argv[i][0]) == '-') + perm_mask = xstrtol_range(argv[i], 8, 0, 07777); + perm_char = argv[i][0]; + if (perm_char == '-') perm_mask = -perm_mask; #endif #ifdef CONFIG_FEATURE_FIND_MTIME } else if (strcmp(argv[i], "-mtime") == 0) { - char *end; if (++i == argc) bb_error_msg_and_die(bb_msg_requires_arg, "-mtime"); - mtime_days = strtol(argv[i], &end, 10); - if (end[0] != '\0') - bb_error_msg_and_die(bb_msg_invalid_arg, argv[i], "-mtime"); - if ((mtime_char = argv[i][0]) == '-') + mtime_days = xatol(argv[i]); + mtime_char = argv[i][0]; + if (mtime_char == '-') mtime_days = -mtime_days; #endif #ifdef CONFIG_FEATURE_FIND_MMIN } else if (strcmp(argv[i], "-mmin") == 0) { - char *end; if (++i == argc) bb_error_msg_and_die(bb_msg_requires_arg, "-mmin"); - mmin_mins = strtol(argv[i], &end, 10); - if (end[0] != '\0') - bb_error_msg_and_die(bb_msg_invalid_arg, argv[i], "-mmin"); - if ((mmin_char = argv[i][0]) == '-') + mmin_mins = xatol(argv[i]); + mmin_char = argv[i][0]; + if (mmin_char == '-') mmin_mins = -mmin_mins; #endif #ifdef CONFIG_FEATURE_FIND_XDEV } else if (strcmp(argv[i], "-xdev") == 0) { struct stat stbuf; - xdev_count = ( firstopt - 1 ) ? ( firstopt - 1 ) : 1; - xdev_dev = xmalloc ( xdev_count * sizeof( dev_t )); + xdev_count = (firstopt - 1) ? (firstopt - 1) : 1; + xdev_dev = xmalloc(xdev_count * sizeof(dev_t)); - if ( firstopt == 1 ) { - xstat ( ".", &stbuf ); - xdev_dev [0] = stbuf. st_dev; + if (firstopt == 1) { + xstat(".", &stbuf); + xdev_dev[0] = stbuf.st_dev; } else { for (i = 1; i < firstopt; i++) { - xstat ( argv [i], &stbuf ); - xdev_dev [i-1] = stbuf. st_dev; + xstat(argv[i], &stbuf); + xdev_dev[i-1] = stbuf.st_dev; } } #endif @@ -271,17 +265,14 @@ int find_main(int argc, char **argv) struct stat stat_newer; if (++i == argc) bb_error_msg_and_die(bb_msg_requires_arg, "-newer"); - xstat (argv[i], &stat_newer); + xstat(argv[i], &stat_newer); newer_mtime = stat_newer.st_mtime; #endif #ifdef CONFIG_FEATURE_FIND_INUM } else if (strcmp(argv[i], "-inum") == 0) { - char *end; if (++i == argc) bb_error_msg_and_die(bb_msg_requires_arg, "-inum"); - inode_num = strtol(argv[i], &end, 10); - if (end[0] != '\0') - bb_error_msg_and_die(bb_msg_invalid_arg, argv[i], "-inum"); + inode_num = xatoul(argv[i]); #endif #ifdef CONFIG_FEATURE_FIND_EXEC } else if (strcmp(argv[i], "-exec") == 0) { diff --git a/findutils/xargs.c b/findutils/xargs.c index 81997b6f6..e7cc7c379 100644 --- a/findutils/xargs.c +++ b/findutils/xargs.c @@ -426,7 +426,7 @@ int xargs_main(int argc, char **argv) orig_arg_max -= 2048; /* POSIX.2 requires subtracting 2048 */ if (opt & OPT_UPTO_SIZE) { - n_max_chars = bb_xgetularg10_bnd(max_chars, 1, orig_arg_max); + n_max_chars = xatoul_range(max_chars, 1, orig_arg_max); for (i = 0; i < argc; i++) { n_chars += strlen(*argv) + 1; } @@ -446,7 +446,7 @@ int xargs_main(int argc, char **argv) max_chars = xmalloc(n_max_chars); if (opt & OPT_UPTO_NUMBER) { - n_max_arg = bb_xgetularg10_bnd(max_args, 1, INT_MAX); + n_max_arg = xatoul_range(max_args, 1, INT_MAX); } else { n_max_arg = n_max_chars; } diff --git a/include/libbb.h b/include/libbb.h index 11e1e62d9..a7c770400 100644 --- a/include/libbb.h +++ b/include/libbb.h @@ -267,46 +267,68 @@ extern void *xmalloc(size_t size); extern void *xrealloc(void *old, size_t size); extern void *xzalloc(size_t size); -extern char *xstrdup (const char *s); -extern char *xstrndup (const char *s, int n); +extern char *xstrdup(const char *s); +extern char *xstrndup(const char *s, int n); extern char *safe_strncpy(char *dst, const char *src, size_t size); -extern int safe_strtoi(char *arg, int* value); -extern int safe_strtod(char *arg, double* value); -extern int safe_strtol(char *arg, long* value); -extern int safe_strtoll(char *arg, long long* value); -extern int safe_strtoul(char *arg, unsigned long* value); -extern int safe_strtoull(char *arg, unsigned long long* value); +// FIXME: the prototype doesn't match libc strtoXX -> confusion +// FIXME: alot of unchecked strtoXXX are still in tree +// FIXME: atoi_or_else(str, N)? +extern int safe_strtoi(const char *arg, int* value); +extern int safe_strtou(const char *arg, unsigned* value); +extern int safe_strtod(const char *arg, double* value); +extern int safe_strtol(const char *arg, long* value); +extern int safe_strtoll(const char *arg, long long* value); +extern int safe_strtoul(const char *arg, unsigned long* value); +extern int safe_strtoull(const char *arg, unsigned long long* value); +extern int safe_strtou32(const char *arg, uint32_t* value); struct suffix_mult { const char *suffix; unsigned int mult; }; -extern unsigned long bb_xgetularg_bnd_sfx(const char *arg, int base, +unsigned long xstrtoul_range_sfx(const char *numstr, int base, unsigned long lower, unsigned long upper, const struct suffix_mult *suffixes); -extern unsigned long bb_xgetularg_bnd(const char *arg, int base, +unsigned long xstrtoul_range(const char *numstr, int base, unsigned long lower, unsigned long upper); -extern unsigned long bb_xgetularg10_bnd(const char *arg, +unsigned long xstrtoul(const char *numstr, int base); +unsigned long xatoul_range_sfx(const char *numstr, + unsigned long lower, + unsigned long upper, + const struct suffix_mult *suffixes); +unsigned long xatoul_sfx(const char *numstr, + const struct suffix_mult *suffixes); +unsigned long xatoul_range(const char *numstr, unsigned long lower, unsigned long upper); -extern unsigned long bb_xgetularg10(const char *arg); - -extern long bb_xgetlarg(const char *arg, int base, - long lower, - long upper); -extern long bb_xgetlarg_bnd_sfx(const char *arg, int base, +unsigned long xatoul(const char *numstr); +unsigned long long xatoull(const char *numstr); +long xstrtol_range_sfx(const char *numstr, int base, long lower, long upper, const struct suffix_mult *suffixes); -extern long bb_xgetlarg10_sfx(const char *arg, const struct suffix_mult *suffixes); - - -extern unsigned long bb_xparse_number(const char *numstr, +long xstrtol_range(const char *numstr, int base, long lower, long upper); +long xatol_range_sfx(const char *numstr, + long lower, + long upper, const struct suffix_mult *suffixes); - +long xatol_range(const char *numstr, long lower, long upper); +long xatol_sfx(const char *numstr, const struct suffix_mult *suffixes); +long xatol(const char *numstr); +/* Specialized: */ +unsigned xatou(const char *numstr); +int xatoi(const char *numstr); +/* Using xatoi() instead of naive atoi() is not always convenient - + * in many places people want *non-negative* values, but store them + * in signed int. Therefore we need this one: + * dies if input is not in [0, INT_MAX] range. Also will reject '-0' etc */ +int xatoi_u(const char *numstr); +uint32_t xatou32(const char *numstr); +/* Useful for reading port numbers */ +uint16_t xatou16(const char *numstr); /* These parse entries in /etc/passwd and /etc/group. This is desirable * for BusyBox since we want to avoid using the glibc NSS stuff, which @@ -329,7 +351,7 @@ extern int device_open(const char *device, int mode); extern char *query_loop(const char *device); extern int del_loop(const char *device); -extern int set_loop(char **device, const char *file, int offset); +extern int set_loop(char **device, const char *file, unsigned long long offset); #if (__GLIBC__ < 2) extern int vdprintf(int d, const char *format, va_list ap); diff --git a/include/unarchive.h b/include/unarchive.h index 82a70aed6..7de6a63fe 100644 --- a/include/unarchive.h +++ b/include/unarchive.h @@ -92,7 +92,7 @@ extern char get_header_tar_lzma(archive_handle_t *archive_handle); extern char get_header_tar_gz(archive_handle_t *archive_handle); extern void seek_by_jump(const archive_handle_t *archive_handle, const unsigned int amount); -extern void seek_by_char(const archive_handle_t *archive_handle, const unsigned int amount); +extern void seek_by_read(const archive_handle_t *archive_handle, const unsigned int amount); extern ssize_t archive_xread_all_eof(archive_handle_t *archive_handle, unsigned char *buf, size_t count); diff --git a/init/halt.c b/init/halt.c index 2ac210e59..9e3cbb1cf 100644 --- a/init/halt.c +++ b/init/halt.c @@ -35,7 +35,7 @@ RB_AUTOBOOT /* Parse and handle arguments */ flags = getopt32(argc, argv, "d:nf", &delay); - if (flags&1) sleep(atoi(delay)); + if (flags&1) sleep(xatou(delay)); if (!(flags&2)) sync(); /* Perform action. */ diff --git a/libbb/Kbuild b/libbb/Kbuild index 909f527ba..4e992ef5b 100644 --- a/libbb/Kbuild +++ b/libbb/Kbuild @@ -15,7 +15,7 @@ lib-y:= \ human_readable.o inet_common.o inode_hash.o isdirectory.o \ kernel_version.o last_char_is.o login.o \ make_directory.o md5.o mode_string.o mtab_file.o \ - obscure.o parse_mode.o parse_number.o perror_msg.o \ + obscure.o parse_mode.o perror_msg.o \ perror_msg_and_die.o get_console.o \ process_escape_sequence.o procps.o \ recursive_action.o remove_file.o \ @@ -23,7 +23,7 @@ lib-y:= \ safe_strncpy.o setup_environment.o sha1.o simplify_path.o \ trim.o u_signal_names.o vdprintf.o verror_msg.o \ vherror_msg.o vperror_msg.o wfopen.o xconnect.o xgetcwd.o \ - xgethostbyname.o xgethostbyname2.o xreadlink.o xgetlarg.o \ + xgethostbyname.o xgethostbyname2.o xreadlink.o \ fclose_nonstdin.o fflush_stdout_and_exit.o \ getopt32.o default_error_retval.o wfopen_input.o speed_table.o \ perror_nomsg_and_die.o perror_nomsg.o skip_whitespace.o bb_askpass.o \ @@ -55,7 +55,7 @@ lib-$(CONFIG_DEVFSD) += xregcomp.o lib-y += messages.o lib-y += xfuncs.o lib-y += printf.o -lib-y += xgetularg.o +lib-y += xatol.o lib-y += safe_strtol.o lib-y += bb_pwd.o lib-y += llist.o diff --git a/libbb/loop.c b/libbb/loop.c index d22b39800..1b296d99b 100644 --- a/libbb/loop.c +++ b/libbb/loop.c @@ -48,11 +48,12 @@ char *query_loop(const char *device) { int fd; bb_loop_info loopinfo; - char *dev=0; + char *dev = 0; - if ((fd = open(device, O_RDONLY)) < 0) return 0; + fd = open(device, O_RDONLY); + if (fd < 0) return 0; if (!ioctl(fd, BB_LOOP_GET_STATUS, &loopinfo)) - dev=xasprintf("%ld %s", (long) loopinfo.lo_offset, + dev = xasprintf("%ld %s", (long) loopinfo.lo_offset, (char *)loopinfo.lo_file_name); close(fd); @@ -64,8 +65,9 @@ int del_loop(const char *device) { int fd, rc; - if ((fd = open(device, O_RDONLY)) < 0) return 1; - rc=ioctl(fd, LOOP_CLR_FD, 0); + fd = open(device, O_RDONLY); + if (fd < 0) return 1; + rc = ioctl(fd, LOOP_CLR_FD, 0); close(fd); return rc; @@ -77,7 +79,7 @@ int del_loop(const char *device) search will re-use an existing loop device already bound to that file/offset if it finds one. */ -int set_loop(char **device, const char *file, int offset) +int set_loop(char **device, const char *file, unsigned long long offset) { char dev[20], *try; bb_loop_info loopinfo; @@ -85,34 +87,43 @@ int set_loop(char **device, const char *file, int offset) int i, dfd, ffd, mode, rc=-1; /* Open the file. Barf if this doesn't work. */ - if((ffd = open(file, mode=O_RDWR))<0 && (ffd = open(file,mode=O_RDONLY))<0) - return -errno; + mode = O_RDWR; + ffd = open(file, mode); + if (ffd < 0) { + mode = O_RDONLY; + ffd = open(file, mode); + if (ffd < 0) + return -errno; + } /* Find a loop device. */ - try=*device ? : dev; - for(i=0;rc;i++) { + try = *device ? : dev; + for (i=0;rc;i++) { sprintf(dev, LOOP_FORMAT, i); /* Ran out of block devices, return failure. */ - if(stat(try, &statbuf) || !S_ISBLK(statbuf.st_mode)) { + if (stat(try, &statbuf) || !S_ISBLK(statbuf.st_mode)) { rc=-ENOENT; break; } /* Open the sucker and check its loopiness. */ - if((dfd=open(try, mode))<0 && errno==EROFS) - dfd=open(try, mode = O_RDONLY); - if(dfd<0) goto try_again; + dfd = open(try, mode); + if (dfd < 0 && errno == EROFS) { + mode = O_RDONLY; + dfd = open(try, mode); + } + if (dfd < 0) goto try_again; - rc=ioctl(dfd, BB_LOOP_GET_STATUS, &loopinfo); + rc = ioctl(dfd, BB_LOOP_GET_STATUS, &loopinfo); /* If device free, claim it. */ - if(rc && errno==ENXIO) { + if (rc && errno == ENXIO) { memset(&loopinfo, 0, sizeof(loopinfo)); safe_strncpy((char *)loopinfo.lo_file_name, file, LO_NAME_SIZE); loopinfo.lo_offset = offset; /* Associate free loop device with file. */ - if(!ioctl(dfd, LOOP_SET_FD, ffd)) { - if (!ioctl(dfd, BB_LOOP_SET_STATUS, &loopinfo)) rc=0; + if (!ioctl(dfd, LOOP_SET_FD, ffd)) { + if (!ioctl(dfd, BB_LOOP_SET_STATUS, &loopinfo)) rc = 0; else ioctl(dfd, LOOP_CLR_FD, 0); } @@ -121,15 +132,16 @@ int set_loop(char **device, const char *file, int offset) file isn't pretty either. In general, mounting the same file twice without using losetup manually is problematic.) */ - } else if(strcmp(file,(char *)loopinfo.lo_file_name) - || offset!=loopinfo.lo_offset) rc=-1; + } else if (strcmp(file,(char *)loopinfo.lo_file_name) + || offset!=loopinfo.lo_offset) rc = -1; close(dfd); try_again: - if(*device) break; + if (*device) break; } close(ffd); - if(!rc) { - if(!*device) *device=strdup(dev); + if (!rc) { + if (!*device) *device = strdup(dev); return mode==O_RDONLY ? 1 : 0; - } else return rc; + } + return rc; } diff --git a/libbb/parse_number.c b/libbb/parse_number.c deleted file mode 100644 index c7dafb7f0..000000000 --- a/libbb/parse_number.c +++ /dev/null @@ -1,50 +0,0 @@ -/* vi: set sw=4 ts=4: */ -/* - * bb_xparse_number implementation for busybox - * - * Copyright (C) 2003 Manuel Novoa III - * - * Licensed under GPLv2 or later, see file LICENSE in this tarball for details. - */ - -#include -#include -#include -#include -#include -#include "libbb.h" - -unsigned long bb_xparse_number(const char *numstr, - const struct suffix_mult *suffixes) -{ - unsigned long int r; - char *e; - int old_errno; - - /* Since this is a lib function, we're not allowed to reset errno to 0. - * Doing so could break an app that is deferring checking of errno. - * So, save the old value so that we can restore it if successful. */ - old_errno = errno; - errno = 0; - r = strtoul(numstr, &e, 10); - - if ((numstr != e) && !errno) { - errno = old_errno; /* Ok. So restore errno. */ - if (!*e) { - return r; - } - if (suffixes) { - assert(suffixes->suffix); /* No nul suffixes. */ - do { - if (strcmp(suffixes->suffix, e) == 0) { - if (ULONG_MAX / suffixes->mult < r) { /* Overflow! */ - break; - } - return r * suffixes->mult; - } - ++suffixes; - } while (suffixes->suffix); - } - } - bb_error_msg_and_die("invalid number '%s'", numstr); -} diff --git a/libbb/safe_strtol.c b/libbb/safe_strtol.c index 027fc1e62..a7f012fbc 100644 --- a/libbb/safe_strtol.c +++ b/libbb/safe_strtol.c @@ -7,21 +7,10 @@ * Licensed under GPLv2 or later, see file LICENSE in this tarball for details. */ -#include -#include #include #include "libbb.h" -int safe_strtoi(char *arg, int* value) -{ - int error; - long lvalue = *value; - error = safe_strtol(arg, &lvalue); - *value = (int) lvalue; - return error; -} - -int safe_strtod(char *arg, double* value) +int safe_strtod(const char *arg, double* value) { char *endptr; int errno_save = errno; @@ -29,69 +18,132 @@ int safe_strtod(char *arg, double* value) assert(arg!=NULL); errno = 0; *value = strtod(arg, &endptr); - if (errno != 0 || *endptr!='\0' || endptr==arg) { + if (errno != 0 || *endptr != '\0' || endptr == arg) { return 1; } errno = errno_save; return 0; } -int safe_strtol(char *arg, long* value) +int safe_strtoull(const char *arg, unsigned long long* value) { char *endptr; int errno_save = errno; assert(arg!=NULL); + if (!isdigit(arg[0])) /* strtouXX takes minus signs w/o error! :( */ + return 1; errno = 0; - *value = strtol(arg, &endptr, 0); - if (errno != 0 || *endptr!='\0' || endptr==arg) { + *value = strtoull(arg, &endptr, 0); + if (errno != 0 || *endptr != '\0' || endptr == arg) { return 1; } errno = errno_save; return 0; } -int safe_strtoul(char *arg, unsigned long* value) +int safe_strtoll(const char *arg, long long* value) { char *endptr; int errno_save = errno; assert(arg!=NULL); errno = 0; - *value = strtoul(arg, &endptr, 0); - if (errno != 0 || *endptr!='\0' || endptr==arg) { + *value = strtoll(arg, &endptr, 0); + if (errno != 0 || *endptr != '\0' || endptr == arg) { return 1; } errno = errno_save; return 0; } -int safe_strtoll(char *arg, long long* value) +int safe_strtoul(const char *arg, unsigned long* value) { char *endptr; int errno_save = errno; assert(arg!=NULL); + if (!isdigit(arg[0])) /* strtouXX takes minus signs w/o error! :( */ + return 1; errno = 0; - *value = strtoll(arg, &endptr, 0); - if (errno != 0 || *endptr!='\0' || endptr==arg) { + *value = strtoul(arg, &endptr, 0); + if (errno != 0 || *endptr != '\0' || endptr == arg) { return 1; } errno = errno_save; return 0; } -int safe_strtoull(char *arg, unsigned long long* value) +int safe_strtol(const char *arg, long* value) { char *endptr; int errno_save = errno; assert(arg!=NULL); errno = 0; - *value = strtoull(arg, &endptr, 0); - if (errno != 0 || *endptr!='\0' || endptr==arg) { + *value = strtol(arg, &endptr, 0); + if (errno != 0 || *endptr != '\0' || endptr == arg) { return 1; } errno = errno_save; return 0; } + +/* TODO: This is what uclibc is doing. Try to do the same? */ + +#if 0 +#if defined __HAVE_ELF__ + +# define strong_alias(name, aliasname) _strong_alias(name, aliasname) +# define _strong_alias(name, aliasname) \ + extern __typeof (name) aliasname __attribute__ ((alias (#name))); + +#else /* !defined __HAVE_ELF__ */ + +# define strong_alias(name, aliasname) _strong_alias (name, aliasname) +# define _strong_alias(name, aliasname) \ + __asm__(".global " __C_SYMBOL_PREFIX__ #aliasname "\n" \ + ".set " __C_SYMBOL_PREFIX__ #aliasname "," __C_SYMBOL_PREFIX__ #name); + +#endif +#endif + +int safe_strtoi(const char *arg, int* value) +{ + if (sizeof(long) == sizeof(int)) { + return safe_strtol(arg, (long*)value); + } else { + int error; + long lvalue = *value; + error = safe_strtol(arg, &lvalue); + if (lvalue < INT_MIN || lvalue > INT_MAX) + return 1; + *value = (int) lvalue; + return error; + } +} + +int safe_strtou(const char *arg, unsigned* value) +{ + if (sizeof(unsigned long) == sizeof(unsigned)) { + return safe_strtoul(arg, (unsigned long*)value); + } else { + int error; + unsigned long lvalue = *value; + error = safe_strtoul(arg, &lvalue); + if (lvalue > UINT_MAX) + return 1; + *value = (unsigned) lvalue; + return error; + } +} + +int BUG_safe_strtou32_unimplemented(void); +int safe_strtou32(const char *arg, uint32_t* value) +{ + if (sizeof(uint32_t) == sizeof(unsigned)) + return safe_strtou(arg, (unsigned*)value); + if (sizeof(uint32_t) == sizeof(unsigned long)) + return safe_strtoul(arg, (unsigned long*)value); + return BUG_safe_strtou32_unimplemented(); +} diff --git a/libbb/xatol.c b/libbb/xatol.c new file mode 100644 index 000000000..82250a7bb --- /dev/null +++ b/libbb/xatol.c @@ -0,0 +1,210 @@ +/* vi: set sw=4 ts=4: */ +/* + * ascii-to-numbers implementations for busybox + * + * Copyright (C) 2003 Manuel Novoa III + * + * Licensed under GPLv2, see file LICENSE in this tarball for details. + */ + +#include "libbb.h" + +unsigned long long xatoull(const char *numstr) +{ + unsigned long long r; + int old_errno; + char *e; + if ((*numstr == '-') || (isspace)(*numstr)) + bb_error_msg_and_die("invalid number '%s'", numstr); + old_errno = errno; + errno = 0; + r = strtoull(numstr, &e, 10); + if (errno || (numstr == e) || *e) + /* Error / no digits / illegal trailing chars */ + bb_error_msg_and_die("invalid number '%s'", numstr); + /* No error. So restore errno. */ + errno = old_errno; + return r; +} + +unsigned long xstrtoul_range_sfx(const char *numstr, int base, + unsigned long lower, + unsigned long upper, + const struct suffix_mult *suffixes) +{ + unsigned long r; + int old_errno; + char *e; + + /* Disallow '-' and any leading whitespace. Speed isn't critical here + * since we're parsing commandline args. So make sure we get the + * actual isspace function rather than a lnumstrer macro implementaion. */ + if ((*numstr == '-') || (isspace)(*numstr)) + goto inval; + + /* Since this is a lib function, we're not allowed to reset errno to 0. + * Doing so could break an app that is deferring checking of errno. + * So, save the old value so that we can restore it if successful. */ + old_errno = errno; + errno = 0; + r = strtoul(numstr, &e, base); + /* Do the initial validity check. Note: The standards do not + * guarantee that errno is set if no digits were found. So we + * must test for this explicitly. */ + if (errno || (numstr == e)) + goto inval; /* error / no digits / illegal trailing chars */ + + errno = old_errno; /* Ok. So restore errno. */ + + /* Do optional suffix parsing. Allow 'empty' suffix tables. + * Note that we also allow nul suffixes with associated multipliers, + * to allow for scaling of the numstr by some default multiplier. */ + if (suffixes) { + while (suffixes->suffix) { + if (strcmp(suffixes->suffix, e) == 0) { + if (ULONG_MAX / suffixes->mult < r) + goto range; /* overflow! */ + ++e; + r *= suffixes->mult; + break; + } + ++suffixes; + } + } + + /* Note: trailing space is an error. + It would be easy enough to allow though if desired. */ + if (*e) + goto inval; + /* Finally, check for range limits. */ + if (r >= lower && r <= upper) + return r; + range: + bb_error_msg_and_die("number %s is not in %lu..%lu range", + numstr, lower, upper); + inval: + bb_error_msg_and_die("invalid number '%s'", numstr); +} + +unsigned long xstrtoul_range(const char *numstr, int base, + unsigned long lower, + unsigned long upper) +{ + return xstrtoul_range_sfx(numstr, base, lower, upper, NULL); +} + +unsigned long xstrtoul(const char *numstr, int base) +{ + return xstrtoul_range_sfx(numstr, base, 0, ULONG_MAX, NULL); +} + +unsigned long xatoul_range_sfx(const char *numstr, + unsigned long lower, + unsigned long upper, + const struct suffix_mult *suffixes) +{ + return xstrtoul_range_sfx(numstr, 10, lower, upper, suffixes); +} + +unsigned long xatoul_sfx(const char *numstr, + const struct suffix_mult *suffixes) +{ + return xstrtoul_range_sfx(numstr, 10, 0, ULONG_MAX, suffixes); +} + +unsigned long xatoul_range(const char *numstr, + unsigned long lower, + unsigned long upper) +{ + return xstrtol_range_sfx(numstr, 10, lower, upper, NULL); +} + +unsigned long xatoul(const char *numstr) +{ + return xatoul_sfx(numstr, NULL); +} + +/* Signed ones */ + +long xstrtol_range_sfx(const char *numstr, int base, + long lower, + long upper, + const struct suffix_mult *suffixes) +{ + unsigned long u = LONG_MAX; + long r; + const char *p = numstr; + + if ((p[0] == '-') && (p[1] != '+')) { + ++p; + ++u; /* two's complement */ + } + + r = xstrtoul_range_sfx(p, base, 0, u, suffixes); + + if (*numstr == '-') { + r = -r; + } + + if (r < lower || r > upper) { + bb_error_msg_and_die("number %s is not in %ld..%ld range", + numstr, lower, upper); + } + + return r; +} + +long xstrtol_range(const char *numstr, int base, long lower, long upper) +{ + return xstrtol_range_sfx(numstr, base, lower, upper, NULL); +} + +long xatol_range_sfx(const char *numstr, + long lower, + long upper, + const struct suffix_mult *suffixes) +{ + return xstrtol_range_sfx(numstr, 10, lower, upper, suffixes); +} + +long xatol_range(const char *numstr, long lower, long upper) +{ + return xstrtol_range_sfx(numstr, 10, lower, upper, NULL); +} + +long xatol_sfx(const char *numstr, const struct suffix_mult *suffixes) +{ + return xstrtol_range_sfx(numstr, 10, LONG_MIN, LONG_MAX, suffixes); +} + +long xatol(const char *numstr) +{ + return xstrtol_range_sfx(numstr, 10, LONG_MIN, LONG_MAX, NULL); +} + +/* Others */ + +unsigned xatou(const char *numstr) +{ + return xatoul_range(numstr, 0, UINT_MAX); +} + +int xatoi(const char *numstr) +{ + return xatol_range(numstr, INT_MIN, INT_MAX); +} + +int xatoi_u(const char *numstr) +{ + return xatoul_range(numstr, 0, INT_MAX); +} + +uint32_t xatou32(const char *numstr) +{ + return xatoul_range(numstr, 0, 0xffffffff); +} + +uint16_t xatou16(const char *numstr) +{ + return xatoul_range(numstr, 0, 0xffff); +} diff --git a/libbb/xgetlarg.c b/libbb/xgetlarg.c deleted file mode 100644 index 5b1e7b9d5..000000000 --- a/libbb/xgetlarg.c +++ /dev/null @@ -1,32 +0,0 @@ -/* vi: set sw=4 ts=4: */ -/* - * Copyright (C) 2003-2004 Erik Andersen - * - * Licensed under GPLv2 or later, see file LICENSE in this tarball for details. - */ - -#include -#include -#include -#include -#include -#include - -#include "libbb.h" - -long bb_xgetlarg(const char *arg, int base, long lower, long upper) -{ - long result; - char *endptr; - int errno_save = errno; - - if (ENABLE_DEBUG && arg==NULL) - bb_error_msg_and_die("Null in xgetlarg."); - - errno = 0; - result = strtol(arg, &endptr, base); - if (errno != 0 || *endptr!='\0' || endptr==arg || result < lower || result > upper) - bb_show_usage(); - errno = errno_save; - return result; -} diff --git a/libbb/xgetularg.c b/libbb/xgetularg.c deleted file mode 100644 index 17ba581f7..000000000 --- a/libbb/xgetularg.c +++ /dev/null @@ -1,127 +0,0 @@ -/* vi: set sw=4 ts=4: */ -/* - * xgetularg* implementations for busybox - * - * Copyright (C) 2003 Manuel Novoa III - * - * Licensed under GPLv2 or later, see file LICENSE in this tarball for details. - */ - -#include -#include -#include -#include -#include -#include -#include "libbb.h" - -unsigned long bb_xgetularg_bnd_sfx(const char *arg, int base, - unsigned long lower, - unsigned long upper, - const struct suffix_mult *suffixes) -{ - unsigned long r; - int old_errno; - char *e; - - assert(arg); - - /* Disallow '-' and any leading whitespace. Speed isn't critical here - * since we're parsing commandline args. So make sure we get the - * actual isspace function rather than a larger macro implementaion. */ - if ((*arg == '-') || (isspace)(*arg)) { - bb_show_usage(); - } - - /* Since this is a lib function, we're not allowed to reset errno to 0. - * Doing so could break an app that is deferring checking of errno. - * So, save the old value so that we can restore it if successful. */ - old_errno = errno; - errno = 0; - r = strtoul(arg, &e, base); - /* Do the initial validity check. Note: The standards do not - * guarantee that errno is set if no digits were found. So we - * must test for this explicitly. */ - if (errno || (arg == e)) { /* error or no digits */ - bb_show_usage(); - } - errno = old_errno; /* Ok. So restore errno. */ - - /* Do optional suffix parsing. Allow 'empty' suffix tables. - * Note that we also all nul suffixes with associated multipliers, - * to allow for scaling of the arg by some default multiplier. */ - - if (suffixes) { - while (suffixes->suffix) { - if (strcmp(suffixes->suffix, e) == 0) { - if (ULONG_MAX / suffixes->mult < r) { /* Overflow! */ - bb_show_usage(); - } - ++e; - r *= suffixes->mult; - break; - } - ++suffixes; - } - } - - /* Finally, check for illegal trailing chars and range limits. */ - /* Note: although we allow leading space (via stroul), trailing space - * is an error. It would be easy enough to allow though if desired. */ - if (*e || (r < lower) || (r > upper)) { - bb_show_usage(); - } - - return r; -} - -long bb_xgetlarg_bnd_sfx(const char *arg, int base, - long lower, - long upper, - const struct suffix_mult *suffixes) -{ - unsigned long u = LONG_MAX; - long r; - const char *p = arg; - - if ((*p == '-') && (p[1] != '+')) { - ++p; - ++u; /* two's complement */ - } - - r = bb_xgetularg_bnd_sfx(p, base, 0, u, suffixes); - - if (*arg == '-') { - r = -r; - } - - if ((r < lower) || (r > upper)) { - bb_show_usage(); - } - - return r; -} - -long bb_xgetlarg10_sfx(const char *arg, const struct suffix_mult *suffixes) -{ - return bb_xgetlarg_bnd_sfx(arg, 10, LONG_MIN, LONG_MAX, suffixes); -} - -unsigned long bb_xgetularg_bnd(const char *arg, int base, - unsigned long lower, - unsigned long upper) -{ - return bb_xgetularg_bnd_sfx(arg, base, lower, upper, NULL); -} - -unsigned long bb_xgetularg10_bnd(const char *arg, - unsigned long lower, - unsigned long upper) -{ - return bb_xgetularg_bnd(arg, 10, lower, upper); -} - -unsigned long bb_xgetularg10(const char *arg) -{ - return bb_xgetularg10_bnd(arg, 0, ULONG_MAX); -} diff --git a/loginutils/addgroup.c b/loginutils/addgroup.c index 236dc1099..0172e6041 100644 --- a/loginutils/addgroup.c +++ b/loginutils/addgroup.c @@ -91,15 +91,14 @@ int addgroup_main(int argc, char **argv) /* check for min, max and missing args and exit on error */ opt_complementary = "-1:?2:?"; - if (getopt32(argc, argv, "g:", &group)) { - gid = bb_xgetlarg(group, 10, 0, LONG_MAX); + gid = xatoul_range(group, 0, (gid_t)ULONG_MAX); } /* move past the commandline options */ argv += optind; /* need to be root */ - if(geteuid()) { + if (geteuid()) { bb_error_msg_and_die(bb_msg_perm_denied_are_you_root); } diff --git a/loginutils/getty.c b/loginutils/getty.c index 4b43684a2..d279dc3a4 100644 --- a/loginutils/getty.c +++ b/loginutils/getty.c @@ -113,7 +113,7 @@ extern void updwtmp(const char *filename, const struct utmp *ut); struct options { int flags; /* toggle switches, see below */ - int timeout; /* time-out period */ + unsigned timeout; /* time-out period */ char *login; /* login program */ char *tty; /* name of tty */ char *initstring; /* modem init string */ @@ -226,11 +226,12 @@ FILE *dbf; static int bcode(const char *s) { int r; - unsigned long value; - if (safe_strtoul((char *)s, &value)) { + unsigned value; + if (safe_strtou((char *)s, &value)) { return -1; } - if ((r = tty_value_to_baud(value)) > 0) { + r = tty_value_to_baud(value); + if (r > 0) { return r; } return 0; @@ -280,8 +281,7 @@ static void parse_args(int argc, char **argv, struct options *op) } op->flags ^= F_ISSUE; /* revert flag show /etc/issue */ if(op->flags & F_TIMEOUT) { - if ((op->timeout = atoi(ts)) <= 0) - bb_error_msg_and_die("bad timeout value: %s", ts); + op->timeout = xatoul_range(ts, 1, INT_MAX); } debug("after getopt loop\n"); if (argc < optind + 2) /* check parameter count */ @@ -495,7 +495,8 @@ static void auto_baud(struct termio *tp) buf[nread] = '\0'; for (bp = buf; bp < buf + nread; bp++) { if (isascii(*bp) && isdigit(*bp)) { - if ((speed = bcode(bp))) { + speed = bcode(bp); + if (speed) { tp->c_cflag &= ~CBAUD; tp->c_cflag |= speed; } @@ -881,7 +882,7 @@ int getty_main(int argc, char **argv) /* Set the optional timer. */ if (options.timeout) - (void) alarm((unsigned) options.timeout); + (void) alarm(options.timeout); /* optionally wait for CR or LF before writing /etc/issue */ if (options.flags & F_WAITCRLF) { diff --git a/loginutils/sulogin.c b/loginutils/sulogin.c index 40eb5e9cf..679439544 100644 --- a/loginutils/sulogin.c +++ b/loginutils/sulogin.c @@ -46,10 +46,8 @@ int sulogin_main(int argc, char **argv) logmode = LOGMODE_BOTH; openlog(applet_name, 0, LOG_AUTH); - if (getopt32 (argc, argv, "t:", &timeout_arg)) { - if (safe_strtoi(timeout_arg, &timeout)) { - timeout = 0; - } + if (getopt32(argc, argv, "t:", &timeout_arg)) { + timeout = xatoi_u(timeout_arg); } if (argv[optind]) { diff --git a/loginutils/vlock.c b/loginutils/vlock.c index 02d1ea772..9ab097b77 100644 --- a/loginutils/vlock.c +++ b/loginutils/vlock.c @@ -55,7 +55,7 @@ int vlock_main(int argc, char **argv) bb_show_usage(); } - o_lock_all = getopt32 (argc, argv, "a"); + o_lock_all = getopt32(argc, argv, "a"); if((pw = getpwuid(getuid())) == NULL) { bb_error_msg_and_die("Unknown uid %d", getuid()); diff --git a/miscutils/adjtimex.c b/miscutils/adjtimex.c index 47af1a5d2..b35538a84 100644 --- a/miscutils/adjtimex.c +++ b/miscutils/adjtimex.c @@ -12,10 +12,6 @@ */ #include "busybox.h" -#include -#include -#include -#include #include static const struct {int bit; const char *name;} statlist[] = { @@ -58,19 +54,19 @@ int adjtimex_main(int argc, char **argv) &opt_o, &opt_f, &opt_p, &opt_t); //if (opt & 0x1) // -q if (opt & 0x2) { // -o - txc.offset = atoi(opt_o); + txc.offset = xatoi(opt_o); txc.modes |= ADJ_OFFSET_SINGLESHOT; } if (opt & 0x4) { // -f - txc.freq = atoi(opt_f); + txc.freq = xatou(opt_f); txc.modes |= ADJ_FREQUENCY; } if (opt & 0x8) { // -p - txc.constant = atoi(opt_p); + txc.constant = xatoi(opt_p); txc.modes |= ADJ_TIMECONST; } if (opt & 0x10) { // -t - txc.tick = atoi(opt_t); + txc.tick = xatoi(opt_t); txc.modes |= ADJ_TICK; } if (argc != optind) { /* no valid non-option parameters */ diff --git a/miscutils/crond.c b/miscutils/crond.c index db0cc2c6b..623e8c359 100644 --- a/miscutils/crond.c +++ b/miscutils/crond.c @@ -65,10 +65,10 @@ typedef struct CronLine { #define DaemonUid 0 #if ENABLE_DEBUG_CROND_OPTION -static short DebugOpt; +static unsigned DebugOpt; #endif -static short LogLevel = 8; +static unsigned LogLevel = 8; static const char *LogFile; static const char *CDir = CRONTABS; @@ -155,7 +155,7 @@ int crond_main(int ac, char **av) #endif ); if (opt & 1) { - LogLevel = atoi(lopt); + LogLevel = xatou(lopt); } if (opt & 2) { if (*Lopt != 0) { @@ -169,7 +169,7 @@ int crond_main(int ac, char **av) } #if ENABLE_DEBUG_CROND_OPTION if (opt & 64) { - DebugOpt = atoi(dopt); + DebugOpt = xatou(dopt); LogLevel = 0; } #endif diff --git a/miscutils/dc.c b/miscutils/dc.c index 95cf0d0ad..8e7a2494c 100644 --- a/miscutils/dc.c +++ b/miscutils/dc.c @@ -171,7 +171,7 @@ static void stack_machine(const char *argument) } o++; } - bb_error_msg_and_die("%s: syntax error.", argument); + bb_error_msg_and_die("%s: syntax error", argument); } /* return pointer to next token in buffer and set *buffer to one char diff --git a/miscutils/hdparm.c b/miscutils/hdparm.c index 6c46f6a92..1c9a99e13 100644 --- a/miscutils/hdparm.c +++ b/miscutils/hdparm.c @@ -2063,7 +2063,7 @@ static void parse_opts(unsigned long *get, unsigned long *set, unsigned long *va } if (optarg) { *set = 1; - *value = bb_xgetlarg(optarg, 10, min, max); + *value = xatol_range(optarg, min, max); } } @@ -2154,8 +2154,8 @@ int hdparm_main(int argc, char **argv) #if ENABLE_FEATURE_HDPARM_HDIO_SCAN_HWIF if (c == 'R') { parse_opts(NULL, &scan_hwif, &hwif_data, 0, INT_MAX); - hwif_ctrl = bb_xgetlarg((argv[optind]) ? argv[optind] : "", 10, 0, INT_MAX); - hwif_irq = bb_xgetlarg((argv[optind+1]) ? argv[optind+1] : "", 10, 0, INT_MAX); + hwif_ctrl = xatoi_u((argv[optind]) ? argv[optind] : ""); + hwif_irq = xatoi_u((argv[optind+1]) ? argv[optind+1] : ""); /* Move past the 2 additional arguments */ argv += 2; argc -= 2; diff --git a/miscutils/makedevs.c b/miscutils/makedevs.c index 4619e4dd5..e27634add 100644 --- a/miscutils/makedevs.c +++ b/miscutils/makedevs.c @@ -21,10 +21,10 @@ int makedevs_main(int argc, char **argv) basedev = argv[1]; type = argv[2]; - Smajor = atoi(argv[3]); - Sminor = atoi(argv[4]); - S = atoi(argv[5]); - E = atoi(argv[6]); + Smajor = xatoi_u(argv[3]); + Sminor = xatoi_u(argv[4]); + S = xatoi_u(argv[5]); + E = xatoi_u(argv[6]); nodname = argc == 8 ? basedev : buf; mode = 0660; diff --git a/miscutils/mt.c b/miscutils/mt.c index f4a3be739..a2bb6be91 100644 --- a/miscutils/mt.c +++ b/miscutils/mt.c @@ -84,7 +84,7 @@ int mt_main(int argc, char **argv) op.mt_op = code->value; if (argc >= 3) - op.mt_count = atoi(argv[2]); + op.mt_count = xatoi_u(argv[2]); else op.mt_count = 1; /* One, not zero, right? */ diff --git a/miscutils/strings.c b/miscutils/strings.c index 36bcf8b17..1ff41ad9c 100644 --- a/miscutils/strings.c +++ b/miscutils/strings.c @@ -34,7 +34,7 @@ int strings_main(int argc, char **argv) argc -= optind; argv += optind; - n = bb_xgetlarg(n_arg, 10, 1, INT_MAX); + n = xatoul_range(n_arg, 1, INT_MAX); string = xzalloc(n + 1); n--; @@ -45,7 +45,8 @@ int strings_main(int argc, char **argv) } do { - if ((file = bb_wfopen(*argv, "r"))) { + file = bb_wfopen(*argv, "r"); + if (file) { PIPE: count = 0; do { diff --git a/miscutils/watchdog.c b/miscutils/watchdog.c index ae51aba7b..e342c13f3 100644 --- a/miscutils/watchdog.c +++ b/miscutils/watchdog.c @@ -26,13 +26,13 @@ static void watchdog_shutdown(int ATTRIBUTE_UNUSED unused) int watchdog_main(int argc, char **argv) { unsigned opts; - unsigned long timer_duration = 30; /* Userspace timer duration, in seconds */ + unsigned timer_duration = 30; /* Userspace timer duration, in seconds */ char *t_arg; opts = getopt32(argc, argv, "Ft:", &t_arg); if (opts & OPT_TIMER) - timer_duration = bb_xgetlarg(t_arg, 10, 0, INT_MAX); + timer_duration = xatou(t_arg); /* We're only interested in the watchdog device .. */ if (optind < argc - 1 || argc == 1) diff --git a/modutils/insmod.c b/modutils/insmod.c index 348feed8d..cef47ff45 100644 --- a/modutils/insmod.c +++ b/modutils/insmod.c @@ -2652,7 +2652,7 @@ static int new_is_module_checksummed(struct obj_file *f) { const char *p = get_modinfo_value(f, "using_checksums"); if (p) - return atoi(p); + return xatoi(p); else return 0; } diff --git a/networking/arping.c b/networking/arping.c index 1ff6f90be..b9605985c 100644 --- a/networking/arping.c +++ b/networking/arping.c @@ -41,8 +41,8 @@ enum cfg_e { static int cfg; static int s; -static int count = -1; -static int timeout; +static unsigned count = UINT_MAX; +static unsigned timeout; static int sent; static int brd_sent; static int received; @@ -276,9 +276,9 @@ int arping_main(int argc, char **argv) &_count, &_timeout, &device, &source); cfg |= opt & 0x3f; /* set respective flags */ if (opt & 0x40) /* -c: count */ - count = atoi(_count); + count = xatou(_count); if (opt & 0x80) /* -w: timeout */ - timeout = atoi(_timeout); + timeout = xatoul_range(_timeout, 0, INT_MAX/2000); if (opt & 0x100) { /* -i: interface */ if (strlen(device) > IF_NAMESIZE) { bb_error_msg_and_die("interface name '%s' is too long", diff --git a/networking/ftpgetput.c b/networking/ftpgetput.c index 492854153..902528f93 100644 --- a/networking/ftpgetput.c +++ b/networking/ftpgetput.c @@ -42,15 +42,15 @@ static int ftpcmd(const char *s1, const char *s2, FILE *stream, char *buf) char *buf_ptr; if (fgets(buf, 510, stream) == NULL) { - bb_perror_msg_and_die("fgets()"); + bb_perror_msg_and_die("fgets"); } buf_ptr = strstr(buf, "\r\n"); if (buf_ptr) { *buf_ptr = '\0'; } - } while (! isdigit(buf[0]) || buf[3] != ' '); + } while (!isdigit(buf[0]) || buf[3] != ' '); - return atoi(buf); + return xatou(buf); } static int xconnect_ftpdata(ftp_host_info_t *server, const char *buf) @@ -60,14 +60,14 @@ static int xconnect_ftpdata(ftp_host_info_t *server, const char *buf) buf_ptr = strrchr(buf, ','); *buf_ptr = '\0'; - port_num = atoi(buf_ptr + 1); + port_num = xatoul_range(buf_ptr + 1, 0, 255); buf_ptr = strrchr(buf, ','); *buf_ptr = '\0'; - port_num += atoi(buf_ptr + 1) * 256; + port_num += xatoul_range(buf_ptr + 1, 0, 255) * 256; - server->s_in->sin_port=htons(port_num); - return(xconnect(server->s_in)); + server->s_in->sin_port = htons(port_num); + return xconnect(server->s_in); } static FILE *ftp_login(ftp_host_info_t *server) diff --git a/networking/httpd.c b/networking/httpd.c index 0e471ba58..f3fe49cae 100644 --- a/networking/httpd.c +++ b/networking/httpd.c @@ -1951,7 +1951,7 @@ int httpd_main(int argc, char *argv[]) #endif #if ENABLE_FEATURE_HTTPD_WITHOUT_INETD if (opt & OPT_PORT) - config->port = bb_xgetlarg(s_port, 10, 1, 0xffff); + config->port = xatou16(s_port); #if ENABLE_FEATURE_HTTPD_SETUID if (opt & OPT_SETUID) { char *e; diff --git a/networking/ifconfig.c b/networking/ifconfig.c index 4d346c47f..59b6f0acc 100644 --- a/networking/ifconfig.c +++ b/networking/ifconfig.c @@ -379,7 +379,8 @@ int ifconfig_main(int argc, char **argv) safe_strncpy(host, *argv, (sizeof host)); #ifdef CONFIG_FEATURE_IPV6 - if ((prefix = strchr(host, '/'))) { + prefix = strchr(host, '/'); + if (prefix) { if (safe_strtoi(prefix + 1, &prefix_len) || (prefix_len < 0) || (prefix_len > 128)) { diff --git a/networking/inetd.c b/networking/inetd.c index e22115a5c..966425385 100644 --- a/networking/inetd.c +++ b/networking/inetd.c @@ -149,8 +149,6 @@ #define _PATH_INETDPID "/var/run/inetd.pid" -#define TOOMANY 0 /* don't start more than TOOMANY */ - #define CNT_INTVL 60 /* servers in CNT_INTVL sec. */ #define RETRYTIME (60*10) /* retry after bind or server fail */ @@ -297,7 +295,7 @@ static const struct builtin builtins[] = { static int global_queuelen = 128; static int nsock, maxsock; static fd_set allsock; -static int toomany = TOOMANY; +static int toomany; static int timingout; static struct servent *sp; static uid_t uid; @@ -588,10 +586,10 @@ static servtab_t *getconfigent(void) sep = new_servtab(); /* memset(sep, 0, sizeof *sep); */ -more: + more: /* freeconfig(sep); */ - while ((cp = nextline()) && *cp == '#'); + while ((cp = nextline()) && *cp == '#') /* skip comment line */; if (cp == NULL) { /* free(sep); */ return NULL; @@ -680,7 +678,7 @@ more: } else if (*ccp != '\0') goto badafterall; #else - bb_error_msg("%s: rpc services not supported", sep->se_service); + bb_error_msg("%s: rpc services not supported", sep->se_service); #endif } } @@ -692,7 +690,7 @@ more: char *s = strchr(arg, '.'); if (s) { *s++ = '\0'; - sep->se_max = atoi(s); + sep->se_max = xatoi(s); } else sep->se_max = toomany; } @@ -928,7 +926,7 @@ static void config(int sig ATTRIBUTE_UNUSED) */ if ( #ifdef INETD_FEATURE_ENABLED - cp->se_bi == 0 && + cp->se_bi == 0 && #endif (sep->se_wait == 1 || cp->se_wait == 0)) sep->se_wait = cp->se_wait; @@ -974,7 +972,7 @@ static void config(int sig ATTRIBUTE_UNUSED) #ifdef CONFIG_FEATURE_INETD_RPC if (isrpcservice(sep)) { struct rpcent *rp; - + // FIXME: atoi_or_else(str, 0) would be handy here sep->se_rpcprog = atoi(sep->se_service); if (sep->se_rpcprog == 0) { rp = getrpcbyname(sep->se_service); @@ -990,9 +988,9 @@ static void config(int sig ATTRIBUTE_UNUSED) register_rpc(sep); } else #endif - { + { u_short port = htons(atoi(sep->se_service)); - + // FIXME: atoi_or_else(str, 0) would be handy here if (!port) { /*XXX*/ strncpy(protoname, sep->se_proto, sizeof(protoname)); if (isdigit(protoname[strlen(protoname) - 1])) @@ -1255,13 +1253,7 @@ inetd_main(int argc, char *argv[]) opt = getopt32(argc, argv, "R:f", &stoomany); if(opt & 1) { - char *e; - - toomany = strtoul(stoomany, &e, 0); - if (!(toomany >= 0 && *e == '\0')) { - toomany = TOOMANY; - bb_perror_msg("-R %s: bad value for service invocation rate", stoomany); - } + toomany = xatoi_u(stoomany); } argc -= optind; argv += optind; @@ -1317,7 +1309,6 @@ inetd_main(int argc, char *argv[]) sigaddset(&sa.sa_mask, SIGHUP); sa.sa_handler = retry; sigaction(SIGALRM, &sa, NULL); - /* doconfig(); */ config(SIGHUP); sa.sa_handler = config; sigaction(SIGHUP, &sa, NULL); diff --git a/networking/interface.c b/networking/interface.c index c3cc7c0bc..8e2498d27 100644 --- a/networking/interface.c +++ b/networking/interface.c @@ -363,7 +363,7 @@ static int nstrcmp(const char *a, const char *b) } if (isdigit(*a) && isdigit(*b)) { - return atoi(a_ptr) > atoi(b_ptr) ? 1 : -1; + return xatoul(a_ptr) > xatoul(b_ptr) ? 1 : -1; } return *a - *b; } diff --git a/networking/ipcalc.c b/networking/ipcalc.c index 576dfc853..909373cbb 100644 --- a/networking/ipcalc.c +++ b/networking/ipcalc.c @@ -18,8 +18,6 @@ #include #include -#define IPCALC_MSG(CMD,ALTCMD) if (mode & SILENT) {ALTCMD;} else {CMD;} - #define CLASS_A_NETMASK ntohl(0xFF000000) #define CLASS_B_NETMASK ntohl(0xFFFF0000) #define CLASS_C_NETMASK ntohl(0xFFFFFF00) @@ -56,6 +54,7 @@ static int get_prefix(unsigned long netmask) int get_prefix(unsigned long netmask); #endif + #define NETMASK 0x01 #define BROADCAST 0x02 #define NETWORK 0x04 @@ -78,12 +77,9 @@ int get_prefix(unsigned long netmask); #else #define long_options 0 #endif - - - int ipcalc_main(int argc, char **argv) { - unsigned long mode; + unsigned opt; int have_netmask = 0; in_addr_t netmask, broadcast, network, ipaddr; struct in_addr a; @@ -92,17 +88,18 @@ int ipcalc_main(int argc, char **argv) if (ENABLE_FEATURE_IPCALC_LONG_OPTIONS) applet_long_options = long_options; - mode = getopt32(argc, argv, "mbn" USE_FEATURE_IPCALC_FANCY("phs")); - + opt = getopt32(argc, argv, "mbn" USE_FEATURE_IPCALC_FANCY("phs")); argc -= optind; argv += optind; - if (mode & (BROADCAST | NETWORK | NETPREFIX)) { + if (opt & (BROADCAST | NETWORK | NETPREFIX)) { if (argc > 2 || argc <= 0) bb_show_usage(); } else { if (argc != 1) bb_show_usage(); } + if (opt & SILENT) + logmode = LOGMODE_NONE; /* Suppress error_msg() output */ ipstr = argv[0]; if (ENABLE_FEATURE_IPCALC_FANCY) { @@ -111,17 +108,13 @@ int ipcalc_main(int argc, char **argv) prefixstr = ipstr; - while(*prefixstr) { + while (*prefixstr) { if (*prefixstr == '/') { *prefixstr = (char)0; prefixstr++; if (*prefixstr) { - unsigned int msk; - - if (safe_strtoul(prefixstr, &netprefix) || netprefix > 32) { - IPCALC_MSG(bb_error_msg_and_die("bad IP prefix: %s", prefixstr), - exit(EXIT_FAILURE)); - } + unsigned msk; + netprefix = xatoul_range(prefixstr, 0, 32); netmask = 0; msk = 0x80000000; while (netprefix > 0) { @@ -142,21 +135,18 @@ int ipcalc_main(int argc, char **argv) ipaddr = inet_aton(ipstr, &a); if (ipaddr == 0) { - IPCALC_MSG(bb_error_msg_and_die("bad IP address: %s", argv[0]), - exit(EXIT_FAILURE)); + bb_error_msg_and_die("bad IP address: %s", argv[0]); } ipaddr = a.s_addr; if (argc == 2) { if (ENABLE_FEATURE_IPCALC_FANCY && have_netmask) { - IPCALC_MSG(bb_error_msg_and_die("Use prefix or netmask, not both"), - exit(EXIT_FAILURE)); + bb_error_msg_and_die("use prefix or netmask, not both"); } netmask = inet_aton(argv[1], &a); if (netmask == 0) { - IPCALC_MSG(bb_error_msg_and_die("bad netmask: %s", argv[1]), - exit(EXIT_FAILURE)); + bb_error_msg_and_die("bad netmask: %s", argv[1]); } netmask = a.s_addr; } else { @@ -166,34 +156,32 @@ int ipcalc_main(int argc, char **argv) netmask = get_netmask(ipaddr); } - if (mode & NETMASK) { + if (opt & NETMASK) { printf("NETMASK=%s\n", inet_ntoa((*(struct in_addr *) &netmask))); } - if (mode & BROADCAST) { + if (opt & BROADCAST) { broadcast = (ipaddr & netmask) | ~netmask; printf("BROADCAST=%s\n", inet_ntoa((*(struct in_addr *) &broadcast))); } - if (mode & NETWORK) { + if (opt & NETWORK) { network = ipaddr & netmask; printf("NETWORK=%s\n", inet_ntoa((*(struct in_addr *) &network))); } if (ENABLE_FEATURE_IPCALC_FANCY) { - if (mode & NETPREFIX) { + if (opt & NETPREFIX) { printf("PREFIX=%i\n", get_prefix(netmask)); } - if (mode & HOSTNAME) { + if (opt & HOSTNAME) { struct hostent *hostinfo; int x; hostinfo = gethostbyaddr((char *) &ipaddr, sizeof(ipaddr), AF_INET); if (!hostinfo) { - IPCALC_MSG(bb_herror_msg_and_die( - "cannot find hostname for %s", argv[0]),); - exit(EXIT_FAILURE); + bb_herror_msg_and_die("cannot find hostname for %s", argv[0]); } for (x = 0; hostinfo->h_name[x]; x++) { hostinfo->h_name[x] = tolower(hostinfo->h_name[x]); diff --git a/networking/nc.c b/networking/nc.c index f8b3fb2dd..bde5e6600 100644 --- a/networking/nc.c +++ b/networking/nc.c @@ -11,13 +11,15 @@ static void timeout(int signum) { - bb_error_msg_and_die("Timed out"); + bb_error_msg_and_die("timed out"); } int nc_main(int argc, char **argv) { - int do_listen = 0, lport = 0, delay = 0, wsecs = 0, execflag = 0, opt, - sfd = 0, cfd; + int sfd = 0, cfd; + unsigned opt; + unsigned lport = 0, wsecs = 0, delay = 0; + unsigned do_listen = 0, execflag = 0; struct sockaddr_in address; struct hostent *hostinfo; fd_set readfds, testfds; @@ -30,8 +32,8 @@ int nc_main(int argc, char **argv) if (ENABLE_NC_SERVER && opt=='l') do_listen++; else if (ENABLE_NC_SERVER && opt=='p') lport = bb_lookup_port(optarg, "tcp", 0); - else if (ENABLE_NC_EXTRA && opt=='w') wsecs = atoi(optarg); - else if (ENABLE_NC_EXTRA && opt=='i') delay = atoi(optarg); + else if (ENABLE_NC_EXTRA && opt=='w') wsecs = xatou(optarg); + else if (ENABLE_NC_EXTRA && opt=='i') delay = xatou(optarg); else if (ENABLE_NC_EXTRA && opt=='f') infile = optarg; else if (ENABLE_NC_EXTRA && opt=='e' && optind!=argc) { execflag++; @@ -40,11 +42,10 @@ int nc_main(int argc, char **argv) } } - // For listen or file we need zero arguments, dialout is 2. // For exec we need at least one more argument at the end, more ok - opt = (do_listen || infile) ? 0 : 2 + execflag; + opt = (do_listen || infile) ? 0 : 2 + execflag; if (execflag ? argc-optind < opt : argc-optind!=opt || (infile && do_listen)) bb_show_usage(); @@ -66,7 +67,6 @@ int nc_main(int argc, char **argv) if (lport != 0) { address.sin_port = lport; - xbind(sfd, (struct sockaddr *) &address, sizeof(address)); } @@ -83,7 +83,8 @@ int nc_main(int argc, char **argv) fdprintf(2, "%d\n", SWAP_BE16(address.sin_port)); } repeatyness: - if ((cfd = accept(sfd, (struct sockaddr *) &address, &addrlen)) < 0) + cfd = accept(sfd, (struct sockaddr *) &address, &addrlen); + if (cfd < 0) bb_perror_msg_and_die("accept"); if (!execflag) close(sfd); @@ -116,10 +117,11 @@ repeatyness: // With more than one -l, repeatedly act as server. - if (do_listen>1 && vfork()) { + if (do_listen > 1 && vfork()) { // This is a bit weird as cleanup goes, since we wind up with no // stdin/stdout/stderr. But it's small and shouldn't hurt anything. // We check for cfd == 0 above. + logmode = LOGMODE_NONE; close(0); close(1); close(2); diff --git a/networking/ping.c b/networking/ping.c index a81472f96..8ca8be9b9 100644 --- a/networking/ping.c +++ b/networking/ping.c @@ -157,9 +157,9 @@ int ping_main(int argc, char **argv) static struct sockaddr_in pingaddr; static struct sockaddr_in sourceaddr; static int pingsock = -1; -static int datalen; /* intentionally uninitialized to work around gcc bug */ +static unsigned datalen; /* intentionally uninitialized to work around gcc bug */ -static long ntransmitted, nreceived, nrepeats, pingcount; +static unsigned long ntransmitted, nreceived, nrepeats, pingcount; static int myid, options; static unsigned long tmin = ULONG_MAX, tmax, tsum; static char rcvd_tbl[MAX_DUP_CHK / 8]; @@ -179,12 +179,12 @@ static void pingstats(int junk) signal(SIGINT, SIG_IGN); printf("\n--- %s ping statistics ---\n", hostent->h_name); - printf("%ld packets transmitted, ", ntransmitted); - printf("%ld packets received, ", nreceived); + printf("%lu packets transmitted, ", ntransmitted); + printf("%lu packets received, ", nreceived); if (nrepeats) - printf("%ld duplicates, ", nrepeats); + printf("%lu duplicates, ", nrepeats); if (ntransmitted) - printf("%ld%% packet loss\n", + printf("%lu%% packet loss\n", (ntransmitted - nreceived) * 100 / ntransmitted); if (nreceived) printf("round-trip min/avg/max = %lu.%lu/%lu.%lu/%lu.%lu ms\n", @@ -427,13 +427,13 @@ int ping_main(int argc, char **argv) if (--argc <= 0) bb_show_usage(); argv++; - pingcount = atoi(*argv); + pingcount = xatoul(*argv); break; case 's': if (--argc <= 0) bb_show_usage(); argv++; - datalen = atoi(*argv); + datalen = xatou16(*argv); break; case 'I': if (--argc <= 0) diff --git a/networking/ping6.c b/networking/ping6.c index 6079c40d9..0d6a739bf 100644 --- a/networking/ping6.c +++ b/networking/ping6.c @@ -145,10 +145,10 @@ int ping6_main(int argc, char **argv) /* full(er) version */ static struct sockaddr_in6 pingaddr; static int pingsock = -1; -static int datalen; /* intentionally uninitialized to work around gcc bug */ +static unsigned datalen; /* intentionally uninitialized to work around gcc bug */ static int if_index; -static long ntransmitted, nreceived, nrepeats, pingcount; +static unsigned long ntransmitted, nreceived, nrepeats, pingcount; static int myid, options; static unsigned long tmin = ULONG_MAX, tmax, tsum; static char rcvd_tbl[MAX_DUP_CHK / 8]; @@ -168,12 +168,12 @@ static void pingstats(int junk) signal(SIGINT, SIG_IGN); printf("\n--- %s ping statistics ---\n", hostent->h_name); - printf("%ld packets transmitted, ", ntransmitted); - printf("%ld packets received, ", nreceived); + printf("%lu packets transmitted, ", ntransmitted); + printf("%lu packets received, ", nreceived); if (nrepeats) - printf("%ld duplicates, ", nrepeats); + printf("%lu duplicates, ", nrepeats); if (ntransmitted) - printf("%ld%% packet loss\n", + printf("%lu%% packet loss\n", (ntransmitted - nreceived) * 100 / ntransmitted); if (nreceived) printf("round-trip min/avg/max = %lu.%lu/%lu.%lu/%lu.%lu ms\n", @@ -439,13 +439,13 @@ int ping6_main(int argc, char **argv) if (--argc <= 0) bb_show_usage(); argv++; - pingcount = atoi(*argv); + pingcount = xatoul(*argv); break; case 's': if (--argc <= 0) bb_show_usage(); argv++; - datalen = atoi(*argv); + datalen = xatou16(*argv); break; case 'I': if (--argc <= 0) diff --git a/networking/route.c b/networking/route.c index 2e6e017b6..65b40fcd6 100644 --- a/networking/route.c +++ b/networking/route.c @@ -178,7 +178,7 @@ static void INET_setroute(int action, char **args) if(prefix) { int prefix_len; - prefix_len = bb_xgetularg10_bnd(prefix+1, 0, 32); + prefix_len = xatoul_range(prefix+1, 0, 32); mask_in_addr(rt) = htonl( ~ (0xffffffffUL >> prefix_len)); *prefix = '\0'; #if HAVE_NEW_ADDRT @@ -218,7 +218,7 @@ static void INET_setroute(int action, char **args) #if HAVE_NEW_ADDRT if (k == KW_IPVx_METRIC) { - rt.rt_metric = bb_xgetularg10(args_m1) + 1; + rt.rt_metric = xatoul(args_m1) + 1; continue; } #endif @@ -259,20 +259,20 @@ static void INET_setroute(int action, char **args) if (k == KW_IPVx_MSS) { /* Check valid MSS bounds. */ rt.rt_flags |= RTF_MSS; - rt.rt_mss = bb_xgetularg10_bnd(args_m1, 64, 32768); + rt.rt_mss = xatoul_range(args_m1, 64, 32768); continue; } if (k == KW_IPVx_WINDOW) { /* Check valid window bounds. */ rt.rt_flags |= RTF_WINDOW; - rt.rt_window = bb_xgetularg10_bnd(args_m1, 128, INT_MAX); + rt.rt_window = xatoul_range(args_m1, 128, INT_MAX); continue; } #ifdef RTF_IRTT if (k == KW_IPVx_IRTT) { rt.rt_flags |= RTF_IRTT; - rt.rt_irtt = bb_xgetularg10(args_m1); + rt.rt_irtt = xatoul(args_m1); rt.rt_irtt *= (sysconf(_SC_CLK_TCK) / 100); /* FIXME */ #if 0 /* FIXME: do we need to check anything of this? */ if (rt.rt_irtt < 1 || rt.rt_irtt > (120 * HZ)) { @@ -353,7 +353,7 @@ static void INET6_setroute(int action, char **args) char *cp; if ((cp = strchr(target, '/'))) { /* Yes... const to non is ok. */ *cp = 0; - prefix_len = bb_xgetularg10_bnd(cp+1, 0, 128); + prefix_len = xatoul_range(cp+1, 0, 128); } else { prefix_len = 128; } @@ -384,7 +384,7 @@ static void INET6_setroute(int action, char **args) } if (k == KW_IPVx_METRIC) { - rt.rtmsg_metric = bb_xgetularg10(args_m1); + rt.rtmsg_metric = xatoul(args_m1); continue; } diff --git a/networking/telnetd.c b/networking/telnetd.c index 1c4dede39..c6789e19c 100644 --- a/networking/telnetd.c +++ b/networking/telnetd.c @@ -369,7 +369,7 @@ telnetd_main(int argc, char **argv) sockaddr_type sa; int master_fd; int on = 1; - int portnbr = 23; + unsigned portnbr = 23; struct in_addr bind_addr = { .s_addr = 0x0 }; char *opt_portnbr, *opt_bindaddr; #endif /* CONFIG_FEATURE_TELNETD_INETD */ @@ -393,7 +393,7 @@ telnetd_main(int argc, char **argv) //if (opt & 1) // -f //if (opt & 2) // -l #ifndef CONFIG_FEATURE_TELNETD_INETD - if (opt & 4) portnbr = atoi(opt_portnbr); // -p + if (opt & 4) portnbr = xatou16(opt_portnbr); // -p if (opt & 8) // -b if (inet_aton(opt_bindaddr, &bind_addr) == 0) bb_show_usage(); #endif /* CONFIG_FEATURE_TELNETD_INETD */ diff --git a/networking/tftp.c b/networking/tftp.c index bfe94aca2..6213d6622 100644 --- a/networking/tftp.c +++ b/networking/tftp.c @@ -373,7 +373,7 @@ static int tftp(const int cmd, const struct hostent *host, res = tftp_option_get(&buf[2], len - 2, OPTION_BLOCKSIZE); if (res) { - int blksize = atoi(res); + int blksize = xatoi_u(res); if (tftp_blocksize_check(blksize, tftp_bufsize - 4)) { @@ -516,7 +516,7 @@ int tftp_main(int argc, char **argv) #ifdef CONFIG_FEATURE_TFTP_BLOCKSIZE if (sblocksize) { - blocksize = atoi(sblocksize); + blocksize = xatoi_u(sblocksize); if (!tftp_blocksize_check(blocksize, 0)) { return EXIT_FAILURE; } diff --git a/networking/traceroute.c b/networking/traceroute.c index 4af523625..84ce8ae69 100644 --- a/networking/traceroute.c +++ b/networking/traceroute.c @@ -416,7 +416,7 @@ ifaddrlist(struct IFADDRLIST **ipaddrp) ++al; ++nipaddr; } - if(nipaddr == 0) + if (nipaddr == 0) bb_error_msg_and_die ("Can't find any network interfaces"); (void)close(fd); @@ -494,34 +494,6 @@ findsaddr(const struct sockaddr_in *to, struct sockaddr_in *from) */ -/* String to value with optional min and max. Handles decimal and hex. */ -static int -str2val(const char *str, const char *what, int mi, int ma) -{ - const char *cp; - int val; - char *ep; - - if (str[0] == '0' && (str[1] == 'x' || str[1] == 'X')) { - cp = str + 2; - val = (int)strtol(cp, &ep, 16); - } else - val = (int)strtol(str, &ep, 10); - if (*ep != '\0') { - bb_error_msg_and_die("\"%s\" bad value for %s", str, what); - } - if (val < mi && mi >= 0) { - if (mi == 0) - bb_error_msg_and_die("%s must be >= %d", what, mi); - else - bb_error_msg_and_die("%s must be > %d", what, mi - 1); - } - if (val > ma && ma >= 0) - bb_error_msg_and_die("%s must be <= %d", what, ma); - return val; -} - - /* * Subtract 2 timeval structs: out = out - in. * Out is assumed to be >= in. @@ -828,7 +800,7 @@ inetname(struct sockaddr_in *from) char name[257]; if (!nflag && from->sin_addr.s_addr != INADDR_ANY) { - if(INET_rresolve(name, sizeof(name), from, 0x4000, 0xffffffff) >= 0) + if (INET_rresolve(name, sizeof(name), from, 0x4000, 0xffffffff) >= 0) n = name; } ina = inet_ntoa(from->sin_addr); @@ -974,7 +946,7 @@ traceroute_main(int argc, char *argv[]) #endif ); - if(op & USAGE_OP_DONT_FRAGMNT) + if (op & USAGE_OP_DONT_FRAGMNT) off = IP_DF; #ifdef CONFIG_FEATURE_TRACEROUTE_USE_ICMP useicmp = op & USAGE_OP_USE_ICMP; @@ -983,34 +955,34 @@ traceroute_main(int argc, char *argv[]) #ifdef CONFIG_FEATURE_TRACEROUTE_VERBOSE verbose = op & USAGE_OP_VERBOSE; #endif - if(op & USAGE_OP_IP_CHKSUM) { + if (op & USAGE_OP_IP_CHKSUM) { doipcksum = 0; - bb_error_msg("Warning: ip checksums disabled"); + bb_error_msg("warning: ip checksums disabled"); } if (tos_str) - tos = str2val(tos_str, "tos", 0, 255); - if(max_ttl_str) - max_ttl = str2val(max_ttl_str, "max ttl", 1, 255); - if(port_str) - port = (u_short)str2val(port_str, "port", 1, (1 << 16) - 1); - if(nprobes_str) - nprobes = str2val(nprobes_str, "nprobes", 1, -1); - if(source) { + tos = xatoul_range(tos_str, 0, 255); + if (max_ttl_str) + max_ttl = xatoul_range(max_ttl_str, 1, 255); + if (port_str) + port = xatou16(port_str); + if (nprobes_str) + nprobes = xatoul_range(nprobes_str, 1, INT_MAX); + if (source) { /* * set the ip source address of the outbound * probe (e.g., on a multi-homed host). */ if (getuid()) bb_error_msg_and_die("-s %s: permission denied", source); } - if(waittime_str) - waittime = str2val(waittime_str, "wait time", 2, 24 * 60 * 60); - if(pausemsecs_str) - pausemsecs = str2val(pausemsecs_str, "pause msecs", 0, 60 * 60 * 1000); - if(first_ttl_str) - first_ttl = str2val(first_ttl_str, "first ttl", 1, 255); + if (waittime_str) + waittime = xatoul_range(waittime_str, 2, 24 * 60 * 60); + if (pausemsecs_str) + pausemsecs = xatoul_range(pausemsecs_str, 0, 60 * 60 * 1000); + if (first_ttl_str) + first_ttl = xatoul_range(first_ttl_str, 1, 255); #ifdef CONFIG_FEATURE_TRACEROUTE_SOURCE_ROUTE - if(sourse_route_list) { + if (sourse_route_list) { llist_t *l_sr; for(l_sr = sourse_route_list; l_sr; ) { @@ -1046,8 +1018,7 @@ traceroute_main(int argc, char *argv[]) switch (argc - optind) { case 2: - packlen = str2val(argv[optind + 1], - "packet length", minpacket, maxpacket); + packlen = xatoul_range(argv[optind + 1], minpacket, maxpacket); /* Fall through */ case 1: @@ -1055,8 +1026,7 @@ traceroute_main(int argc, char *argv[]) hi = gethostinfo(hostname); setsin(to, hi->addrs[0]); if (hi->n > 1) - bb_error_msg( - "Warning: %s has multiple addresses; using %s", + bb_error_msg("warning: %s has multiple addresses; using %s", hostname, inet_ntoa(to->sin_addr)); hostname = hi->name; hi->name = NULL; diff --git a/networking/udhcp/dhcpc.c b/networking/udhcp/dhcpc.c index 9ab6aee8c..f2cf82f05 100644 --- a/networking/udhcp/dhcpc.c +++ b/networking/udhcp/dhcpc.c @@ -262,10 +262,10 @@ int udhcpc_main(int argc, char *argv[]) client_config.script = optarg; break; case 'T': - client_config.timeout = atoi(optarg); + client_config.timeout = xatoi_u(optarg); break; case 't': - client_config.retries = atoi(optarg); + client_config.retries = xatoi_u(optarg); break; case 'v': printf("version %s\n\n", BB_VER); diff --git a/networking/udhcp/files.c b/networking/udhcp/files.c index d9dfb8965..52d383869 100644 --- a/networking/udhcp/files.c +++ b/networking/udhcp/files.c @@ -35,7 +35,8 @@ static int read_ip(const char *line, void *arg) int retval = 1; if (!inet_aton(line, addr)) { - if ((host = gethostbyname(line))) + host = gethostbyname(line); + if (host) addr->s_addr = *((unsigned long *) host->h_addr_list[0]); else retval = 0; } @@ -72,10 +73,7 @@ static int read_str(const char *line, void *arg) static int read_u32(const char *line, void *arg) { - uint32_t *dest = arg; - char *endptr; - *dest = strtoul(line, &endptr, 0); - return endptr[0] == '\0'; + return safe_strtou32(line, (uint32_t*)arg) == 0; } diff --git a/networking/vconfig.c b/networking/vconfig.c index 6c808eb2f..003c1a8f7 100644 --- a/networking/vconfig.c +++ b/networking/vconfig.c @@ -144,14 +144,14 @@ int vconfig_main(int argc, char **argv) * doing so wouldn't save that much space and would also make maintainence * more of a pain. */ if (ifr.cmd == SET_VLAN_FLAG_CMD) { /* set_flag */ - ifr.u.flag = bb_xgetularg10_bnd(p, 0, 1); + ifr.u.flag = xatoul_range(p, 0, 1); /* DM: in order to set reorder header, qos must be set */ - ifr.vlan_qos = bb_xgetularg10_bnd(argv[3], 0, 7); + ifr.vlan_qos = xatoul_range(argv[3], 0, 7); } else if (ifr.cmd == ADD_VLAN_CMD) { /* add */ - ifr.u.VID = bb_xgetularg10_bnd(p, 0, VLAN_GROUP_ARRAY_LEN-1); + ifr.u.VID = xatoul_range(p, 0, VLAN_GROUP_ARRAY_LEN-1); } else if (ifr.cmd != DEL_VLAN_CMD) { /* set_{egress|ingress}_map */ - ifr.u.skb_priority = bb_xgetularg10_bnd(p, 0, ULONG_MAX); - ifr.vlan_qos = bb_xgetularg10_bnd(argv[3], 0, 7); + ifr.u.skb_priority = xatou(p); + ifr.vlan_qos = xatoul_range(argv[3], 0, 7); } } diff --git a/networking/wget.c b/networking/wget.c index eda0bb87c..e7b19f2ef 100644 --- a/networking/wget.c +++ b/networking/wget.c @@ -297,7 +297,7 @@ read_response: s = buf; while (*s != '\0' && !isspace(*s)) ++s; while (isspace(*s)) ++s; - switch (status = atoi(s)) { + switch (status = xatoi(s)) { case 0: case 100: while (gethdr(buf, sizeof(buf), sfp, &n) != NULL) @@ -406,9 +406,9 @@ read_response: bb_error_msg_and_die("PASV: %s", buf+4); s = strrchr(buf, ','); *s = 0; - port = atoi(s+1); + port = xatol_range(s+1, 0, 255); s = strrchr(buf, ','); - port += atoi(s+1) * 256; + port += xatol_range(s+1, 0, 255) * 256; s_in.sin_port = htons(port); dfp = open_socket(&s_in); @@ -562,7 +562,7 @@ static void parse_url(char *src_url, struct host_info *h) cp = strchr(pp, ':'); if (cp != NULL) { *cp++ = '\0'; - h->port = htons(atoi(cp)); + h->port = htons(xatou16(cp)); } } @@ -646,7 +646,7 @@ static int ftpcmd(char *s1, char *s2, FILE *fp, char *buf) } } while (!isdigit(buf[0]) || buf[3] != ' '); - return atoi(buf); + return xatoi(buf); } #ifdef CONFIG_FEATURE_WGET_STATUSBAR diff --git a/procps/kill.c b/procps/kill.c index 2408a70ca..b29f61b58 100644 --- a/procps/kill.c +++ b/procps/kill.c @@ -47,7 +47,7 @@ int kill_main(int argc, char **argv) } else { /* -l */ while ((arg = *++argv)!=NULL) { if (isdigit(arg[0])) { - signo = atoi(arg); + signo = xatoi_u(arg); name = get_signame(signo); } else { signo = get_signum(arg); @@ -140,7 +140,7 @@ do_it_now: while (arg) { if (!isdigit(arg[0]) && arg[0]!='-') bb_error_msg_and_die("bad pid '%s'", arg); - pid = strtol(arg, NULL, 0); + pid = xatou(arg); /* FIXME: better overflow check? */ if (kill(pid, signo)!=0) { bb_perror_msg("cannot kill pid %ld", (long)pid); diff --git a/procps/pidof.c b/procps/pidof.c index e6c954843..62c590fd8 100644 --- a/procps/pidof.c +++ b/procps/pidof.c @@ -14,7 +14,7 @@ #define SINGLE (1<<0) #else #define _SINGLE_COMPL(a) -#define SINGLE (0) +#define SINGLE 0 #endif #if ENABLE_FEATURE_PIDOF_OMIT @@ -56,7 +56,7 @@ int pidof_main(int argc, char **argv) /* are we asked to exclude the parent's process ID? */ if (!strncmp(omits_p->data, "%PPID", 5)) { llist_pop(&omits_p); - snprintf(getppid_str, sizeof(getppid_str), "%d", getppid()); + snprintf(getppid_str, sizeof(getppid_str), "%ld", (long)getppid()); llist_add_to(&omits_p, getppid_str); } omits_p = omits_p->link; @@ -64,19 +64,19 @@ int pidof_main(int argc, char **argv) } #endif /* Looks like everything is set to go. */ - while(optind < argc) { + while (optind < argc) { long *pidList; long *pl; /* reverse the pidlist like GNU pidof does. */ pidList = pidlist_reverse(find_pid_by_name(argv[optind])); - for(pl = pidList; *pl > 0; pl++) { + for (pl = pidList; *pl > 0; pl++) { #if ENABLE_FEATURE_PIDOF_OMIT unsigned omitted = 0; if (opt & OMIT) { llist_t *omits_p = omits; while (omits_p) - if (strtol(omits_p->data, NULL, 10) == *pl) { + if (xatoul(omits_p->data) == *pl) { omitted = 1; break; } else omits_p = omits_p->link; diff --git a/procps/renice.c b/procps/renice.c index 53dc57855..a91328f53 100644 --- a/procps/renice.c +++ b/procps/renice.c @@ -53,13 +53,13 @@ static inline int int_add_no_wrap(int a, int b) int renice_main(int argc, char **argv) { - static const char Xetpriority_msg[] = "%d : %cetpriority"; + static const char Xetpriority_msg[] = "%d: %cetpriority"; int retval = EXIT_SUCCESS; int which = PRIO_PROCESS; /* Default 'which' value. */ int use_relative = 0; int adjustment, new_priority; - id_t who; + unsigned who; ++argv; @@ -74,15 +74,15 @@ int renice_main(int argc, char **argv) } /* Get the priority adjustment (absolute or relative). */ - adjustment = bb_xgetlarg(*argv, 10, INT_MIN, INT_MAX); + adjustment = xatoi(*argv); while (*++argv) { /* Check for a mode switch. */ if ((argv[0][0] == '-') && argv[0][1] && !argv[0][2]) { static const char opts[] = { 'p', 'g', 'u', 0, PRIO_PROCESS, PRIO_PGRP, PRIO_USER }; - const char *p; - if ((p = strchr(opts, argv[0][1]))) { + const char *p = strchr(opts, argv[0][1]); + if (p) { which = p[4]; continue; } @@ -91,16 +91,14 @@ int renice_main(int argc, char **argv) /* Process an ID arg. */ if (which == PRIO_USER) { struct passwd *p; - if (!(p = getpwnam(*argv))) { + p = getpwnam(*argv); + if (!p) { bb_error_msg("unknown user: %s", *argv); goto HAD_ERROR; } who = p->pw_uid; } else { - char *e; - errno = 0; - who = strtoul(*argv, &e, 10); - if (*e || (*argv == e) || errno) { + if (safe_strtou(*argv, &who)) { bb_error_msg("bad value: %s", *argv); goto HAD_ERROR; } diff --git a/procps/top.c b/procps/top.c index be1c45faa..14a3870a1 100644 --- a/procps/top.c +++ b/procps/top.c @@ -384,8 +384,8 @@ static void sig_catcher(int sig ATTRIBUTE_UNUSED) int top_main(int argc, char **argv) { int count, lines, col; - int interval = 5; /* default update rate is 5 seconds */ - int iterations = -1; /* 2^32 iterations by default :) */ + unsigned interval = 5; /* default update rate is 5 seconds */ + unsigned iterations = UINT_MAX; /* 2^32 iterations by default :) */ char *sinterval, *siterations; #ifdef CONFIG_FEATURE_USE_TERMIOS struct termios new_settings; @@ -399,8 +399,8 @@ int top_main(int argc, char **argv) opt_complementary = "-"; getopt32(argc, argv, "d:n:b", &sinterval, &siterations); - if (option_mask32 & 0x1) interval = atoi(sinterval); // -d - if (option_mask32 & 0x2) iterations = atoi(siterations); // -n + if (option_mask32 & 0x1) interval = xatou(sinterval); // -d + if (option_mask32 & 0x2) iterations = xatou(siterations); // -n //if (option_mask32 & 0x4) // -b /* change to /proc */ diff --git a/runit/chpst.c b/runit/chpst.c index 4c44e3c0c..5f30b8815 100644 --- a/runit/chpst.c +++ b/runit/chpst.c @@ -22,7 +22,7 @@ static long limitf = -2; static long limitc = -2; static long limitr = -2; static long limitt = -2; -static long nicelvl; +static int nicelvl; static const char *root; static void suidgid(char *user) @@ -229,16 +229,16 @@ int chpst_main(int argc, char **argv) // if (option_mask32 & 0x1) // -u // if (option_mask32 & 0x2) // -U // if (option_mask32 & 0x4) // -e - if (option_mask32 & 0x8) limits = limitl = limita = limitd = bb_xgetularg10(m); // -m - if (option_mask32 & 0x10) limitd = bb_xgetularg10(d); // -d - if (option_mask32 & 0x20) limito = bb_xgetularg10(o); // -o - if (option_mask32 & 0x40) limitp = bb_xgetularg10(p); // -p - if (option_mask32 & 0x80) limitf = bb_xgetularg10(f); // -f - if (option_mask32 & 0x100) limitc = bb_xgetularg10(c); // -c - if (option_mask32 & 0x200) limitr = bb_xgetularg10(r); // -r - if (option_mask32 & 0x400) limitt = bb_xgetularg10(t); // -t + if (option_mask32 & 0x8) limits = limitl = limita = limitd = xatoul(m); // -m + if (option_mask32 & 0x10) limitd = xatoul(d); // -d + if (option_mask32 & 0x20) limito = xatoul(o); // -o + if (option_mask32 & 0x40) limitp = xatoul(p); // -p + if (option_mask32 & 0x80) limitf = xatoul(f); // -f + if (option_mask32 & 0x100) limitc = xatoul(c); // -c + if (option_mask32 & 0x200) limitr = xatoul(r); // -r + if (option_mask32 & 0x400) limitt = xatoul(t); // -t // if (option_mask32 & 0x800) // -/ - if (option_mask32 & 0x1000) nicelvl = bb_xgetlarg_bnd_sfx(n, 10, -20, 20, NULL); // -n + if (option_mask32 & 0x1000) nicelvl = xatoi(n); // -n // The below consts should match #defines at top! //if (option_mask32 & 0x2000) OPT_verbose = 1; // -v //if (option_mask32 & 0x4000) OPT_pgrp = 1; // -P @@ -312,17 +312,17 @@ static void softlimit(int argc, char **argv) char *a,*c,*d,*f,*l,*m,*o,*p,*r,*s,*t; getopt32(argc, argv, "a:c:d:f:l:m:o:p:r:s:t:", &a,&c,&d,&f,&l,&m,&o,&p,&r,&s,&t); - if (option_mask32 & 0x001) limita = bb_xgetularg10(a); // -a - if (option_mask32 & 0x002) limitc = bb_xgetularg10(c); // -c - if (option_mask32 & 0x004) limitd = bb_xgetularg10(d); // -d - if (option_mask32 & 0x008) limitf = bb_xgetularg10(f); // -f - if (option_mask32 & 0x010) limitl = bb_xgetularg10(l); // -l - if (option_mask32 & 0x020) limits = limitl = limita = limitd = bb_xgetularg10(m); // -m - if (option_mask32 & 0x040) limito = bb_xgetularg10(o); // -o - if (option_mask32 & 0x080) limitp = bb_xgetularg10(p); // -p - if (option_mask32 & 0x100) limitr = bb_xgetularg10(r); // -r - if (option_mask32 & 0x200) limits = bb_xgetularg10(s); // -s - if (option_mask32 & 0x400) limitt = bb_xgetularg10(t); // -t + if (option_mask32 & 0x001) limita = xatoul(a); // -a + if (option_mask32 & 0x002) limitc = xatoul(c); // -c + if (option_mask32 & 0x004) limitd = xatoul(d); // -d + if (option_mask32 & 0x008) limitf = xatoul(f); // -f + if (option_mask32 & 0x010) limitl = xatoul(l); // -l + if (option_mask32 & 0x020) limits = limitl = limita = limitd = xatoul(m); // -m + if (option_mask32 & 0x040) limito = xatoul(o); // -o + if (option_mask32 & 0x080) limitp = xatoul(p); // -p + if (option_mask32 & 0x100) limitr = xatoul(r); // -r + if (option_mask32 & 0x200) limits = xatoul(s); // -s + if (option_mask32 & 0x400) limitt = xatoul(t); // -t argv += optind; if (!argv[0]) bb_show_usage(); slimit(); diff --git a/sysklogd/klogd.c b/sysklogd/klogd.c index e629bec5d..f735d9fc1 100644 --- a/sysklogd/klogd.c +++ b/sysklogd/klogd.c @@ -43,7 +43,6 @@ int klogd_main(int argc, char **argv) int i, n, lastc; char *start; - { unsigned opt; @@ -52,7 +51,7 @@ int klogd_main(int argc, char **argv) if (opt & OPT_LEVEL) { /* Valid levels are between 1 and 8 */ - console_log_level = bb_xgetlarg(start, 10, 1, 8); + console_log_level = xatoul_range(start, 1, 8); } if (!(opt & OPT_FOREGROUND)) { diff --git a/sysklogd/logger.c b/sysklogd/logger.c index 15a4bfb82..8901bd79f 100644 --- a/sysklogd/logger.c +++ b/sysklogd/logger.c @@ -48,14 +48,14 @@ static int decode(char *name, CODE * codetab) CODE *c; if (isdigit(*name)) - return (atoi(name)); + return atoi(name); for (c = codetab; c->c_name; c++) { if (!strcasecmp(name, c->c_name)) { - return (c->c_val); + return c->c_val; } } - return (-1); + return -1; } /* Decode a symbolic name to a numeric value @@ -177,6 +177,3 @@ int logger_main(int argc, char **argv) * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ - - - diff --git a/sysklogd/syslogd.c b/sysklogd/syslogd.c index 254d7e73c..9e030bd63 100644 --- a/sysklogd/syslogd.c +++ b/sysklogd/syslogd.c @@ -575,20 +575,20 @@ int syslogd_main(int argc, char **argv) /* do normal option parsing */ getopt32(argc, argv, OPTION_STR, OPTION_PARAM); - if (option_mask32 & OPT_mark) MarkInterval = atoi(opt_m) * 60; // -m + if (option_mask32 & OPT_mark) MarkInterval = xatoul_range(opt_m, 0, INT_MAX/60) * 60; // -m //if (option_mask32 & OPT_nofork) // -n //if (option_mask32 & OPT_outfile) // -O if (option_mask32 & OPT_loglevel) { // -l - logLevel = atoi(opt_l); + logLevel = xatoi_u(opt_l); /* Valid levels are between 1 and 8 */ if (logLevel < 1 || logLevel > 8) bb_show_usage(); } //if (option_mask32 & OPT_small) // -S #if ENABLE_FEATURE_ROTATE_LOGFILE - if (option_mask32 & OPT_filesize) logFileSize = atoi(opt_s) * 1024; // -s + if (option_mask32 & OPT_filesize) logFileSize = xatoul_range(opt_s, 0, INT_MAX/1024) * 1024; // -s if (option_mask32 & OPT_rotatecnt) { // -b - logFileRotate = atoi(opt_b); + logFileRotate = xatoi_u(opt_b); if (logFileRotate > 99) logFileRotate = 99; } #endif @@ -598,7 +598,7 @@ int syslogd_main(int argc, char **argv) char *host = xstrdup(opt_R); p = strchr(host, ':'); if (p) { - port = atoi(p + 1); + port = xatou16(p + 1); *p = '\0'; } remoteaddr.sin_family = AF_INET; @@ -612,9 +612,7 @@ int syslogd_main(int argc, char **argv) #if ENABLE_FEATURE_IPC_SYSLOG if (option_mask32 & OPT_circularlog) { // -C if (opt_C) { - int buf_size = atoi(opt_C); - if (buf_size >= 4) - shm_size = buf_size * 1024; + shm_size = xatoul_range(opt_C, 4, INT_MAX/1024) * 1024; } } #endif diff --git a/util-linux/dmesg.c b/util-linux/dmesg.c index 277415a2d..658cddc38 100644 --- a/util-linux/dmesg.c +++ b/util-linux/dmesg.c @@ -19,13 +19,13 @@ int dmesg_main(int argc, char *argv[]) int flags = getopt32(argc, argv, "cs:n:", &size, &level); if (flags & 4) { - if (klogctl(8, NULL, bb_xgetlarg(level, 10, 0, 10))) + if (klogctl(8, NULL, xatoul_range(level, 0, 10))) bb_perror_msg_and_die("klogctl"); } else { int len; char *buf; - len = (flags & 2) ? bb_xgetlarg(size, 10, 2, INT_MAX) : 16384; + len = (flags & 2) ? xatoul_range(size, 2, INT_MAX) : 16384; buf = xmalloc(len); if (0 > (len = klogctl(3 + (flags & 1), buf, len))) bb_perror_msg_and_die("klogctl"); diff --git a/util-linux/fbset.c b/util-linux/fbset.c index bc8ec1806..1aa0a0ac1 100644 --- a/util-linux/fbset.c +++ b/util-linux/fbset.c @@ -338,20 +338,20 @@ int fbset_main(int argc, char **argv) modefile = argv[1]; break; case CMD_GEOMETRY: - varset.xres = strtoul(argv[1], 0, 0); - varset.yres = strtoul(argv[2], 0, 0); - varset.xres_virtual = strtoul(argv[3], 0, 0); - varset.yres_virtual = strtoul(argv[4], 0, 0); - varset.bits_per_pixel = strtoul(argv[5], 0, 0); + varset.xres = xatou32(argv[1]); + varset.yres = xatou32(argv[2]); + varset.xres_virtual = xatou32(argv[3]); + varset.yres_virtual = xatou32(argv[4]); + varset.bits_per_pixel = xatou32(argv[5]); break; case CMD_TIMING: - varset.pixclock = strtoul(argv[1], 0, 0); - varset.left_margin = strtoul(argv[2], 0, 0); - varset.right_margin = strtoul(argv[3], 0, 0); - varset.upper_margin = strtoul(argv[4], 0, 0); - varset.lower_margin = strtoul(argv[5], 0, 0); - varset.hsync_len = strtoul(argv[6], 0, 0); - varset.vsync_len = strtoul(argv[7], 0, 0); + varset.pixclock = xatou32(argv[1]); + varset.left_margin = xatou32(argv[2]); + varset.right_margin = xatou32(argv[3]); + varset.upper_margin = xatou32(argv[4]); + varset.lower_margin = xatou32(argv[5]); + varset.hsync_len = xatou32(argv[6]); + varset.vsync_len = xatou32(argv[7]); break; case CMD_ALL: g_options |= OPT_ALL; @@ -361,13 +361,13 @@ int fbset_main(int argc, char **argv) break; #ifdef CONFIG_FEATURE_FBSET_FANCY case CMD_XRES: - varset.xres = strtoul(argv[1], 0, 0); + varset.xres = xatou32(argv[1]); break; case CMD_YRES: - varset.yres = strtoul(argv[1], 0, 0); + varset.yres = xatou32(argv[1]); break; case CMD_DEPTH: - varset.bits_per_pixel = strtoul(argv[1], 0, 0); + varset.bits_per_pixel = xatou32(argv[1]); break; #endif } diff --git a/util-linux/fdisk.c b/util-linux/fdisk.c index 85acaa4aa..3bf78ee04 100644 --- a/util-linux/fdisk.c +++ b/util-linux/fdisk.c @@ -1222,8 +1222,7 @@ edit_int(int def, char *mesg) printf(" (%d): ", def); if (!read_line()) return def; - } - while (!isdigit(*line_ptr)); /* FIXME: ?!! */ + } while (!isdigit(*line_ptr)); return atoi(line_ptr); } @@ -5664,14 +5663,14 @@ int fdisk_main(int argc, char **argv) #ifdef CONFIG_FEATURE_FDISK_BLKSIZE "s" #endif - )) != -1) { + )) != -1) { switch (c) { case 'b': /* Ugly: this sector size is really per device, so cannot be combined with multiple disks, and te same goes for the C/H/S options. */ - sector_size = atoi(optarg); + sector_size = xatoi_u(optarg); if (sector_size != 512 && sector_size != 1024 && sector_size != 2048) bb_show_usage(); @@ -5679,15 +5678,15 @@ int fdisk_main(int argc, char **argv) user_set_sector_size = 1; break; case 'C': - user_cylinders = atoi(optarg); + user_cylinders = xatoi_u(optarg); break; case 'H': - user_heads = atoi(optarg); + user_heads = xatoi_u(optarg); if (user_heads <= 0 || user_heads >= 256) user_heads = 0; break; case 'S': - user_sectors = atoi(optarg); + user_sectors = xatoi_u(optarg); if (user_sectors <= 0 || user_sectors >= 64) user_sectors = 0; break; diff --git a/util-linux/hexdump.c b/util-linux/hexdump.c index e038005f5..03b222dd0 100644 --- a/util-linux/hexdump.c +++ b/util-linux/hexdump.c @@ -79,10 +79,10 @@ int hexdump_main(int argc, char **argv) bb_dump_addfile(optarg); } /* else */ if (ch == 'n') { - bb_dump_length = bb_xgetularg10_bnd(optarg, 0, INT_MAX); + bb_dump_length = xatoi_u(optarg); } /* else */ if (ch == 's') { - bb_dump_skip = bb_xgetularg_bnd_sfx(optarg, 10, 0, LONG_MAX, suffixes); + bb_dump_skip = xatoul_range_sfx(optarg, 0, LONG_MAX, suffixes); } /* else */ if (ch == 'v') { bb_dump_vflag = ALL; diff --git a/util-linux/ipcs.c b/util-linux/ipcs.c index 5e58e81da..ba81ea97c 100644 --- a/util-linux/ipcs.c +++ b/util-linux/ipcs.c @@ -581,7 +581,7 @@ int ipcs_main(int argc, char **argv) opt = getopt32(argc, argv, "i:aqsmtcplu", &opt_i); if (opt & 0x1) { // -i - id = atoi(opt_i); + id = xatoi(opt_i); flags |= flag_print; } if (opt & 0x2) flags |= flag_msg | flag_sem | flag_shm; // -a diff --git a/util-linux/losetup.c b/util-linux/losetup.c index 8882ee4da..c7eb85a91 100644 --- a/util-linux/losetup.c +++ b/util-linux/losetup.c @@ -16,7 +16,7 @@ int losetup_main(int argc, char **argv) { unsigned opt; char *opt_o; - int offset = 0; + unsigned long long offset = 0; opt = getopt32(argc, argv, "do:", &opt_o); argc -= optind; @@ -35,7 +35,7 @@ int losetup_main(int argc, char **argv) } if (opt == 0x2) // -o - offset = bb_xparse_number(opt_o, NULL); + offset = xatoull(opt_o); /* -o or no option */ diff --git a/util-linux/mount.c b/util-linux/mount.c index 141517ba0..531fb4520 100644 --- a/util-linux/mount.c +++ b/util-linux/mount.c @@ -856,7 +856,7 @@ static int nfsmount(struct mntent *mp, int vfsflags, char *filteropts) for (opt = strtok(filteropts, ","); opt; opt = strtok(NULL, ",")) { char *opteq = strchr(opt, '='); if (opteq) { - int val = atoi(opteq + 1); + int val = xatoi_u(opteq + 1); *opteq = '\0'; if (!strcmp(opt, "rsize")) data.rsize = val; diff --git a/util-linux/readprofile.c b/util-linux/readprofile.c index ff70bf79b..b368067ef 100644 --- a/util-linux/readprofile.c +++ b/util-linux/readprofile.c @@ -38,8 +38,8 @@ #define S_LEN 128 /* These are the defaults */ -static const char defaultmap[]="/boot/System.map"; -static const char defaultpro[]="/proc/profile"; +static const char defaultmap[] = "/boot/System.map"; +static const char defaultpro[] = "/proc/profile"; int readprofile_main(int argc, char **argv) { @@ -78,7 +78,7 @@ int readprofile_main(int argc, char **argv) * not sizeof(int), the multiplier is not changed */ if (mult) { - multiplier = strtoul(mult, 0, 10); + multiplier = xatoi_u(mult); to_write = sizeof(int); } else { multiplier = 0; -- 2.25.1