Major coreutils update.

1_00_stable_10817
Manuel Novoa III 2003-03-19 09:13:01 +00:00
parent e01f9662a5
commit cad5364599
295 changed files with 6944 additions and 5570 deletions

View File

@ -29,7 +29,7 @@ include Rules.mak
DIRS:=applets archival archival/libunarchive coreutils console-tools \ DIRS:=applets archival archival/libunarchive coreutils console-tools \
debianutils editors findutils init miscutils modutils networking \ debianutils editors findutils init miscutils modutils networking \
networking/libiproute networking/udhcp procps loginutils shell \ networking/libiproute networking/udhcp procps loginutils shell \
sysklogd util-linux libbb libpwdgrp sysklogd util-linux libbb libpwdgrp coreutils/libcoreutils
ifeq ($(strip $(HAVE_DOT_CONFIG)),y) ifeq ($(strip $(HAVE_DOT_CONFIG)),y)

View File

@ -78,7 +78,7 @@ static struct BB_suid_config *suid_config;
extern void show_usage(void) extern void bb_show_usage(void)
{ {
const char *format_string; const char *format_string;
const char *usage_string = usage_messages; const char *usage_string = usage_messages;
@ -93,7 +93,7 @@ extern void show_usage(void)
format_string = "%s\n\nUsage: %s %s\n\n"; format_string = "%s\n\nUsage: %s %s\n\n";
if(*usage_string == '\b') if(*usage_string == '\b')
format_string = "%s\n\nNo help available.\n\n"; format_string = "%s\n\nNo help available.\n\n";
fprintf(stderr, format_string, full_version, applet_using->name, usage_string); fprintf(stderr, format_string, bb_msg_full_version, applet_using->name, usage_string);
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} }
@ -127,7 +127,7 @@ void run_applet_by_name(const char *name, int argc, char **argv)
recurse_level++; recurse_level++;
/* Do a binary search to find the applet entry given the name. */ /* Do a binary search to find the applet entry given the name. */
if ((applet_using = find_applet_by_name(name)) != NULL) { if ((applet_using = find_applet_by_name(name)) != NULL) {
applet_name = applet_using->name; bb_applet_name = applet_using->name;
if (argv[1] && strcmp(argv[1], "--help") == 0) { if (argv[1] && strcmp(argv[1], "--help") == 0) {
if (strcmp(applet_using->name, "busybox")==0) { if (strcmp(applet_using->name, "busybox")==0) {
if(argv[2]) if(argv[2])
@ -136,7 +136,7 @@ void run_applet_by_name(const char *name, int argc, char **argv)
applet_using = NULL; applet_using = NULL;
} }
if(applet_using) if(applet_using)
show_usage(); bb_show_usage();
been_there_done_that=1; been_there_done_that=1;
busybox_main(0, NULL); busybox_main(0, NULL);
} }
@ -201,18 +201,18 @@ void check_suid ( struct BB_applet *applet )
m >>= 3; m >>= 3;
if (!( m & S_IXOTH )) /* is x bit not set ? */ if (!( m & S_IXOTH )) /* is x bit not set ? */
error_msg_and_die ( "You have no permission to run this applet!" ); bb_error_msg_and_die ( "You have no permission to run this applet!" );
if (( sct-> m_mode & ( S_ISGID | S_IXGRP )) == ( S_ISGID | S_IXGRP )) { /* *both* have to be set for sgid */ if (( sct-> m_mode & ( S_ISGID | S_IXGRP )) == ( S_ISGID | S_IXGRP )) { /* *both* have to be set for sgid */
if ( setegid ( sct-> m_gid )) if ( setegid ( sct-> m_gid ))
error_msg_and_die ( "BusyBox binary has insufficient rights to set proper GID for applet!" ); bb_error_msg_and_die ( "BusyBox binary has insufficient rights to set proper GID for applet!" );
} }
else else
setgid ( rgid ); /* no sgid -> drop */ setgid ( rgid ); /* no sgid -> drop */
if ( sct-> m_mode & S_ISUID ) { if ( sct-> m_mode & S_ISUID ) {
if ( seteuid ( sct-> m_uid )) if ( seteuid ( sct-> m_uid ))
error_msg_and_die ( "BusyBox binary has insufficient rights to set proper UID for applet!" ); bb_error_msg_and_die ( "BusyBox binary has insufficient rights to set proper UID for applet!" );
} }
else else
setuid ( ruid ); /* no suid -> drop */ setuid ( ruid ); /* no suid -> drop */
@ -237,7 +237,7 @@ void check_suid ( struct BB_applet *applet )
if ( applet-> need_suid == _BB_SUID_ALWAYS ) { if ( applet-> need_suid == _BB_SUID_ALWAYS ) {
if ( geteuid ( ) != 0 ) if ( geteuid ( ) != 0 )
error_msg_and_die ( "This applet requires root priviledges!" ); bb_error_msg_and_die ( "This applet requires root priviledges!" );
} }
else if ( applet-> need_suid == _BB_SUID_NEVER ) { else if ( applet-> need_suid == _BB_SUID_NEVER ) {
setgid ( rgid ); /* drop all priviledges */ setgid ( rgid ); /* drop all priviledges */
@ -280,7 +280,7 @@ int parse_config_file ( void )
p = strchr ( buffer, '#' ); p = strchr ( buffer, '#' );
if ( p ) if ( p )
*p = 0; *p = 0;
p = buffer + xstrlen ( buffer ); p = buffer + bb_strlen ( buffer );
while (( p > buffer ) && isspace ( *--p )) while (( p > buffer ) && isspace ( *--p ))
*p = 0; *p = 0;

View File

@ -10,7 +10,7 @@
#endif #endif
int been_there_done_that = 0; /* Also used in applets.c */ int been_there_done_that = 0; /* Also used in applets.c */
const char *applet_name; const char *bb_applet_name;
#ifdef CONFIG_FEATURE_INSTALLER #ifdef CONFIG_FEATURE_INSTALLER
/* /*
@ -60,7 +60,7 @@ static void install_links(const char *busybox, int use_symbolic_links)
install_dir[applets[i].location], applets[i].name); install_dir[applets[i].location], applets[i].name);
rc = Link(busybox, fpc); rc = Link(busybox, fpc);
if (rc!=0 && errno!=EEXIST) { if (rc!=0 && errno!=EEXIST) {
perror_msg("%s", fpc); bb_perror_msg("%s", fpc);
} }
free(fpc); free(fpc);
} }
@ -72,14 +72,14 @@ int main(int argc, char **argv)
{ {
const char *s; const char *s;
applet_name = argv[0]; bb_applet_name = argv[0];
if (applet_name[0] == '-') if (bb_applet_name[0] == '-')
applet_name++; bb_applet_name++;
for (s = applet_name; *s != '\0';) { for (s = bb_applet_name; *s != '\0';) {
if (*s++ == '/') if (*s++ == '/')
applet_name = s; bb_applet_name = s;
} }
#ifdef CONFIG_LOCALE_SUPPORT #ifdef CONFIG_LOCALE_SUPPORT
@ -91,8 +91,8 @@ int main(int argc, char **argv)
} }
#endif #endif
run_applet_by_name(applet_name, argc, argv); run_applet_by_name(bb_applet_name, argc, argv);
error_msg_and_die("applet not found"); bb_error_msg_and_die("applet not found");
} }
@ -143,7 +143,7 @@ int busybox_main(int argc, char **argv)
"\tutilities into a single executable. Most people will create a\n" "\tutilities into a single executable. Most people will create a\n"
"\tlink to busybox for each function they wish to use, and BusyBox\n" "\tlink to busybox for each function they wish to use, and BusyBox\n"
"\twill act like whatever it was invoked as.\n" "\twill act like whatever it was invoked as.\n"
"\nCurrently defined functions:\n", full_version); "\nCurrently defined functions:\n", bb_msg_full_version);
while (a->name != 0) { while (a->name != 0) {
col += col +=

View File

@ -40,7 +40,7 @@
static void header_verbose_list_ar(const file_header_t *file_header) static void header_verbose_list_ar(const file_header_t *file_header)
{ {
const char *mode = mode_string(file_header->mode); const char *mode = bb_mode_string(file_header->mode);
char *mtime; char *mtime;
mtime = ctime(&file_header->mtime); mtime = ctime(&file_header->mtime);
@ -58,7 +58,7 @@ static void data_extract_regular_file(archive_handle_t *archive_handle)
int dst_fd; int dst_fd;
file_header = archive_handle->file_header; file_header = archive_handle->file_header;
dst_fd = xopen(file_header->name, O_WRONLY | O_CREAT); dst_fd = bb_xopen(file_header->name, O_WRONLY | O_CREAT);
archive_copy_file(archive_handle, dst_fd); archive_copy_file(archive_handle, dst_fd);
close(dst_fd); close(dst_fd);
@ -110,16 +110,16 @@ extern int ar_main(int argc, char **argv)
archive_handle->action_header = header_verbose_list_ar; archive_handle->action_header = header_verbose_list_ar;
break; break;
default: default:
show_usage(); bb_show_usage();
} }
} }
/* check the src filename was specified */ /* check the src filename was specified */
if (optind == argc) { if (optind == argc) {
show_usage(); bb_show_usage();
} }
archive_handle->src_fd = xopen(argv[optind++], O_RDONLY); archive_handle->src_fd = bb_xopen(argv[optind++], O_RDONLY);
/* TODO: This is the same as in tar, seperate function ? */ /* TODO: This is the same as in tar, seperate function ? */
while (optind < argc) { while (optind < argc) {
@ -133,7 +133,7 @@ extern int ar_main(int argc, char **argv)
#else #else
archive_xread_all(archive_handle, magic, 7); archive_xread_all(archive_handle, magic, 7);
if (strncmp(magic, "!<arch>", 7) != 0) { if (strncmp(magic, "!<arch>", 7) != 0) {
error_msg_and_die("Invalid ar magic"); bb_error_msg_and_die("Invalid ar magic");
} }
archive_handle->offset += 7; archive_handle->offset += 7;

View File

@ -41,7 +41,7 @@ int bunzip2_main(int argc, char **argv)
char *delete_name = NULL; char *delete_name = NULL;
/* if called as bzcat */ /* if called as bzcat */
if (strcmp(applet_name, "bzcat") == 0) if (strcmp(bb_applet_name, "bzcat") == 0)
flags |= bunzip_to_stdout; flags |= bunzip_to_stdout;
while ((opt = getopt(argc, argv, "cfh")) != -1) { while ((opt = getopt(argc, argv, "cfh")) != -1) {
@ -54,7 +54,7 @@ int bunzip2_main(int argc, char **argv)
break; break;
case 'h': case 'h':
default: default:
show_usage(); /* exit's inside usage */ bb_show_usage(); /* exit's inside usage */
} }
} }
@ -64,23 +64,23 @@ int bunzip2_main(int argc, char **argv)
src_fd = fileno(stdin); src_fd = fileno(stdin);
} else { } else {
/* Open input file */ /* Open input file */
src_fd = xopen(argv[optind], O_RDONLY); src_fd = bb_xopen(argv[optind], O_RDONLY);
save_name = xstrdup(argv[optind]); save_name = bb_xstrdup(argv[optind]);
if (strcmp(save_name + strlen(save_name) - 4, ".bz2") != 0) if (strcmp(save_name + strlen(save_name) - 4, ".bz2") != 0)
error_msg_and_die("Invalid extension"); bb_error_msg_and_die("Invalid extension");
save_name[strlen(save_name) - 4] = '\0'; save_name[strlen(save_name) - 4] = '\0';
} }
/* Check that the input is sane. */ /* Check that the input is sane. */
if (isatty(src_fd) && (flags & bunzip_force) == 0) { if (isatty(src_fd) && (flags & bunzip_force) == 0) {
error_msg_and_die("compressed data not read from terminal. Use -f to force it."); bb_error_msg_and_die("compressed data not read from terminal. Use -f to force it.");
} }
if (flags & bunzip_to_stdout) { if (flags & bunzip_to_stdout) {
dst_fd = fileno(stdout); dst_fd = fileno(stdout);
} else { } else {
dst_fd = xopen(save_name, O_WRONLY | O_CREAT); dst_fd = bb_xopen(save_name, O_WRONLY | O_CREAT);
} }
if (uncompressStream(src_fd, dst_fd)) { if (uncompressStream(src_fd, dst_fd)) {
@ -96,7 +96,7 @@ int bunzip2_main(int argc, char **argv)
} }
if ((delete_name) && (unlink(delete_name) < 0)) { if ((delete_name) && (unlink(delete_name) < 0)) {
error_msg_and_die("Couldn't remove %s", delete_name); bb_error_msg_and_die("Couldn't remove %s", delete_name);
} }
return status; return status;

View File

@ -63,11 +63,11 @@ extern int cpio_main(int argc, char **argv)
archive_handle->action_header = header_list; archive_handle->action_header = header_list;
break; break;
case 'F': case 'F':
archive_handle->src_fd = xopen(optarg, O_RDONLY); archive_handle->src_fd = bb_xopen(optarg, O_RDONLY);
archive_handle->seek = seek_by_jump; archive_handle->seek = seek_by_jump;
break; break;
default: default:
show_usage(); bb_show_usage();
} }
} }

View File

@ -177,7 +177,7 @@ int search_name_hashtable(const char *key)
} }
} }
} }
name_hashtable[probe_address] = xstrdup(key); name_hashtable[probe_address] = bb_xstrdup(key);
return(probe_address); return(probe_address);
} }
@ -218,10 +218,10 @@ int version_compare_part(const char *version1, const char *version2)
int ret; int ret;
if (version1 == NULL) { if (version1 == NULL) {
version1 = xstrdup(""); version1 = bb_xstrdup("");
} }
if (version2 == NULL) { if (version2 == NULL) {
version2 = xstrdup(""); version2 = bb_xstrdup("");
} }
upstream_len1 = strlen(version1); upstream_len1 = strlen(version1);
upstream_len2 = strlen(version2); upstream_len2 = strlen(version2);
@ -229,10 +229,10 @@ int version_compare_part(const char *version1, const char *version2)
while ((len1 < upstream_len1) || (len2 < upstream_len2)) { while ((len1 < upstream_len1) || (len2 < upstream_len2)) {
/* Compare non-digit section */ /* Compare non-digit section */
tmp_int = strcspn(&version1[len1], "0123456789"); tmp_int = strcspn(&version1[len1], "0123456789");
name1_char = xstrndup(&version1[len1], tmp_int); name1_char = bb_xstrndup(&version1[len1], tmp_int);
len1 += tmp_int; len1 += tmp_int;
tmp_int = strcspn(&version2[len2], "0123456789"); tmp_int = strcspn(&version2[len2], "0123456789");
name2_char = xstrndup(&version2[len2], tmp_int); name2_char = bb_xstrndup(&version2[len2], tmp_int);
len2 += tmp_int; len2 += tmp_int;
tmp_int = strcmp(name1_char, name2_char); tmp_int = strcmp(name1_char, name2_char);
free(name1_char); free(name1_char);
@ -244,10 +244,10 @@ int version_compare_part(const char *version1, const char *version2)
/* Compare digits */ /* Compare digits */
tmp_int = strspn(&version1[len1], "0123456789"); tmp_int = strspn(&version1[len1], "0123456789");
name1_char = xstrndup(&version1[len1], tmp_int); name1_char = bb_xstrndup(&version1[len1], tmp_int);
len1 += tmp_int; len1 += tmp_int;
tmp_int = strspn(&version2[len2], "0123456789"); tmp_int = strspn(&version2[len2], "0123456789");
name2_char = xstrndup(&version2[len2], tmp_int); name2_char = bb_xstrndup(&version2[len2], tmp_int);
len2 += tmp_int; len2 += tmp_int;
ver_num1 = atoi(name1_char); ver_num1 = atoi(name1_char);
ver_num2 = atoi(name2_char); ver_num2 = atoi(name2_char);
@ -306,8 +306,8 @@ int version_compare(const unsigned int ver1, const unsigned int ver2)
} }
/* Compare upstream version */ /* Compare upstream version */
upstream_ver1 = xstrdup(ver1_ptr); upstream_ver1 = bb_xstrdup(ver1_ptr);
upstream_ver2 = xstrdup(ver2_ptr); upstream_ver2 = bb_xstrdup(ver2_ptr);
/* Chop off debian version, and store for later use */ /* Chop off debian version, and store for later use */
deb_ver1 = strrchr(upstream_ver1, '-'); deb_ver1 = strrchr(upstream_ver1, '-');
@ -397,7 +397,7 @@ int search_package_hashtable(const unsigned int name, const unsigned int version
*/ */
void add_split_dependencies(common_node_t *parent_node, const char *whole_line, unsigned int edge_type) void add_split_dependencies(common_node_t *parent_node, const char *whole_line, unsigned int edge_type)
{ {
char *line = xstrdup(whole_line); char *line = bb_xstrdup(whole_line);
char *line2; char *line2;
char *line_ptr1 = NULL; char *line_ptr1 = NULL;
char *line_ptr2 = NULL; char *line_ptr2 = NULL;
@ -410,7 +410,7 @@ void add_split_dependencies(common_node_t *parent_node, const char *whole_line,
field = strtok_r(line, ",", &line_ptr1); field = strtok_r(line, ",", &line_ptr1);
do { do {
line2 = xstrdup(field); line2 = bb_xstrdup(field);
field2 = strtok_r(line2, "|", &line_ptr2); field2 = strtok_r(line2, "|", &line_ptr2);
if ((edge_type == EDGE_DEPENDS) && (strcmp(field, field2) != 0)) { if ((edge_type == EDGE_DEPENDS) && (strcmp(field, field2) != 0)) {
type = EDGE_OR_DEPENDS; type = EDGE_OR_DEPENDS;
@ -457,7 +457,7 @@ void add_split_dependencies(common_node_t *parent_node, const char *whole_line,
else if (strncmp(version, ">=", offset_ch) == 0) { else if (strncmp(version, ">=", offset_ch) == 0) {
edge->operator = VER_MORE_EQUAL; edge->operator = VER_MORE_EQUAL;
} else { } else {
error_msg_and_die("Illegal operator\n"); bb_error_msg_and_die("Illegal operator\n");
} }
} }
/* skip to start of version numbers */ /* skip to start of version numbers */
@ -588,7 +588,7 @@ unsigned int get_status(const unsigned int status_node, const int num)
status_string += strspn(status_string, " "); status_string += strspn(status_string, " ");
} }
len = strcspn(status_string, " \n\0"); len = strcspn(status_string, " \n\0");
state_sub_string = xstrndup(status_string, len); state_sub_string = bb_xstrndup(status_string, len);
state_sub_num = search_name_hashtable(state_sub_string); state_sub_num = search_name_hashtable(state_sub_string);
free(state_sub_string); free(state_sub_string);
return(state_sub_num); return(state_sub_num);
@ -620,7 +620,7 @@ void set_status(const unsigned int status_node_num, const char *new_value, const
status_len = new_value_len; status_len = new_value_len;
break; break;
default: default:
error_msg_and_die("DEBUG ONLY: this shouldnt happen"); bb_error_msg_and_die("DEBUG ONLY: this shouldnt happen");
} }
new_status = (char *) xmalloc(want_len + flag_len + status_len + 3); new_status = (char *) xmalloc(want_len + flag_len + status_len + 3);
@ -638,7 +638,7 @@ void index_status_file(const char *filename)
status_node_t *status_node = NULL; status_node_t *status_node = NULL;
unsigned int status_num; unsigned int status_num;
status_file = xfopen(filename, "r"); status_file = bb_xfopen(filename, "r");
while ((control_buffer = fgets_str(status_file, "\n\n")) != NULL) { while ((control_buffer = fgets_str(status_file, "\n\n")) != NULL) {
const unsigned int package_num = fill_package_struct(control_buffer); const unsigned int package_num = fill_package_struct(control_buffer);
if (package_num != -1) { if (package_num != -1) {
@ -648,7 +648,7 @@ void index_status_file(const char *filename)
if (status_line != NULL) { if (status_line != NULL) {
status_line += 7; status_line += 7;
status_line += strspn(status_line, " \n\t"); status_line += strspn(status_line, " \n\t");
status_line = xstrndup(status_line, strcspn(status_line, "\n\0")); status_line = bb_xstrndup(status_line, strcspn(status_line, "\n\0"));
status_node->status = search_name_hashtable(status_line); status_node->status = search_name_hashtable(status_line);
free(status_line); free(status_line);
} }
@ -754,8 +754,8 @@ void write_buffer_no_status(FILE *new_status_file, const char *control_buffer)
/* This could do with a cleanup */ /* This could do with a cleanup */
void write_status_file(deb_file_t **deb_file) void write_status_file(deb_file_t **deb_file)
{ {
FILE *old_status_file = xfopen("/var/lib/dpkg/status", "r"); FILE *old_status_file = bb_xfopen("/var/lib/dpkg/status", "r");
FILE *new_status_file = xfopen("/var/lib/dpkg/status.udeb", "w"); FILE *new_status_file = bb_xfopen("/var/lib/dpkg/status.udeb", "w");
char *package_name; char *package_name;
char *status_from_file; char *status_from_file;
char *control_buffer = NULL; char *control_buffer = NULL;
@ -773,14 +773,14 @@ void write_status_file(deb_file_t **deb_file)
tmp_string += 8; tmp_string += 8;
tmp_string += strspn(tmp_string, " \n\t"); tmp_string += strspn(tmp_string, " \n\t");
package_name = xstrndup(tmp_string, strcspn(tmp_string, "\n\0")); package_name = bb_xstrndup(tmp_string, strcspn(tmp_string, "\n\0"));
write_flag = FALSE; write_flag = FALSE;
tmp_string = strstr(control_buffer, "Status:"); tmp_string = strstr(control_buffer, "Status:");
if (tmp_string != NULL) { if (tmp_string != NULL) {
/* Seperate the status value from the control buffer */ /* Seperate the status value from the control buffer */
tmp_string += 7; tmp_string += 7;
tmp_string += strspn(tmp_string, " \n\t"); tmp_string += strspn(tmp_string, " \n\t");
status_from_file = xstrndup(tmp_string, strcspn(tmp_string, "\n")); status_from_file = bb_xstrndup(tmp_string, strcspn(tmp_string, "\n"));
} else { } else {
status_from_file = NULL; status_from_file = NULL;
} }
@ -810,7 +810,7 @@ void write_status_file(deb_file_t **deb_file)
} }
/* This is temperary, debugging only */ /* This is temperary, debugging only */
if (deb_file[i] == NULL) { if (deb_file[i] == NULL) {
error_msg_and_die("ALERT: Couldnt find a control file, your status file may be broken, status may be incorrect for %s", package_name); bb_error_msg_and_die("ALERT: Couldnt find a control file, your status file may be broken, status may be incorrect for %s", package_name);
} }
} }
else if (strcmp("not-installed", name_hashtable[state_status]) == 0) { else if (strcmp("not-installed", name_hashtable[state_status]) == 0) {
@ -881,15 +881,15 @@ void write_status_file(deb_file_t **deb_file)
if (rename("/var/lib/dpkg/status", "/var/lib/dpkg/status.udeb.bak") == -1) { if (rename("/var/lib/dpkg/status", "/var/lib/dpkg/status.udeb.bak") == -1) {
struct stat stat_buf; struct stat stat_buf;
if (stat("/var/lib/dpkg/status", &stat_buf) == 0) { if (stat("/var/lib/dpkg/status", &stat_buf) == 0) {
error_msg_and_die("Couldnt create backup status file"); bb_error_msg_and_die("Couldnt create backup status file");
} }
/* Its ok if renaming the status file fails becasue status /* Its ok if renaming the status file fails becasue status
* file doesnt exist, maybe we are starting from scratch */ * file doesnt exist, maybe we are starting from scratch */
error_msg("No status file found, creating new one"); bb_error_msg("No status file found, creating new one");
} }
if (rename("/var/lib/dpkg/status.udeb", "/var/lib/dpkg/status") == -1) { if (rename("/var/lib/dpkg/status.udeb", "/var/lib/dpkg/status") == -1) {
error_msg_and_die("DANGER: Couldnt create status file, you need to manually repair your status file"); bb_error_msg_and_die("DANGER: Couldnt create status file, you need to manually repair your status file");
} }
} }
@ -976,7 +976,7 @@ int check_deps(deb_file_t **deb_file, int deb_start, int dep_max_count)
} }
if (result) { if (result) {
error_msg_and_die("Package %s conflicts with %s", bb_error_msg_and_die("Package %s conflicts with %s",
name_hashtable[package_node->name], name_hashtable[package_node->name],
name_hashtable[package_edge->name]); name_hashtable[package_edge->name]);
} }
@ -1021,7 +1021,7 @@ int check_deps(deb_file_t **deb_file, int deb_start, int dep_max_count)
} }
if (result) { if (result) {
error_msg_and_die("Package %s pre-depends on %s, but it is not installed", bb_error_msg_and_die("Package %s pre-depends on %s, but it is not installed",
name_hashtable[package_node->name], name_hashtable[package_node->name],
name_hashtable[package_edge->name]); name_hashtable[package_edge->name]);
} }
@ -1038,7 +1038,7 @@ int check_deps(deb_file_t **deb_file, int deb_start, int dep_max_count)
} }
/* It must be already installed, or to be installed */ /* It must be already installed, or to be installed */
if (result) { if (result) {
error_msg_and_die("Package %s depends on %s, but it is not installed, or flaged to be installed", bb_error_msg_and_die("Package %s depends on %s, but it is not installed, or flaged to be installed",
name_hashtable[package_node->name], name_hashtable[package_node->name],
name_hashtable[package_edge->name]); name_hashtable[package_edge->name]);
} }
@ -1065,9 +1065,8 @@ char **create_list(const char *filename)
return(NULL); return(NULL);
} }
while ((line = get_line_from_file(list_stream)) != NULL) { while ((line = bb_get_chomped_line_from_file(list_stream)) != NULL) {
file_list = xrealloc(file_list, sizeof(char *) * (count + 2)); file_list = xrealloc(file_list, sizeof(char *) * (count + 2));
chomp(line);
file_list[count] = line; file_list[count] = line;
count++; count++;
} }
@ -1228,7 +1227,7 @@ void remove_package(const unsigned int package_num)
/* run prerm script */ /* run prerm script */
return_value = run_package_script(package_name, "prerm"); return_value = run_package_script(package_name, "prerm");
if (return_value == -1) { if (return_value == -1) {
error_msg_and_die("script failed, prerm failure"); bb_error_msg_and_die("script failed, prerm failure");
} }
/* Create a list of files to remove, and a seperate list of those to keep */ /* Create a list of files to remove, and a seperate list of those to keep */
@ -1245,7 +1244,7 @@ void remove_package(const unsigned int package_num)
/* Create a list of files in /var/lib/dpkg/info/<package>.* to keep */ /* Create a list of files in /var/lib/dpkg/info/<package>.* to keep */
exclude_files = xmalloc(sizeof(char*) * 3); exclude_files = xmalloc(sizeof(char*) * 3);
exclude_files[0] = xstrdup(conffile_name); exclude_files[0] = bb_xstrdup(conffile_name);
exclude_files[1] = xmalloc(package_name_length + 27); exclude_files[1] = xmalloc(package_name_length + 27);
sprintf(exclude_files[1], "/var/lib/dpkg/info/%s.postrm", package_name); sprintf(exclude_files[1], "/var/lib/dpkg/info/%s.postrm", package_name);
exclude_files[2] = NULL; exclude_files[2] = NULL;
@ -1275,7 +1274,7 @@ void purge_package(const unsigned int package_num)
/* run prerm script */ /* run prerm script */
if (run_package_script(package_name, "prerm") != 0) { if (run_package_script(package_name, "prerm") != 0) {
error_msg_and_die("script failed, prerm failure"); bb_error_msg_and_die("script failed, prerm failure");
} }
/* Create a list of files to remove */ /* Create a list of files to remove */
@ -1297,7 +1296,7 @@ void purge_package(const unsigned int package_num)
/* run postrm script */ /* run postrm script */
if (run_package_script(package_name, "postrm") == -1) { if (run_package_script(package_name, "postrm") == -1) {
error_msg_and_die("postrm fialure.. set status to what?"); bb_error_msg_and_die("postrm fialure.. set status to what?");
} }
/* Change package status */ /* Change package status */
@ -1312,7 +1311,7 @@ static archive_handle_t *init_archive_deb_ar(const char *filename)
/* Setup an ar archive handle that refers to the gzip sub archive */ /* Setup an ar archive handle that refers to the gzip sub archive */
ar_handle = init_handle(); ar_handle = init_handle();
ar_handle->filter = filter_accept_list_reassign; ar_handle->filter = filter_accept_list_reassign;
ar_handle->src_fd = xopen(filename, O_RDONLY); ar_handle->src_fd = bb_xopen(filename, O_RDONLY);
return(ar_handle); return(ar_handle);
} }
@ -1420,7 +1419,7 @@ static void unpack_package(deb_file_t *deb_file)
/* Run the preinst prior to extracting */ /* Run the preinst prior to extracting */
if (run_package_script(package_name, "preinst") != 0) { if (run_package_script(package_name, "preinst") != 0) {
/* when preinst returns exit code != 0 then quit installation process */ /* when preinst returns exit code != 0 then quit installation process */
error_msg_and_die("subprocess pre-installation script returned error."); bb_error_msg_and_die("subprocess pre-installation script returned error.");
} }
/* Extract data.tar.gz to the root directory */ /* Extract data.tar.gz to the root directory */
@ -1430,7 +1429,7 @@ static void unpack_package(deb_file_t *deb_file)
/* Create the list file */ /* Create the list file */
strcat(info_prefix, "list"); strcat(info_prefix, "list");
out_stream = xfopen(info_prefix, "w"); out_stream = bb_xfopen(info_prefix, "w");
while (archive_handle->passed) { while (archive_handle->passed) {
/* blindly skip over the leading '.' */ /* blindly skip over the leading '.' */
fputs(archive_handle->passed->data + 1, out_stream); fputs(archive_handle->passed->data + 1, out_stream);
@ -1457,7 +1456,7 @@ void configure_package(deb_file_t *deb_file)
/* Run the postinst script */ /* Run the postinst script */
if (run_package_script(package_name, "postinst") != 0) { if (run_package_script(package_name, "postinst") != 0) {
/* TODO: handle failure gracefully */ /* TODO: handle failure gracefully */
error_msg_and_die("postrm failure.. set status to what?"); bb_error_msg_and_die("postrm failure.. set status to what?");
} }
/* Change status to reflect success */ /* Change status to reflect success */
set_status(status_num, "install", 1); set_status(status_num, "install", 1);
@ -1506,12 +1505,12 @@ int dpkg_main(int argc, char **argv)
dpkg_opt |= dpkg_opt_filename; dpkg_opt |= dpkg_opt_filename;
break; break;
default: default:
show_usage(); bb_show_usage();
} }
} }
/* check for non-otion argument if expected */ /* check for non-otion argument if expected */
if ((dpkg_opt == 0) || ((argc == optind) && !(dpkg_opt && dpkg_opt_list_installed))) { if ((dpkg_opt == 0) || ((argc == optind) && !(dpkg_opt && dpkg_opt_list_installed))) {
show_usage(); bb_show_usage();
} }
/* puts("(Reading database ... xxxxx files and directories installed.)"); */ /* puts("(Reading database ... xxxxx files and directories installed.)"); */
@ -1538,13 +1537,13 @@ int dpkg_main(int argc, char **argv)
init_archive_deb_control(archive_handle); init_archive_deb_control(archive_handle);
deb_file[deb_count]->control_file = deb_extract_control_file_to_buffer(archive_handle, control_list); deb_file[deb_count]->control_file = deb_extract_control_file_to_buffer(archive_handle, control_list);
if (deb_file[deb_count]->control_file == NULL) { if (deb_file[deb_count]->control_file == NULL) {
error_msg_and_die("Couldnt extract control file"); bb_error_msg_and_die("Couldnt extract control file");
} }
deb_file[deb_count]->filename = xstrdup(argv[optind]); deb_file[deb_count]->filename = bb_xstrdup(argv[optind]);
package_num = fill_package_struct(deb_file[deb_count]->control_file); package_num = fill_package_struct(deb_file[deb_count]->control_file);
if (package_num == -1) { if (package_num == -1) {
error_msg("Invalid control file in %s", argv[optind]); bb_error_msg("Invalid control file in %s", argv[optind]);
continue; continue;
} }
deb_file[deb_count]->package = (unsigned int) package_num; deb_file[deb_count]->package = (unsigned int) package_num;
@ -1574,7 +1573,7 @@ int dpkg_main(int argc, char **argv)
search_name_hashtable(argv[optind]), search_name_hashtable(argv[optind]),
search_name_hashtable("ANY"), VER_ANY); search_name_hashtable("ANY"), VER_ANY);
if (package_hashtable[deb_file[deb_count]->package] == NULL) { if (package_hashtable[deb_file[deb_count]->package] == NULL) {
error_msg_and_die("Package %s is uninstalled or unknown\n", argv[optind]); bb_error_msg_and_die("Package %s is uninstalled or unknown\n", argv[optind]);
} }
state_status = get_status(search_status_hashtable(name_hashtable[package_hashtable[deb_file[deb_count]->package]->name]), 3); state_status = get_status(search_status_hashtable(name_hashtable[package_hashtable[deb_file[deb_count]->package]->name]), 3);
@ -1582,13 +1581,13 @@ int dpkg_main(int argc, char **argv)
if (dpkg_opt & dpkg_opt_remove) { if (dpkg_opt & dpkg_opt_remove) {
if ((strcmp(name_hashtable[state_status], "not-installed") == 0) || if ((strcmp(name_hashtable[state_status], "not-installed") == 0) ||
(strcmp(name_hashtable[state_status], "config-files") == 0)) { (strcmp(name_hashtable[state_status], "config-files") == 0)) {
error_msg_and_die("%s is already removed.", name_hashtable[package_hashtable[deb_file[deb_count]->package]->name]); bb_error_msg_and_die("%s is already removed.", name_hashtable[package_hashtable[deb_file[deb_count]->package]->name]);
} }
} }
else if (dpkg_opt & dpkg_opt_purge) { else if (dpkg_opt & dpkg_opt_purge) {
/* if package status is "conf-files" then its ok */ /* if package status is "conf-files" then its ok */
if (strcmp(name_hashtable[state_status], "not-installed") == 0) { if (strcmp(name_hashtable[state_status], "not-installed") == 0) {
error_msg_and_die("%s is already purged.", name_hashtable[package_hashtable[deb_file[deb_count]->package]->name]); bb_error_msg_and_die("%s is already purged.", name_hashtable[package_hashtable[deb_file[deb_count]->package]->name]);
} }
} }
} }
@ -1601,7 +1600,7 @@ int dpkg_main(int argc, char **argv)
/* TODO: check dependencies before removing */ /* TODO: check dependencies before removing */
if ((dpkg_opt & dpkg_opt_force_ignore_depends) != dpkg_opt_force_ignore_depends) { if ((dpkg_opt & dpkg_opt_force_ignore_depends) != dpkg_opt_force_ignore_depends) {
if (!check_deps(deb_file, 0, deb_count)) { if (!check_deps(deb_file, 0, deb_count)) {
error_msg_and_die("Dependency check failed"); bb_error_msg_and_die("Dependency check failed");
} }
} }

View File

@ -82,15 +82,15 @@ extern int dpkg_deb_main(int argc, char **argv)
tar_archive->action_data = data_extract_all; tar_archive->action_data = data_extract_all;
break; break;
default: default:
show_usage(); bb_show_usage();
} }
} }
if (optind + 2 < argc) { if (optind + 2 < argc) {
show_usage(); bb_show_usage();
} }
tar_archive->src_fd = ar_archive->src_fd = xopen(argv[optind++], O_RDONLY); tar_archive->src_fd = ar_archive->src_fd = bb_xopen(argv[optind++], O_RDONLY);
/* Workout where to extract the files */ /* Workout where to extract the files */
/* 2nd argument is a dir name */ /* 2nd argument is a dir name */

View File

@ -82,7 +82,7 @@ extern int gunzip_main(int argc, char **argv)
int opt; int opt;
/* if called as zcat */ /* if called as zcat */
if (strcmp(applet_name, "zcat") == 0) { if (strcmp(bb_applet_name, "zcat") == 0) {
flags |= gunzip_to_stdout; flags |= gunzip_to_stdout;
} }
@ -100,7 +100,7 @@ extern int gunzip_main(int argc, char **argv)
case 'd': /* Used to convert gzip to gunzip. */ case 'd': /* Used to convert gzip to gunzip. */
break; break;
default: default:
show_usage(); /* exit's inside usage */ bb_show_usage(); /* exit's inside usage */
} }
} }
@ -118,29 +118,29 @@ extern int gunzip_main(int argc, char **argv)
src_fd = fileno(stdin); src_fd = fileno(stdin);
flags |= gunzip_to_stdout; flags |= gunzip_to_stdout;
} else { } else {
src_fd = xopen(old_path, O_RDONLY); src_fd = bb_xopen(old_path, O_RDONLY);
/* Get the time stamp on the input file. */ /* Get the time stamp on the input file. */
if (stat(old_path, &stat_buf) < 0) { if (stat(old_path, &stat_buf) < 0) {
error_msg_and_die("Couldn't stat file %s", old_path); bb_error_msg_and_die("Couldn't stat file %s", old_path);
} }
} }
/* Check that the input is sane. */ /* Check that the input is sane. */
if (isatty(src_fd) && ((flags & gunzip_force) == 0)) { if (isatty(src_fd) && ((flags & gunzip_force) == 0)) {
error_msg_and_die bb_error_msg_and_die
("compressed data not read from terminal. Use -f to force it."); ("compressed data not read from terminal. Use -f to force it.");
} }
/* Set output filename and number */ /* Set output filename and number */
if (flags & gunzip_test) { if (flags & gunzip_test) {
dst_fd = xopen("/dev/null", O_WRONLY); /* why does test use filenum 2 ? */ dst_fd = bb_xopen("/dev/null", O_WRONLY); /* why does test use filenum 2 ? */
} else if (flags & gunzip_to_stdout) { } else if (flags & gunzip_to_stdout) {
dst_fd = fileno(stdout); dst_fd = fileno(stdout);
} else { } else {
char *extension; char *extension;
new_path = xstrdup(old_path); new_path = bb_xstrdup(old_path);
extension = strrchr(new_path, '.'); extension = strrchr(new_path, '.');
#ifdef CONFIG_FEATURE_GUNZIP_UNCOMPRESS #ifdef CONFIG_FEATURE_GUNZIP_UNCOMPRESS
@ -154,11 +154,11 @@ extern int gunzip_main(int argc, char **argv)
extension[2] = 'a'; extension[2] = 'a';
extension[3] = 'r'; extension[3] = 'r';
} else { } else {
error_msg_and_die("Invalid extension"); bb_error_msg_and_die("Invalid extension");
} }
/* Open output file */ /* Open output file */
dst_fd = xopen(new_path, O_WRONLY | O_CREAT); dst_fd = bb_xopen(new_path, O_WRONLY | O_CREAT);
/* Set permissions on the file */ /* Set permissions on the file */
chmod(new_path, stat_buf.st_mode); chmod(new_path, stat_buf.st_mode);
@ -168,10 +168,10 @@ extern int gunzip_main(int argc, char **argv)
} }
/* do the decompression, and cleanup */ /* do the decompression, and cleanup */
if (xread_char(src_fd) == 0x1f) { if (bb_xread_char(src_fd) == 0x1f) {
unsigned char magic2; unsigned char magic2;
magic2 = xread_char(src_fd); magic2 = bb_xread_char(src_fd);
#ifdef CONFIG_FEATURE_GUNZIP_UNCOMPRESS #ifdef CONFIG_FEATURE_GUNZIP_UNCOMPRESS
if (magic2 == 0x9d) { if (magic2 == 0x9d) {
status = uncompress(src_fd, dst_fd); status = uncompress(src_fd, dst_fd);
@ -181,14 +181,14 @@ extern int gunzip_main(int argc, char **argv)
check_header_gzip(src_fd); check_header_gzip(src_fd);
status = inflate(src_fd, dst_fd); status = inflate(src_fd, dst_fd);
if (status != 0) { if (status != 0) {
error_msg_and_die("Error inflating"); bb_error_msg_and_die("Error inflating");
} }
check_trailer_gzip(src_fd); check_trailer_gzip(src_fd);
} else { } else {
error_msg_and_die("Invalid magic"); bb_error_msg_and_die("Invalid magic");
} }
} else { } else {
error_msg_and_die("Invalid magic"); bb_error_msg_and_die("Invalid magic");
} }
if ((status != EXIT_SUCCESS) && (new_path)) { if ((status != EXIT_SUCCESS) && (new_path)) {
@ -205,7 +205,7 @@ extern int gunzip_main(int argc, char **argv)
/* delete_path will be NULL if in test mode or from stdin */ /* delete_path will be NULL if in test mode or from stdin */
if (delete_path && (unlink(delete_path) == -1)) { if (delete_path && (unlink(delete_path) == -1)) {
error_msg_and_die("Couldn't remove %s", delete_path); bb_error_msg_and_die("Couldn't remove %s", delete_path);
} }
free(new_path); free(new_path);

View File

@ -187,7 +187,7 @@ typedef int file_t; /* Do not use stdio */
/* Diagnostic functions */ /* Diagnostic functions */
#ifdef DEBUG #ifdef DEBUG
# define Assert(cond,msg) {if(!(cond)) error_msg(msg);} # define Assert(cond,msg) {if(!(cond)) bb_error_msg(msg);}
# define Trace(x) fprintf x # define Trace(x) fprintf x
# define Tracev(x) {if (verbose) fprintf x ;} # define Tracev(x) {if (verbose) fprintf x ;}
# define Tracevv(x) {if (verbose>1) fprintf x ;} # define Tracevv(x) {if (verbose>1) fprintf x ;}
@ -352,10 +352,10 @@ static void clear_bufs(void)
bytes_in = 0L; bytes_in = 0L;
} }
static void write_error_msg(void) static void write_bb_error_msg(void)
{ {
fputc('\n', stderr); fputc('\n', stderr);
perror_msg(""); bb_perror_nomsg();
abort_gzip(); abort_gzip();
} }
@ -369,7 +369,7 @@ static void write_buf(int fd, void *buf, unsigned cnt)
while ((n = write(fd, buf, cnt)) != cnt) { while ((n = write(fd, buf, cnt)) != cnt) {
if (n == (unsigned) (-1)) { if (n == (unsigned) (-1)) {
write_error_msg(); write_bb_error_msg();
} }
cnt -= n; cnt -= n;
buf = (void *) ((char *) buf + n); buf = (void *) ((char *) buf + n);
@ -977,11 +977,11 @@ static void check_match(IPos start, IPos match, int length)
/* check that the match is indeed a match */ /* check that the match is indeed a match */
if (memcmp((char *) window + match, if (memcmp((char *) window + match,
(char *) window + start, length) != EQUAL) { (char *) window + start, length) != EQUAL) {
error_msg(" start %d, match %d, length %d", start, match, length); bb_error_msg(" start %d, match %d, length %d", start, match, length);
error_msg("invalid match"); bb_error_msg("invalid match");
} }
if (verbose > 1) { if (verbose > 1) {
error_msg("\\[%d,%d]", start - match, length); bb_error_msg("\\[%d,%d]", start - match, length);
do { do {
putc(window[start++], stderr); putc(window[start++], stderr);
} while (--length != 0); } while (--length != 0);
@ -1232,7 +1232,7 @@ int gzip_main(int argc, char **argv)
return gunzip_main(argc, argv); return gunzip_main(argc, argv);
#endif #endif
default: default:
show_usage(); bb_show_usage();
} }
} }
@ -1282,7 +1282,7 @@ int gzip_main(int argc, char **argv)
} else { } else {
inFileNum = open(argv[i], O_RDONLY); inFileNum = open(argv[i], O_RDONLY);
if (inFileNum < 0 || fstat(inFileNum, &statBuf) < 0) if (inFileNum < 0 || fstat(inFileNum, &statBuf) < 0)
perror_msg_and_die("%s", argv[i]); bb_perror_msg_and_die("%s", argv[i]);
time_stamp = statBuf.st_ctime; time_stamp = statBuf.st_ctime;
ifile_size = statBuf.st_size; ifile_size = statBuf.st_size;
@ -1299,7 +1299,7 @@ int gzip_main(int argc, char **argv)
outFileNum = open(path, O_RDWR | O_CREAT | O_EXCL); outFileNum = open(path, O_RDWR | O_CREAT | O_EXCL);
#endif #endif
if (outFileNum < 0) { if (outFileNum < 0) {
perror_msg("%s", path); bb_perror_msg("%s", path);
free(path); free(path);
continue; continue;
} }
@ -1311,7 +1311,7 @@ int gzip_main(int argc, char **argv)
} }
if (path == NULL && isatty(outFileNum) && force == 0) { if (path == NULL && isatty(outFileNum) && force == 0) {
error_msg bb_error_msg
("compressed data not written to a terminal. Use -f to force compression."); ("compressed data not written to a terminal. Use -f to force compression.");
free(path); free(path);
continue; continue;
@ -1330,7 +1330,7 @@ int gzip_main(int argc, char **argv)
delFileName = path; delFileName = path;
if (unlink(delFileName) < 0) if (unlink(delFileName) < 0)
perror_msg("%s", delFileName); bb_perror_msg("%s", delFileName);
} }
free(path); free(path);
@ -1655,7 +1655,7 @@ static void set_file_type(void);
#else /* DEBUG */ #else /* DEBUG */
# define send_code(c, tree) \ # define send_code(c, tree) \
{ if (verbose>1) error_msg("\ncd %3d ",(c)); \ { if (verbose>1) bb_error_msg("\ncd %3d ",(c)); \
send_bits(tree[c].Code, tree[c].Len); } send_bits(tree[c].Code, tree[c].Len); }
#endif #endif
@ -2035,7 +2035,7 @@ static void build_tree(tree_desc * desc)
tree[n].Dad = tree[m].Dad = (ush) node; tree[n].Dad = tree[m].Dad = (ush) node;
#ifdef DUMP_BL_TREE #ifdef DUMP_BL_TREE
if (tree == bl_tree) { if (tree == bl_tree) {
error_msg("\nnode %d(%d), sons %d(%d) %d(%d)", bb_error_msg("\nnode %d(%d), sons %d(%d) %d(%d)",
node, tree[node].Freq, n, tree[n].Freq, m, tree[m].Freq); node, tree[node].Freq, n, tree[n].Freq, m, tree[m].Freq);
} }
#endif #endif
@ -2273,7 +2273,7 @@ static ulg flush_block(char *buf, ulg stored_len, int eof)
if (stored_len <= opt_lenb && eof && compressed_len == 0L && seekable()) { if (stored_len <= opt_lenb && eof && compressed_len == 0L && seekable()) {
/* Since LIT_BUFSIZE <= 2*WSIZE, the input data must be there: */ /* Since LIT_BUFSIZE <= 2*WSIZE, the input data must be there: */
if (buf == (char *) 0) if (buf == (char *) 0)
error_msg("block vanished"); bb_error_msg("block vanished");
copy_block(buf, (unsigned) stored_len, 0); /* without header */ copy_block(buf, (unsigned) stored_len, 0); /* without header */
compressed_len = stored_len << 3; compressed_len = stored_len << 3;
@ -2442,7 +2442,7 @@ static void set_file_type()
bin_freq += dyn_ltree[n++].Freq; bin_freq += dyn_ltree[n++].Freq;
*file_type = bin_freq > (ascii_freq >> 2) ? BINARY : ASCII; *file_type = bin_freq > (ascii_freq >> 2) ? BINARY : ASCII;
if (*file_type == BINARY && translate_eol) { if (*file_type == BINARY && translate_eol) {
error_msg("-l used on binary file"); bb_error_msg("-l used on binary file");
} }
} }

View File

@ -35,7 +35,7 @@ extern void archive_copy_file(const archive_handle_t *archive_handle, const int
size = archive_xread(archive_handle, buffer, size); size = archive_xread(archive_handle, buffer, size);
if (write(dst_fd, buffer, size) != size) { if (write(dst_fd, buffer, size) != size) {
error_msg_and_die ("Short write"); bb_error_msg_and_die ("Short write");
} }
chunksize -= size; chunksize -= size;
} }

View File

@ -26,7 +26,7 @@ extern ssize_t archive_xread(const archive_handle_t *archive_handle, unsigned ch
size = archive_handle->read(archive_handle->src_fd, buf, count); size = archive_handle->read(archive_handle->src_fd, buf, count);
if (size == -1) { if (size == -1) {
perror_msg_and_die("Read error"); bb_perror_msg_and_die("Read error");
} }
return(size); return(size);

View File

@ -26,7 +26,7 @@ extern void archive_xread_all(const archive_handle_t *archive_handle, void *buf,
size = archive_xread(archive_handle, buf, count); size = archive_xread(archive_handle, buf, count);
if (size != count) { if (size != count) {
error_msg_and_die("Short read"); bb_error_msg_and_die("Short read");
} }
return; return;
} }

View File

@ -26,7 +26,7 @@ extern ssize_t archive_xread_all_eof(archive_handle_t *archive_handle, unsigned
size = archive_xread(archive_handle, buf, count); size = archive_xread(archive_handle, buf, count);
if ((size != 0) && (size != count)) { if ((size != 0) && (size != count)) {
perror_msg_and_die("Short read, read %d of %d", size, count); bb_perror_msg_and_die("Short read, read %d of %d", size, count);
} }
return(size); return(size);
} }

View File

@ -15,11 +15,11 @@ extern void check_header_gzip(int src_fd)
} formated; } formated;
} header; } header;
xread_all(src_fd, header.raw, 8); bb_xread_all(src_fd, header.raw, 8);
/* Check the compression method */ /* Check the compression method */
if (header.formated.method != 8) { if (header.formated.method != 8) {
error_msg_and_die("Unknown compression method %d", bb_error_msg_and_die("Unknown compression method %d",
header.formated.method); header.formated.method);
} }
@ -27,10 +27,10 @@ extern void check_header_gzip(int src_fd)
/* bit 2 set: extra field present */ /* bit 2 set: extra field present */
unsigned char extra_short; unsigned char extra_short;
extra_short = xread_char(src_fd) + (xread_char(src_fd) << 8); extra_short = bb_xread_char(src_fd) + (bb_xread_char(src_fd) << 8);
while (extra_short > 0) { while (extra_short > 0) {
/* Ignore extra field */ /* Ignore extra field */
xread_char(src_fd); bb_xread_char(src_fd);
extra_short--; extra_short--;
} }
} }
@ -38,19 +38,19 @@ extern void check_header_gzip(int src_fd)
/* Discard original name if any */ /* Discard original name if any */
if (header.formated.flags & 0x08) { if (header.formated.flags & 0x08) {
/* bit 3 set: original file name present */ /* bit 3 set: original file name present */
while(xread_char(src_fd) != 0); while(bb_xread_char(src_fd) != 0);
} }
/* Discard file comment if any */ /* Discard file comment if any */
if (header.formated.flags & 0x10) { if (header.formated.flags & 0x10) {
/* bit 4 set: file comment present */ /* bit 4 set: file comment present */
while(xread_char(src_fd) != 0); while(bb_xread_char(src_fd) != 0);
} }
/* Read the header checksum */ /* Read the header checksum */
if (header.formated.flags & 0x02) { if (header.formated.flags & 0x02) {
xread_char(src_fd); bb_xread_char(src_fd);
xread_char(src_fd); bb_xread_char(src_fd);
} }
return; return;

View File

@ -34,8 +34,8 @@ extern void data_extract_all(archive_handle_t *archive_handle)
int res; int res;
if (archive_handle->flags & ARCHIVE_CREATE_LEADING_DIRS) { if (archive_handle->flags & ARCHIVE_CREATE_LEADING_DIRS) {
char *name = xstrdup(file_header->name); char *name = bb_xstrdup(file_header->name);
make_directory (dirname(name), 0777, FILEUTILS_RECUR); bb_make_directory (dirname(name), 0777, FILEUTILS_RECUR);
free(name); free(name);
} }
@ -47,13 +47,13 @@ extern void data_extract_all(archive_handle_t *archive_handle)
/* hard link */ /* hard link */
res = link(file_header->link_name, file_header->name); res = link(file_header->link_name, file_header->name);
if ((res == -1) && !(archive_handle->flags & ARCHIVE_EXTRACT_QUIET)) { if ((res == -1) && !(archive_handle->flags & ARCHIVE_EXTRACT_QUIET)) {
perror_msg("Couldnt create hard link"); bb_perror_msg("Couldnt create hard link");
} }
} else } else
#endif #endif
{ {
/* Regular file */ /* Regular file */
dst_fd = xopen(file_header->name, O_WRONLY | O_CREAT); dst_fd = bb_xopen(file_header->name, O_WRONLY | O_CREAT);
archive_copy_file(archive_handle, dst_fd); archive_copy_file(archive_handle, dst_fd);
close(dst_fd); close(dst_fd);
} }
@ -63,7 +63,7 @@ extern void data_extract_all(archive_handle_t *archive_handle)
unlink(file_header->name); unlink(file_header->name);
res = mkdir(file_header->name, file_header->mode); res = mkdir(file_header->name, file_header->mode);
if ((res == -1) && !(archive_handle->flags & ARCHIVE_EXTRACT_QUIET)) { if ((res == -1) && !(archive_handle->flags & ARCHIVE_EXTRACT_QUIET)) {
perror_msg("extract_archive: %s", file_header->name); bb_perror_msg("extract_archive: %s", file_header->name);
} }
break; break;
case S_IFLNK: case S_IFLNK:
@ -71,7 +71,7 @@ extern void data_extract_all(archive_handle_t *archive_handle)
unlink(file_header->name); unlink(file_header->name);
res = symlink(file_header->link_name, file_header->name); res = symlink(file_header->link_name, file_header->name);
if ((res == -1) && !(archive_handle->flags & ARCHIVE_EXTRACT_QUIET)) { if ((res == -1) && !(archive_handle->flags & ARCHIVE_EXTRACT_QUIET)) {
perror_msg("Cannot create symlink from %s to '%s'", file_header->name, file_header->link_name); bb_perror_msg("Cannot create symlink from %s to '%s'", file_header->name, file_header->link_name);
} }
break; break;
case S_IFSOCK: case S_IFSOCK:
@ -81,11 +81,11 @@ extern void data_extract_all(archive_handle_t *archive_handle)
unlink(file_header->name); unlink(file_header->name);
res = mknod(file_header->name, file_header->mode, file_header->device); res = mknod(file_header->name, file_header->mode, file_header->device);
if ((res == -1) && !(archive_handle->flags & ARCHIVE_EXTRACT_QUIET)) { if ((res == -1) && !(archive_handle->flags & ARCHIVE_EXTRACT_QUIET)) {
perror_msg("Cannot create node %s", file_header->name); bb_perror_msg("Cannot create node %s", file_header->name);
} }
break; break;
default: default:
error_msg_and_die("Unrecognised file type"); bb_error_msg_and_die("Unrecognised file type");
} }
chmod(file_header->name, file_header->mode); chmod(file_header->name, file_header->mode);

View File

@ -1548,7 +1548,7 @@ extern ssize_t read_bz2(int fd, void *buf, size_t count)
while (1) { while (1) {
if (bzf->strm.avail_in == 0) { if (bzf->strm.avail_in == 0) {
n = xread(bzf->fd, bzf->buf, BZ_MAX_UNUSED); n = bb_xread(bzf->fd, bzf->buf, BZ_MAX_UNUSED);
if (n == 0) { if (n == 0) {
break; break;
} }
@ -1560,7 +1560,7 @@ extern ssize_t read_bz2(int fd, void *buf, size_t count)
ret = BZ2_bzDecompress(&(bzf->strm)); ret = BZ2_bzDecompress(&(bzf->strm));
if ((ret != BZ_OK) && (ret != BZ_STREAM_END)) { if ((ret != BZ_OK) && (ret != BZ_STREAM_END)) {
error_msg_and_die("Error decompressing"); bb_error_msg_and_die("Error decompressing");
} }
if (ret == BZ_STREAM_END) { if (ret == BZ_STREAM_END) {
@ -1628,12 +1628,12 @@ extern unsigned char uncompressStream(int src_fd, int dst_fd)
while (bzerr == BZ_OK) { while (bzerr == BZ_OK) {
nread = read_bz2(src_fd, obuf, 5000); nread = read_bz2(src_fd, obuf, 5000);
if (bzerr == BZ_DATA_ERROR_MAGIC) { if (bzerr == BZ_DATA_ERROR_MAGIC) {
error_msg_and_die("invalid magic"); bb_error_msg_and_die("invalid magic");
} }
if (((bzerr == BZ_OK) || (bzerr == BZ_STREAM_END)) && (nread > 0)) { if (((bzerr == BZ_OK) || (bzerr == BZ_STREAM_END)) && (nread > 0)) {
if (write(dst_fd, obuf, nread) != nread) { if (write(dst_fd, obuf, nread) != nread) {
BZ2_bzReadClose(); BZ2_bzReadClose();
perror_msg_and_die("Couldnt write to file"); bb_perror_msg_and_die("Couldnt write to file");
} }
} }
} }

View File

@ -121,14 +121,14 @@ extern int uncompress(int fd_in, int fd_out)
insize = 0; insize = 0;
inbuf[0] = xread_char(fd_in); inbuf[0] = bb_xread_char(fd_in);
maxbits = inbuf[0] & BIT_MASK; maxbits = inbuf[0] & BIT_MASK;
block_mode = inbuf[0] & BLOCK_MODE; block_mode = inbuf[0] & BLOCK_MODE;
maxmaxcode = MAXCODE(maxbits); maxmaxcode = MAXCODE(maxbits);
if (maxbits > BITS) { if (maxbits > BITS) {
error_msg("compressed with %d bits, can only handle %d bits", maxbits, bb_error_msg("compressed with %d bits, can only handle %d bits", maxbits,
BITS); BITS);
return -1; return -1;
} }
@ -227,11 +227,11 @@ extern int uncompress(int fd_in, int fd_out)
posbits -= n_bits; posbits -= n_bits;
p = &inbuf[posbits >> 3]; p = &inbuf[posbits >> 3];
error_msg bb_error_msg
("insize:%d posbits:%d inbuf:%02X %02X %02X %02X %02X (%d)", ("insize:%d posbits:%d inbuf:%02X %02X %02X %02X %02X (%d)",
insize, posbits, p[-1], p[0], p[1], p[2], p[3], insize, posbits, p[-1], p[0], p[1], p[2], p[3],
(posbits & 07)); (posbits & 07));
error_msg("uncompress: corrupt input"); bb_error_msg("uncompress: corrupt input");
return -1; return -1;
} }

View File

@ -150,7 +150,7 @@ static void fill_bytebuffer(void)
/* Leave the first 4 bytes empty so we can always unwind the bitbuffer /* Leave the first 4 bytes empty so we can always unwind the bitbuffer
* to the front of the bytebuffer, leave 4 bytes free at end of tail * to the front of the bytebuffer, leave 4 bytes free at end of tail
* so we can easily top up buffer in check_trailer_gzip() */ * so we can easily top up buffer in check_trailer_gzip() */
bytebuffer_size = 4 + xread(gunzip_src_fd, &bytebuffer[4], BYTEBUFFER_MAX - 8); bytebuffer_size = 4 + bb_xread(gunzip_src_fd, &bytebuffer[4], BYTEBUFFER_MAX - 8);
bytebuffer_offset = 4; bytebuffer_offset = 4;
} }
} }
@ -448,7 +448,7 @@ static int inflate_codes(huft_t * my_tl, huft_t * my_td, const unsigned int my_b
if ((e = (t = tl + ((unsigned) b & ml))->e) > 16) if ((e = (t = tl + ((unsigned) b & ml))->e) > 16)
do { do {
if (e == 99) { if (e == 99) {
error_msg_and_die("inflate_codes error 1");; bb_error_msg_and_die("inflate_codes error 1");;
} }
b >>= t->b; b >>= t->b;
k -= t->b; k -= t->b;
@ -484,7 +484,7 @@ static int inflate_codes(huft_t * my_tl, huft_t * my_td, const unsigned int my_b
if ((e = (t = td + ((unsigned) b & md))->e) > 16) if ((e = (t = td + ((unsigned) b & md))->e) > 16)
do { do {
if (e == 99) if (e == 99)
error_msg_and_die("inflate_codes error 2");; bb_error_msg_and_die("inflate_codes error 2");;
b >>= t->b; b >>= t->b;
k -= t->b; k -= t->b;
e -= 16; e -= 16;
@ -821,7 +821,7 @@ static int inflate_block(int *e)
if ((i = huft_build(ll, nl, 257, cplens, cplext, &tl, &bl)) != 0) { if ((i = huft_build(ll, nl, 257, cplens, cplext, &tl, &bl)) != 0) {
if (i == 1) { if (i == 1) {
error_msg_and_die("Incomplete literal tree"); bb_error_msg_and_die("Incomplete literal tree");
huft_free(tl); huft_free(tl);
} }
return i; /* incomplete code set */ return i; /* incomplete code set */
@ -830,7 +830,7 @@ static int inflate_block(int *e)
bd = dbits; bd = dbits;
if ((i = huft_build(ll + nl, nd, 0, cpdist, cpdext, &td, &bd)) != 0) { if ((i = huft_build(ll + nl, nd, 0, cpdist, cpdext, &td, &bd)) != 0) {
if (i == 1) { if (i == 1) {
error_msg_and_die("incomplete distance tree"); bb_error_msg_and_die("incomplete distance tree");
huft_free(td); huft_free(td);
} }
huft_free(tl); huft_free(tl);
@ -846,7 +846,7 @@ static int inflate_block(int *e)
} }
default: default:
/* bad block type */ /* bad block type */
error_msg_and_die("bad block type %d\n", t); bb_error_msg_and_die("bad block type %d\n", t);
} }
} }
@ -884,7 +884,7 @@ static int inflate_get_next_window(void)
break; break;
case -2: ret = inflate_codes(0,0,0,0,0); case -2: ret = inflate_codes(0,0,0,0,0);
break; break;
default: error_msg_and_die("inflate error %d", method); default: bb_error_msg_and_die("inflate error %d", method);
} }
if (ret == 1) { if (ret == 1) {
@ -975,16 +975,16 @@ extern void GZ_gzReadClose(void)
ssize_t nread, nwrote; ssize_t nread, nwrote;
GZ_gzReadOpen(in, 0, 0); GZ_gzReadOpen(in, 0, 0);
while(1) { // Robbed from copyfd.c while(1) { // Robbed from bb_copyfd.c
nread = read_gz(in, buf, sizeof(buf)); nread = read_gz(in, buf, sizeof(buf));
if (nread == 0) break; // no data to write if (nread == 0) break; // no data to write
else if (nread == -1) { else if (nread == -1) {
perror_msg("read"); bb_perror_msg("read");
return -1; return -1;
} }
nwrote = full_write(out, buf, nread); nwrote = bb_full_write(out, buf, nread);
if (nwrote == -1) { if (nwrote == -1) {
perror_msg("write"); bb_perror_msg("write");
return -1; return -1;
} }
} }
@ -998,9 +998,9 @@ extern int inflate(int in, int out)
GZ_gzReadOpen(in, 0, 0); GZ_gzReadOpen(in, 0, 0);
while(1) { while(1) {
int ret = inflate_get_next_window(); int ret = inflate_get_next_window();
nwrote = full_write(out, gunzip_window, gunzip_outbuf_count); nwrote = bb_full_write(out, gunzip_window, gunzip_outbuf_count);
if (nwrote == -1) { if (nwrote == -1) {
perror_msg("write"); bb_perror_msg("write");
return -1; return -1;
} }
if (ret == 0) break; if (ret == 0) break;
@ -1017,7 +1017,7 @@ extern void check_trailer_gzip(int src_fd)
/* top up the input buffer with the rest of the trailer */ /* top up the input buffer with the rest of the trailer */
count = bytebuffer_size - bytebuffer_offset; count = bytebuffer_size - bytebuffer_offset;
if (count < 8) { if (count < 8) {
xread_all(src_fd, &bytebuffer[bytebuffer_size], 8 - count); bb_xread_all(src_fd, &bytebuffer[bytebuffer_size], 8 - count);
bytebuffer_size += 8 - count; bytebuffer_size += 8 - count;
} }
for (count = 0; count != 4; count++) { for (count = 0; count != 4; count++) {
@ -1027,14 +1027,14 @@ extern void check_trailer_gzip(int src_fd)
/* Validate decompression - crc */ /* Validate decompression - crc */
if (stored_crc != (gunzip_crc ^ 0xffffffffL)) { if (stored_crc != (gunzip_crc ^ 0xffffffffL)) {
error_msg_and_die("crc error"); bb_error_msg_and_die("crc error");
} }
/* Validate decompression - size */ /* Validate decompression - size */
if (gunzip_bytes_out != if (gunzip_bytes_out !=
(bytebuffer[bytebuffer_offset] | (bytebuffer[bytebuffer_offset+1] << 8) | (bytebuffer[bytebuffer_offset] | (bytebuffer[bytebuffer_offset+1] << 8) |
(bytebuffer[bytebuffer_offset+2] << 16) | (bytebuffer[bytebuffer_offset+3] << 24))) { (bytebuffer[bytebuffer_offset+2] << 16) | (bytebuffer[bytebuffer_offset+3] << 24))) {
error_msg_and_die("Incorrect length, but crc is correct"); bb_error_msg_and_die("Incorrect length, but crc is correct");
} }
} }

View File

@ -41,7 +41,7 @@ extern char get_header_ar(archive_handle_t *archive_handle)
static unsigned int ar_long_name_size; static unsigned int ar_long_name_size;
#endif #endif
/* dont use xread as we want to handle the error ourself */ /* dont use bb_xread as we want to handle the error ourself */
if (read(archive_handle->src_fd, ar.raw, 60) != 60) { if (read(archive_handle->src_fd, ar.raw, 60) != 60) {
/* End Of File */ /* End Of File */
return(EXIT_FAILURE); return(EXIT_FAILURE);
@ -51,14 +51,14 @@ extern char get_header_ar(archive_handle_t *archive_handle)
if (ar.raw[0] == '\n') { if (ar.raw[0] == '\n') {
/* fix up the header, we started reading 1 byte too early */ /* fix up the header, we started reading 1 byte too early */
memmove(ar.raw, &ar.raw[1], 59); memmove(ar.raw, &ar.raw[1], 59);
ar.raw[59] = xread_char(archive_handle->src_fd); ar.raw[59] = bb_xread_char(archive_handle->src_fd);
archive_handle->offset++; archive_handle->offset++;
} }
archive_handle->offset += 60; archive_handle->offset += 60;
/* align the headers based on the header magic */ /* align the headers based on the header magic */
if ((ar.formated.magic[0] != '`') || (ar.formated.magic[1] != '\n')) { if ((ar.formated.magic[0] != '`') || (ar.formated.magic[1] != '\n')) {
error_msg_and_die("Invalid ar header"); bb_error_msg_and_die("Invalid ar header");
} }
typed->mode = strtol(ar.formated.mode, NULL, 8); typed->mode = strtol(ar.formated.mode, NULL, 8);
@ -76,7 +76,7 @@ extern char get_header_ar(archive_handle_t *archive_handle)
* in static variable long_names for use in future entries */ * in static variable long_names for use in future entries */
ar_long_name_size = typed->size; ar_long_name_size = typed->size;
ar_long_names = xmalloc(ar_long_name_size); ar_long_names = xmalloc(ar_long_name_size);
xread_all(archive_handle->src_fd, ar_long_names, ar_long_name_size); bb_xread_all(archive_handle->src_fd, ar_long_names, ar_long_name_size);
archive_handle->offset += ar_long_name_size; archive_handle->offset += ar_long_name_size;
/* This ar entries data section only contained filenames for other records /* This ar entries data section only contained filenames for other records
* they are stored in the static ar_long_names for future reference */ * they are stored in the static ar_long_names for future reference */
@ -90,16 +90,16 @@ extern char get_header_ar(archive_handle_t *archive_handle)
(saved in variable long_name) that conatains the real filename */ (saved in variable long_name) that conatains the real filename */
const unsigned int long_offset = atoi(&ar.formated.name[1]); const unsigned int long_offset = atoi(&ar.formated.name[1]);
if (long_offset >= ar_long_name_size) { if (long_offset >= ar_long_name_size) {
error_msg_and_die("Cant resolve long filename"); bb_error_msg_and_die("Cant resolve long filename");
} }
typed->name = xstrdup(ar_long_names + long_offset); typed->name = bb_xstrdup(ar_long_names + long_offset);
} }
#else #else
error_msg_and_die("long filenames not supported"); bb_error_msg_and_die("long filenames not supported");
#endif #endif
} else { } else {
/* short filenames */ /* short filenames */
typed->name = xstrndup(ar.formated.name, 16); typed->name = bb_xstrndup(ar.formated.name, 16);
} }
typed->name[strcspn(typed->name, " /")] = '\0'; typed->name[strcspn(typed->name, " /")] = '\0';

View File

@ -46,7 +46,7 @@ extern char get_header_cpio(archive_handle_t *archive_handle)
oldtmp = NULL; oldtmp = NULL;
while (tmp) { while (tmp) {
error_msg_and_die("need to fix this\n"); bb_error_msg_and_die("need to fix this\n");
if (tmp->entry->link_name) { /* Found a hardlink ready to be extracted */ if (tmp->entry->link_name) { /* Found a hardlink ready to be extracted */
file_header = tmp->entry; file_header = tmp->entry;
if (oldtmp) { if (oldtmp) {
@ -78,11 +78,11 @@ extern char get_header_cpio(archive_handle_t *archive_handle)
cpio_header[2], cpio_header[2],
cpio_header[3], cpio_header[3],
cpio_header[4]); cpio_header[4]);
error_msg_and_die("Unsupported cpio format"); bb_error_msg_and_die("Unsupported cpio format");
} }
if ((cpio_header[5] != '1') && (cpio_header[5] != '2')) { if ((cpio_header[5] != '1') && (cpio_header[5] != '2')) {
error_msg_and_die("Unsupported cpio format, use newc or crc"); bb_error_msg_and_die("Unsupported cpio format, use newc or crc");
} }
{ {
@ -109,7 +109,7 @@ extern char get_header_cpio(archive_handle_t *archive_handle)
hardlinks_t *tmp = saved_hardlinks; hardlinks_t *tmp = saved_hardlinks;
hardlinks_t *oldtmp = NULL; hardlinks_t *oldtmp = NULL;
while (tmp) { while (tmp) {
error_msg("%s not created: cannot resolve hardlink", tmp->entry->name); bb_error_msg("%s not created: cannot resolve hardlink", tmp->entry->name);
oldtmp = tmp; oldtmp = tmp;
tmp = tmp->next; tmp = tmp->next;
free (oldtmp->entry->name); free (oldtmp->entry->name);
@ -142,13 +142,13 @@ extern char get_header_cpio(archive_handle_t *archive_handle)
pending_hardlinks = 1; pending_hardlinks = 1;
while (tmp) { while (tmp) {
if (tmp->inode == inode) { if (tmp->inode == inode) {
tmp->entry->link_name = xstrdup(file_header->name); tmp->entry->link_name = bb_xstrdup(file_header->name);
nlink--; nlink--;
} }
tmp = tmp->next; tmp = tmp->next;
} }
if (nlink > 1) { if (nlink > 1) {
error_msg("error resolving hardlink: did you create the archive with GNU cpio 2.0-2.2?"); bb_error_msg("error resolving hardlink: did you create the archive with GNU cpio 2.0-2.2?");
} }
} }
} }
@ -165,11 +165,11 @@ extern char get_header_cpio(archive_handle_t *archive_handle)
if ((archive_handle->flags & ARCHIVE_EXTRACT_UNCONDITIONAL) || (statbuf.st_mtime < file_header->mtime)) { if ((archive_handle->flags & ARCHIVE_EXTRACT_UNCONDITIONAL) || (statbuf.st_mtime < file_header->mtime)) {
/* Remove file if flag set or its older than the file to be extracted */ /* Remove file if flag set or its older than the file to be extracted */
if (unlink(file_header->name) == -1) { if (unlink(file_header->name) == -1) {
perror_msg_and_die("Couldnt remove old file"); bb_perror_msg_and_die("Couldnt remove old file");
} }
} else { } else {
if (! archive_handle->flags & ARCHIVE_EXTRACT_QUIET) { if (! archive_handle->flags & ARCHIVE_EXTRACT_QUIET) {
error_msg("%s not created: newer or same age file exists", file_header->name); bb_error_msg("%s not created: newer or same age file exists", file_header->name);
} }
extract_flag = FALSE; extract_flag = FALSE;
} }

View File

@ -75,7 +75,7 @@ extern char get_header_tar(archive_handle_t *archive_handle)
#ifdef CONFIG_FEATURE_TAR_OLDGNU_COMPATABILITY #ifdef CONFIG_FEATURE_TAR_OLDGNU_COMPATABILITY
if (strncmp(tar.formated.magic, "\0\0\0\0\0", 5) != 0) if (strncmp(tar.formated.magic, "\0\0\0\0\0", 5) != 0)
#endif #endif
error_msg_and_die("Invalid tar magic"); bb_error_msg_and_die("Invalid tar magic");
} }
/* Do checksum on headers */ /* Do checksum on headers */
for (i = 0; i < 148 ; i++) { for (i = 0; i < 148 ; i++) {
@ -86,7 +86,7 @@ extern char get_header_tar(archive_handle_t *archive_handle)
sum += tar.raw[i]; sum += tar.raw[i];
} }
if (sum != strtol(tar.formated.chksum, NULL, 8)) { if (sum != strtol(tar.formated.chksum, NULL, 8)) {
error_msg("Invalid tar header checksum"); bb_error_msg("Invalid tar header checksum");
return(EXIT_FAILURE); return(EXIT_FAILURE);
} }
@ -116,7 +116,7 @@ extern char get_header_tar(archive_handle_t *archive_handle)
file_header->size = strtol(tar.formated.size, NULL, 8); file_header->size = strtol(tar.formated.size, NULL, 8);
file_header->mtime = strtol(tar.formated.mtime, NULL, 8); file_header->mtime = strtol(tar.formated.mtime, NULL, 8);
file_header->link_name = (tar.formated.linkname[0] != '\0') ? file_header->link_name = (tar.formated.linkname[0] != '\0') ?
xstrdup(tar.formated.linkname) : NULL; bb_xstrdup(tar.formated.linkname) : NULL;
file_header->device = (dev_t) ((strtol(tar.formated.devmajor, NULL, 8) << 8) + file_header->device = (dev_t) ((strtol(tar.formated.devmajor, NULL, 8) << 8) +
strtol(tar.formated.devminor, NULL, 8)); strtol(tar.formated.devminor, NULL, 8));
@ -129,7 +129,7 @@ extern char get_header_tar(archive_handle_t *archive_handle)
file_header->mode |= S_IFREG; file_header->mode |= S_IFREG;
break; break;
case '1': case '1':
error_msg("Internal hard link not supported"); bb_error_msg("Internal hard link not supported");
break; break;
case '2': case '2':
file_header->mode |= S_IFLNK; file_header->mode |= S_IFLNK;
@ -170,7 +170,7 @@ extern char get_header_tar(archive_handle_t *archive_handle)
case 'N': case 'N':
case 'S': case 'S':
case 'V': case 'V':
error_msg("Ignoring GNU extension type %c", tar.formated.typeflag); bb_error_msg("Ignoring GNU extension type %c", tar.formated.typeflag);
# endif # endif
} }
#endif #endif

View File

@ -25,7 +25,7 @@ extern char get_header_tar_gz(archive_handle_t *archive_handle)
archive_xread_all(archive_handle, &magic, 2); archive_xread_all(archive_handle, &magic, 2);
if ((magic[0] != 0x1f) || (magic[1] != 0x8b)) { if ((magic[0] != 0x1f) || (magic[1] != 0x8b)) {
error_msg_and_die("Invalid gzip magic"); bb_error_msg_and_die("Invalid gzip magic");
} }
check_header_gzip(archive_handle->src_fd); check_header_gzip(archive_handle->src_fd);

View File

@ -9,7 +9,7 @@ extern void header_verbose_list(const file_header_t *file_header)
struct tm *mtime = localtime(&file_header->mtime); struct tm *mtime = localtime(&file_header->mtime);
printf("%s %d/%d%10u %4u-%02u-%02u %02u:%02u:%02u %s", printf("%s %d/%d%10u %4u-%02u-%02u %02u:%02u:%02u %s",
mode_string(file_header->mode), bb_mode_string(file_header->mode),
file_header->uid, file_header->uid,
file_header->gid, file_header->gid,
(unsigned int) file_header->size, (unsigned int) file_header->size,

View File

@ -30,6 +30,6 @@ extern void seek_by_jump(const archive_handle_t *archive_handle, const unsigned
seek_by_char(archive_handle, amount); seek_by_char(archive_handle, amount);
} else } else
#endif #endif
perror_msg_and_die("Seek failure"); bb_perror_msg_and_die("Seek failure");
} }
} }

View File

@ -121,14 +121,14 @@ extern int uncompress(int fd_in, int fd_out)
insize = 0; insize = 0;
inbuf[0] = xread_char(fd_in); inbuf[0] = bb_xread_char(fd_in);
maxbits = inbuf[0] & BIT_MASK; maxbits = inbuf[0] & BIT_MASK;
block_mode = inbuf[0] & BLOCK_MODE; block_mode = inbuf[0] & BLOCK_MODE;
maxmaxcode = MAXCODE(maxbits); maxmaxcode = MAXCODE(maxbits);
if (maxbits > BITS) { if (maxbits > BITS) {
error_msg("compressed with %d bits, can only handle %d bits", maxbits, bb_error_msg("compressed with %d bits, can only handle %d bits", maxbits,
BITS); BITS);
return -1; return -1;
} }
@ -227,11 +227,11 @@ extern int uncompress(int fd_in, int fd_out)
posbits -= n_bits; posbits -= n_bits;
p = &inbuf[posbits >> 3]; p = &inbuf[posbits >> 3];
error_msg bb_error_msg
("insize:%d posbits:%d inbuf:%02X %02X %02X %02X %02X (%d)", ("insize:%d posbits:%d inbuf:%02X %02X %02X %02X %02X (%d)",
insize, posbits, p[-1], p[0], p[1], p[2], p[3], insize, posbits, p[-1], p[0], p[1], p[2], p[3],
(posbits & 07)); (posbits & 07));
error_msg("uncompress: corrupt input"); bb_error_msg("uncompress: corrupt input");
return -1; return -1;
} }

View File

@ -26,7 +26,7 @@ extern void unpack_ar_archive(archive_handle_t *ar_archive)
archive_xread_all(ar_archive, magic, 7); archive_xread_all(ar_archive, magic, 7);
if (strncmp(magic, "!<arch>", 7) != 0) { if (strncmp(magic, "!<arch>", 7) != 0) {
error_msg_and_die("Invalid ar magic"); bb_error_msg_and_die("Invalid ar magic");
} }
ar_archive->offset += 7; ar_archive->offset += 7;

View File

@ -150,7 +150,7 @@ static void fill_bytebuffer(void)
/* Leave the first 4 bytes empty so we can always unwind the bitbuffer /* Leave the first 4 bytes empty so we can always unwind the bitbuffer
* to the front of the bytebuffer, leave 4 bytes free at end of tail * to the front of the bytebuffer, leave 4 bytes free at end of tail
* so we can easily top up buffer in check_trailer_gzip() */ * so we can easily top up buffer in check_trailer_gzip() */
bytebuffer_size = 4 + xread(gunzip_src_fd, &bytebuffer[4], BYTEBUFFER_MAX - 8); bytebuffer_size = 4 + bb_xread(gunzip_src_fd, &bytebuffer[4], BYTEBUFFER_MAX - 8);
bytebuffer_offset = 4; bytebuffer_offset = 4;
} }
} }
@ -448,7 +448,7 @@ static int inflate_codes(huft_t * my_tl, huft_t * my_td, const unsigned int my_b
if ((e = (t = tl + ((unsigned) b & ml))->e) > 16) if ((e = (t = tl + ((unsigned) b & ml))->e) > 16)
do { do {
if (e == 99) { if (e == 99) {
error_msg_and_die("inflate_codes error 1");; bb_error_msg_and_die("inflate_codes error 1");;
} }
b >>= t->b; b >>= t->b;
k -= t->b; k -= t->b;
@ -484,7 +484,7 @@ static int inflate_codes(huft_t * my_tl, huft_t * my_td, const unsigned int my_b
if ((e = (t = td + ((unsigned) b & md))->e) > 16) if ((e = (t = td + ((unsigned) b & md))->e) > 16)
do { do {
if (e == 99) if (e == 99)
error_msg_and_die("inflate_codes error 2");; bb_error_msg_and_die("inflate_codes error 2");;
b >>= t->b; b >>= t->b;
k -= t->b; k -= t->b;
e -= 16; e -= 16;
@ -821,7 +821,7 @@ static int inflate_block(int *e)
if ((i = huft_build(ll, nl, 257, cplens, cplext, &tl, &bl)) != 0) { if ((i = huft_build(ll, nl, 257, cplens, cplext, &tl, &bl)) != 0) {
if (i == 1) { if (i == 1) {
error_msg_and_die("Incomplete literal tree"); bb_error_msg_and_die("Incomplete literal tree");
huft_free(tl); huft_free(tl);
} }
return i; /* incomplete code set */ return i; /* incomplete code set */
@ -830,7 +830,7 @@ static int inflate_block(int *e)
bd = dbits; bd = dbits;
if ((i = huft_build(ll + nl, nd, 0, cpdist, cpdext, &td, &bd)) != 0) { if ((i = huft_build(ll + nl, nd, 0, cpdist, cpdext, &td, &bd)) != 0) {
if (i == 1) { if (i == 1) {
error_msg_and_die("incomplete distance tree"); bb_error_msg_and_die("incomplete distance tree");
huft_free(td); huft_free(td);
} }
huft_free(tl); huft_free(tl);
@ -846,7 +846,7 @@ static int inflate_block(int *e)
} }
default: default:
/* bad block type */ /* bad block type */
error_msg_and_die("bad block type %d\n", t); bb_error_msg_and_die("bad block type %d\n", t);
} }
} }
@ -884,7 +884,7 @@ static int inflate_get_next_window(void)
break; break;
case -2: ret = inflate_codes(0,0,0,0,0); case -2: ret = inflate_codes(0,0,0,0,0);
break; break;
default: error_msg_and_die("inflate error %d", method); default: bb_error_msg_and_die("inflate error %d", method);
} }
if (ret == 1) { if (ret == 1) {
@ -975,16 +975,16 @@ extern void GZ_gzReadClose(void)
ssize_t nread, nwrote; ssize_t nread, nwrote;
GZ_gzReadOpen(in, 0, 0); GZ_gzReadOpen(in, 0, 0);
while(1) { // Robbed from copyfd.c while(1) { // Robbed from bb_copyfd.c
nread = read_gz(in, buf, sizeof(buf)); nread = read_gz(in, buf, sizeof(buf));
if (nread == 0) break; // no data to write if (nread == 0) break; // no data to write
else if (nread == -1) { else if (nread == -1) {
perror_msg("read"); bb_perror_msg("read");
return -1; return -1;
} }
nwrote = full_write(out, buf, nread); nwrote = bb_full_write(out, buf, nread);
if (nwrote == -1) { if (nwrote == -1) {
perror_msg("write"); bb_perror_msg("write");
return -1; return -1;
} }
} }
@ -998,9 +998,9 @@ extern int inflate(int in, int out)
GZ_gzReadOpen(in, 0, 0); GZ_gzReadOpen(in, 0, 0);
while(1) { while(1) {
int ret = inflate_get_next_window(); int ret = inflate_get_next_window();
nwrote = full_write(out, gunzip_window, gunzip_outbuf_count); nwrote = bb_full_write(out, gunzip_window, gunzip_outbuf_count);
if (nwrote == -1) { if (nwrote == -1) {
perror_msg("write"); bb_perror_msg("write");
return -1; return -1;
} }
if (ret == 0) break; if (ret == 0) break;
@ -1017,7 +1017,7 @@ extern void check_trailer_gzip(int src_fd)
/* top up the input buffer with the rest of the trailer */ /* top up the input buffer with the rest of the trailer */
count = bytebuffer_size - bytebuffer_offset; count = bytebuffer_size - bytebuffer_offset;
if (count < 8) { if (count < 8) {
xread_all(src_fd, &bytebuffer[bytebuffer_size], 8 - count); bb_xread_all(src_fd, &bytebuffer[bytebuffer_size], 8 - count);
bytebuffer_size += 8 - count; bytebuffer_size += 8 - count;
} }
for (count = 0; count != 4; count++) { for (count = 0; count != 4; count++) {
@ -1027,14 +1027,14 @@ extern void check_trailer_gzip(int src_fd)
/* Validate decompression - crc */ /* Validate decompression - crc */
if (stored_crc != (gunzip_crc ^ 0xffffffffL)) { if (stored_crc != (gunzip_crc ^ 0xffffffffL)) {
error_msg_and_die("crc error"); bb_error_msg_and_die("crc error");
} }
/* Validate decompression - size */ /* Validate decompression - size */
if (gunzip_bytes_out != if (gunzip_bytes_out !=
(bytebuffer[bytebuffer_offset] | (bytebuffer[bytebuffer_offset+1] << 8) | (bytebuffer[bytebuffer_offset] | (bytebuffer[bytebuffer_offset+1] << 8) |
(bytebuffer[bytebuffer_offset+2] << 16) | (bytebuffer[bytebuffer_offset+3] << 24))) { (bytebuffer[bytebuffer_offset+2] << 16) | (bytebuffer[bytebuffer_offset+3] << 24))) {
error_msg_and_die("Incorrect length, but crc is correct"); bb_error_msg_and_die("Incorrect length, but crc is correct");
} }
} }

View File

@ -116,7 +116,7 @@ int rpm_main(int argc, char **argv)
break; break;
case 'q': // First arg: Query mode case 'q': // First arg: Query mode
if (!func) func |= rpm_query; if (!func) func |= rpm_query;
else show_usage(); else bb_show_usage();
break; break;
case 'p': // Query a package case 'p': // Query a package
func |= rpm_query_package; func |= rpm_query_package;
@ -133,13 +133,13 @@ int rpm_main(int argc, char **argv)
func |= rpm_query_list_config; func |= rpm_query_list_config;
break; break;
default: default:
show_usage(); bb_show_usage();
} }
} }
if (optind == argc) show_usage(); if (optind == argc) bb_show_usage();
while (optind < argc) { while (optind < argc) {
rpm_fd = xopen(argv[optind], O_RDONLY); rpm_fd = bb_xopen(argv[optind], O_RDONLY);
mytags = rpm_gettags(rpm_fd, (int *) &tagcount); mytags = rpm_gettags(rpm_fd, (int *) &tagcount);
offset = lseek(rpm_fd, 0, SEEK_CUR); offset = lseek(rpm_fd, 0, SEEK_CUR);
if (!mytags) { printf("Error reading rpm header\n"); exit(-1); } if (!mytags) { printf("Error reading rpm header\n"); exit(-1); }
@ -206,9 +206,9 @@ void extract_cpio_gz(int fd) {
archive_handle->src_fd = fd; archive_handle->src_fd = fd;
archive_handle->offset = 0; archive_handle->offset = 0;
xread_all(archive_handle->src_fd, &magic, 2); bb_xread_all(archive_handle->src_fd, &magic, 2);
if ((magic[0] != 0x1f) || (magic[1] != 0x8b)) { if ((magic[0] != 0x1f) || (magic[1] != 0x8b)) {
error_msg_and_die("Invalid gzip magic"); bb_error_msg_and_die("Invalid gzip magic");
} }
check_header_gzip(archive_handle->src_fd); check_header_gzip(archive_handle->src_fd);
chdir("/"); // Install RPM's to root chdir("/"); // Install RPM's to root
@ -314,7 +314,7 @@ void fileaction_dobackup(char *filename, int fileref)
if (rpm_getint(RPMTAG_FILEFLAGS, fileref) & RPMFILE_CONFIG) { /* Only need to backup config files */ if (rpm_getint(RPMTAG_FILEFLAGS, fileref) & RPMFILE_CONFIG) { /* Only need to backup config files */
stat_res = lstat (filename, &oldfile); stat_res = lstat (filename, &oldfile);
if (stat_res == 0 && S_ISREG(oldfile.st_mode)) { /* File already exists - really should check MD5's etc to see if different */ if (stat_res == 0 && S_ISREG(oldfile.st_mode)) { /* File already exists - really should check MD5's etc to see if different */
newname = xstrdup(filename); newname = bb_xstrdup(filename);
newname = strcat(newname, ".rpmorig"); newname = strcat(newname, ".rpmorig");
copy_file(filename, newname, FILEUTILS_RECUR | FILEUTILS_PRESERVE_STATUS); copy_file(filename, newname, FILEUTILS_RECUR | FILEUTILS_PRESERVE_STATUS);
remove_file(filename, FILEUTILS_RECUR | FILEUTILS_FORCE); remove_file(filename, FILEUTILS_RECUR | FILEUTILS_FORCE);

View File

@ -52,12 +52,12 @@ void skip_header(int rpm_fd)
{ {
struct rpm_header header; struct rpm_header header;
xread_all(rpm_fd, &header, sizeof(struct rpm_header)); bb_xread_all(rpm_fd, &header, sizeof(struct rpm_header));
if (strncmp((char *) &header.magic, RPM_HEADER_MAGIC, 3) != 0) { if (strncmp((char *) &header.magic, RPM_HEADER_MAGIC, 3) != 0) {
error_msg_and_die("Invalid RPM header magic"); /* Invalid magic */ bb_error_msg_and_die("Invalid RPM header magic"); /* Invalid magic */
} }
if (header.version != 1) { if (header.version != 1) {
error_msg_and_die("Unsupported RPM header version"); /* This program only supports v1 headers */ bb_error_msg_and_die("Unsupported RPM header version"); /* This program only supports v1 headers */
} }
header.entries = ntohl(header.entries); header.entries = ntohl(header.entries);
header.size = ntohl(header.size); header.size = ntohl(header.size);
@ -75,12 +75,12 @@ extern int rpm2cpio_main(int argc, char **argv)
if (argc == 1) { if (argc == 1) {
rpm_fd = fileno(stdin); rpm_fd = fileno(stdin);
} else { } else {
rpm_fd = xopen(argv[1], O_RDONLY); rpm_fd = bb_xopen(argv[1], O_RDONLY);
} }
xread_all(rpm_fd, &lead, sizeof(struct rpm_lead)); bb_xread_all(rpm_fd, &lead, sizeof(struct rpm_lead));
if (strncmp((char *) &lead.magic, RPM_MAGIC, 4) != 0) { if (strncmp((char *) &lead.magic, RPM_MAGIC, 4) != 0) {
error_msg_and_die("Invalid RPM magic"); /* Just check the magic, the rest is irrelevant */ bb_error_msg_and_die("Invalid RPM magic"); /* Just check the magic, the rest is irrelevant */
} }
/* Skip the signature header */ /* Skip the signature header */
@ -90,14 +90,14 @@ extern int rpm2cpio_main(int argc, char **argv)
/* Skip the main header */ /* Skip the main header */
skip_header(rpm_fd); skip_header(rpm_fd);
xread_all(rpm_fd, &magic, 2); bb_xread_all(rpm_fd, &magic, 2);
if ((magic[0] != 0x1f) || (magic[1] != 0x8b)) { if ((magic[0] != 0x1f) || (magic[1] != 0x8b)) {
error_msg_and_die("Invalid gzip magic"); bb_error_msg_and_die("Invalid gzip magic");
} }
check_header_gzip(rpm_fd); check_header_gzip(rpm_fd);
if (inflate(rpm_fd, fileno(stdout)) != 0) { if (inflate(rpm_fd, fileno(stdout)) != 0) {
error_msg("Error inflating"); bb_error_msg("Error inflating");
} }
check_trailer_gzip(rpm_fd); check_trailer_gzip(rpm_fd);

View File

@ -278,7 +278,7 @@ static inline int writeTarHeader(struct TarBallInfo *tbInfo,
header.typeflag = REGTYPE; header.typeflag = REGTYPE;
putOctal(header.size, sizeof(header.size), statbuf->st_size); putOctal(header.size, sizeof(header.size), statbuf->st_size);
} else { } else {
error_msg("%s: Unknown file type", real_name); bb_error_msg("%s: Unknown file type", real_name);
return (FALSE); return (FALSE);
} }
@ -295,9 +295,9 @@ static inline int writeTarHeader(struct TarBallInfo *tbInfo,
/* Now write the header out to disk */ /* Now write the header out to disk */
if ((size = if ((size =
full_write(tbInfo->tarFd, (char *) &header, bb_full_write(tbInfo->tarFd, (char *) &header,
sizeof(struct TarHeader))) < 0) { sizeof(struct TarHeader))) < 0) {
error_msg(io_error, real_name); bb_error_msg(bb_msg_io_error, real_name);
return (FALSE); return (FALSE);
} }
/* Pad the header up to the tar block size */ /* Pad the header up to the tar block size */
@ -368,7 +368,7 @@ static int writeFileToTarball(const char *fileName, struct stat *statbuf,
/* It is against the rules to archive a socket */ /* It is against the rules to archive a socket */
if (S_ISSOCK(statbuf->st_mode)) { if (S_ISSOCK(statbuf->st_mode)) {
error_msg("%s: socket ignored", fileName); bb_error_msg("%s: socket ignored", fileName);
return (TRUE); return (TRUE);
} }
@ -377,7 +377,7 @@ static int writeFileToTarball(const char *fileName, struct stat *statbuf,
* the new tarball */ * the new tarball */
if (tbInfo->statBuf.st_dev == statbuf->st_dev && if (tbInfo->statBuf.st_dev == statbuf->st_dev &&
tbInfo->statBuf.st_ino == statbuf->st_ino) { tbInfo->statBuf.st_ino == statbuf->st_ino) {
error_msg("%s: file is the archive; skipping", fileName); bb_error_msg("%s: file is the archive; skipping", fileName);
return (TRUE); return (TRUE);
} }
@ -386,14 +386,14 @@ static int writeFileToTarball(const char *fileName, struct stat *statbuf,
static int alreadyWarned = FALSE; static int alreadyWarned = FALSE;
if (alreadyWarned == FALSE) { if (alreadyWarned == FALSE) {
error_msg("Removing leading '/' from member names"); bb_error_msg("Removing leading '/' from member names");
alreadyWarned = TRUE; alreadyWarned = TRUE;
} }
header_name++; header_name++;
} }
if (strlen(fileName) >= NAME_SIZE) { if (strlen(fileName) >= NAME_SIZE) {
error_msg(name_longer_than_foo, NAME_SIZE); bb_error_msg(bb_msg_name_longer_than_foo, NAME_SIZE);
return (TRUE); return (TRUE);
} }
@ -419,21 +419,21 @@ static int writeFileToTarball(const char *fileName, struct stat *statbuf,
/* open the file we want to archive, and make sure all is well */ /* open the file we want to archive, and make sure all is well */
if ((inputFileFd = open(fileName, O_RDONLY)) < 0) { if ((inputFileFd = open(fileName, O_RDONLY)) < 0) {
perror_msg("%s: Cannot open", fileName); bb_perror_msg("%s: Cannot open", fileName);
return (FALSE); return (FALSE);
} }
/* write the file to the archive */ /* write the file to the archive */
while ((size = full_read(inputFileFd, buffer, sizeof(buffer))) > 0) { while ((size = bb_full_read(inputFileFd, buffer, sizeof(buffer))) > 0) {
if (full_write(tbInfo->tarFd, buffer, size) != size) { if (bb_full_write(tbInfo->tarFd, buffer, size) != size) {
/* Output file seems to have a problem */ /* Output file seems to have a problem */
error_msg(io_error, fileName); bb_error_msg(bb_msg_io_error, fileName);
return (FALSE); return (FALSE);
} }
readSize += size; readSize += size;
} }
if (size == -1) { if (size == -1) {
error_msg(io_error, fileName); bb_error_msg(bb_msg_io_error, fileName);
return (FALSE); return (FALSE);
} }
/* Pad the file up to the tar block size */ /* Pad the file up to the tar block size */
@ -464,7 +464,7 @@ static inline int writeTarFile(const char *tarName, const int verboseFlag,
/* Make sure there is at least one file to tar up. */ /* Make sure there is at least one file to tar up. */
if (include == NULL) { if (include == NULL) {
error_msg_and_die("Cowardly refusing to create an empty archive"); bb_error_msg_and_die("Cowardly refusing to create an empty archive");
} }
/* Open the tar file for writing. */ /* Open the tar file for writing. */
@ -477,7 +477,7 @@ static inline int writeTarFile(const char *tarName, const int verboseFlag,
} }
if (tbInfo.tarFd < 0) { if (tbInfo.tarFd < 0) {
perror_msg("%s: Cannot open", tarName); bb_perror_msg("%s: Cannot open", tarName);
freeHardLinkInfo(&tbInfo.hlInfoHead); freeHardLinkInfo(&tbInfo.hlInfoHead);
return (FALSE); return (FALSE);
} }
@ -485,12 +485,12 @@ static inline int writeTarFile(const char *tarName, const int verboseFlag,
/* Store the stat info for the tarball's file, so /* Store the stat info for the tarball's file, so
* can avoid including the tarball into itself.... */ * can avoid including the tarball into itself.... */
if (fstat(tbInfo.tarFd, &tbInfo.statBuf) < 0) if (fstat(tbInfo.tarFd, &tbInfo.statBuf) < 0)
error_msg_and_die(io_error, tarName); bb_error_msg_and_die(bb_msg_io_error, tarName);
#ifdef CONFIG_FEATURE_TAR_GZIP #ifdef CONFIG_FEATURE_TAR_GZIP
if (gzip) { if (gzip) {
if (pipe(gzipDataPipe) < 0 || pipe(gzipStatusPipe) < 0) { if (pipe(gzipDataPipe) < 0 || pipe(gzipStatusPipe) < 0) {
perror_msg_and_die("Failed to create gzip pipe"); bb_perror_msg_and_die("Failed to create gzip pipe");
} }
signal(SIGPIPE, SIG_IGN); /* we only want EPIPE on errors */ signal(SIGPIPE, SIG_IGN); /* we only want EPIPE on errors */
@ -529,7 +529,7 @@ static inline int writeTarFile(const char *tarName, const int verboseFlag,
if (n == 0 && vfork_exec_errno != 0) { if (n == 0 && vfork_exec_errno != 0) {
errno = vfork_exec_errno; errno = vfork_exec_errno;
perror_msg_and_die("Could not exec gzip process"); bb_perror_msg_and_die("Could not exec gzip process");
} else if ((n < 0) && (errno == EAGAIN || errno == EINTR)) } else if ((n < 0) && (errno == EAGAIN || errno == EINTR))
continue; /* try it again */ continue; /* try it again */
break; break;
@ -538,7 +538,7 @@ static inline int writeTarFile(const char *tarName, const int verboseFlag,
tbInfo.tarFd = gzipDataPipe[1]; tbInfo.tarFd = gzipDataPipe[1];
} else { } else {
perror_msg_and_die("Failed to vfork gzip process"); bb_perror_msg_and_die("Failed to vfork gzip process");
} }
} }
#endif #endif
@ -567,7 +567,7 @@ static inline int writeTarFile(const char *tarName, const int verboseFlag,
/* Hang up the tools, close up shop, head home */ /* Hang up the tools, close up shop, head home */
close(tbInfo.tarFd); close(tbInfo.tarFd);
if (errorFlag) if (errorFlag)
error_msg("Error exit delayed from previous errors"); bb_error_msg("Error exit delayed from previous errors");
freeHardLinkInfo(&tbInfo.hlInfoHead); freeHardLinkInfo(&tbInfo.hlInfoHead);
@ -585,10 +585,9 @@ static inline int writeTarFile(const char *tarName, const int verboseFlag,
#ifdef CONFIG_FEATURE_TAR_EXCLUDE #ifdef CONFIG_FEATURE_TAR_EXCLUDE
static llist_t *append_file_list_to_list(const char *filename, llist_t *list) static llist_t *append_file_list_to_list(const char *filename, llist_t *list)
{ {
FILE *src_stream = xfopen(filename, "r"); FILE *src_stream = bb_xfopen(filename, "r");
char *line; char *line;
while((line = get_line_from_file(src_stream)) != NULL) { while((line = bb_get_chomped_line_from_file(src_stream)) != NULL) {
chomp(line);
list = llist_add_to(list, line); list = llist_add_to(list, line);
} }
fclose(src_stream); fclose(src_stream);
@ -611,7 +610,7 @@ int tar_main(int argc, char **argv)
unsigned char ctx_flag = 0; unsigned char ctx_flag = 0;
if (argc < 2) { if (argc < 2) {
show_usage(); bb_show_usage();
} }
/* Prepend '-' to the first argument if required */ /* Prepend '-' to the first argument if required */
@ -690,13 +689,13 @@ int tar_main(int argc, char **argv)
break; break;
#endif #endif
default: default:
show_usage(); bb_show_usage();
} }
} }
/* Check one and only one context option was given */ /* Check one and only one context option was given */
if ((ctx_flag != CTX_CREATE) && (ctx_flag != CTX_TEST) && (ctx_flag != CTX_EXTRACT)) { if ((ctx_flag != CTX_CREATE) && (ctx_flag != CTX_TEST) && (ctx_flag != CTX_EXTRACT)) {
show_usage(); bb_show_usage();
} }
/* Check if we are reading from stdin */ /* Check if we are reading from stdin */
@ -740,11 +739,11 @@ int tar_main(int argc, char **argv)
tar_handle->src_fd = fileno(stdin); tar_handle->src_fd = fileno(stdin);
tar_handle->seek = seek_by_char; tar_handle->seek = seek_by_char;
} else { } else {
tar_handle->src_fd = xopen(tar_filename, O_RDONLY); tar_handle->src_fd = bb_xopen(tar_filename, O_RDONLY);
} }
if ((base_dir) && (chdir(base_dir))) { if ((base_dir) && (chdir(base_dir))) {
perror_msg_and_die("Couldnt chdir"); bb_perror_msg_and_die("Couldnt chdir");
} }
while (get_header_ptr(tar_handle) == EXIT_SUCCESS); while (get_header_ptr(tar_handle) == EXIT_SUCCESS);
@ -753,7 +752,7 @@ int tar_main(int argc, char **argv)
while (tar_handle->accept) { while (tar_handle->accept) {
if (find_list_entry(tar_handle->reject, tar_handle->accept->data) == NULL) { if (find_list_entry(tar_handle->reject, tar_handle->accept->data) == NULL) {
if (find_list_entry(tar_handle->passed, tar_handle->accept->data) == NULL) { if (find_list_entry(tar_handle->passed, tar_handle->accept->data) == NULL) {
error_msg_and_die("%s: Not found in archive\n", tar_handle->accept->data); bb_error_msg_and_die("%s: Not found in archive\n", tar_handle->accept->data);
} }
} }
tar_handle->accept = tar_handle->accept->link; tar_handle->accept = tar_handle->accept->link;

View File

@ -45,7 +45,7 @@ int uncompress_main(int argc, char **argv)
flags |= gunzip_force; flags |= gunzip_force;
break; break;
default: default:
show_usage(); /* exit's inside usage */ bb_show_usage(); /* exit's inside usage */
} }
} }
@ -63,17 +63,17 @@ int uncompress_main(int argc, char **argv)
src_fd = fileno(stdin); src_fd = fileno(stdin);
flags |= gunzip_to_stdout; flags |= gunzip_to_stdout;
} else { } else {
src_fd = xopen(old_path, O_RDONLY); src_fd = bb_xopen(old_path, O_RDONLY);
/* Get the time stamp on the input file. */ /* Get the time stamp on the input file. */
if (stat(old_path, &stat_buf) < 0) { if (stat(old_path, &stat_buf) < 0) {
error_msg_and_die("Couldn't stat file %s", old_path); bb_error_msg_and_die("Couldn't stat file %s", old_path);
} }
} }
/* Check that the input is sane. */ /* Check that the input is sane. */
if (isatty(src_fd) && ((flags & gunzip_force) == 0)) { if (isatty(src_fd) && ((flags & gunzip_force) == 0)) {
error_msg_and_die bb_error_msg_and_die
("compressed data not read from terminal. Use -f to force it."); ("compressed data not read from terminal. Use -f to force it.");
} }
@ -83,16 +83,16 @@ int uncompress_main(int argc, char **argv)
} else { } else {
char *extension; char *extension;
new_path = xstrdup(old_path); new_path = bb_xstrdup(old_path);
extension = strrchr(new_path, '.'); extension = strrchr(new_path, '.');
if (!extension || (strcmp(extension, ".Z") != 0)) { if (!extension || (strcmp(extension, ".Z") != 0)) {
error_msg_and_die("Invalid extension"); bb_error_msg_and_die("Invalid extension");
} }
*extension = '\0'; *extension = '\0';
/* Open output file */ /* Open output file */
dst_fd = xopen(new_path, O_WRONLY | O_CREAT); dst_fd = bb_xopen(new_path, O_WRONLY | O_CREAT);
/* Set permissions on the file */ /* Set permissions on the file */
chmod(new_path, stat_buf.st_mode); chmod(new_path, stat_buf.st_mode);
@ -102,10 +102,10 @@ int uncompress_main(int argc, char **argv)
} }
/* do the decompression, and cleanup */ /* do the decompression, and cleanup */
if ((xread_char(src_fd) == 0x1f) && (xread_char(src_fd) == 0x9d)) { if ((bb_xread_char(src_fd) == 0x1f) && (bb_xread_char(src_fd) == 0x9d)) {
status = uncompress(src_fd, dst_fd); status = uncompress(src_fd, dst_fd);
} else { } else {
error_msg_and_die("Invalid magic"); bb_error_msg_and_die("Invalid magic");
} }
if ((status != EXIT_SUCCESS) && (new_path)) { if ((status != EXIT_SUCCESS) && (new_path)) {
@ -122,7 +122,7 @@ int uncompress_main(int argc, char **argv)
/* delete_path will be NULL if in test mode or from stdin */ /* delete_path will be NULL if in test mode or from stdin */
if (delete_path && (unlink(delete_path) == -1)) { if (delete_path && (unlink(delete_path) == -1)) {
error_msg_and_die("Couldn't remove %s", delete_path); bb_error_msg_and_die("Couldn't remove %s", delete_path);
} }
free(new_path); free(new_path);

View File

@ -120,12 +120,12 @@ extern int unzip_main(int argc, char **argv)
break; break;
#endif #endif
default: default:
show_usage(); bb_show_usage();
} }
} }
if (argc == optind) { if (argc == optind) {
show_usage(); bb_show_usage();
} }
printf("Archive: %s\n", argv[optind]); printf("Archive: %s\n", argv[optind]);
@ -138,11 +138,11 @@ extern int unzip_main(int argc, char **argv)
archive_handle->src_fd = fileno(stdin); archive_handle->src_fd = fileno(stdin);
archive_handle->seek = seek_by_char; archive_handle->seek = seek_by_char;
} else { } else {
archive_handle->src_fd = xopen(argv[optind++], O_RDONLY); archive_handle->src_fd = bb_xopen(argv[optind++], O_RDONLY);
} }
if ((base_dir) && (chdir(base_dir))) { if ((base_dir) && (chdir(base_dir))) {
perror_msg_and_die("Couldnt chdir"); bb_perror_msg_and_die("Couldnt chdir");
} }
while (optind < argc) { while (optind < argc) {
@ -163,7 +163,7 @@ extern int unzip_main(int argc, char **argv)
break; break;
} }
else if (magic != ZIP_FILEHEADER_MAGIC) { else if (magic != ZIP_FILEHEADER_MAGIC) {
error_msg_and_die("Invlaide zip magic"); bb_error_msg_and_die("Invlaide zip magic");
} }
/* Read the file header */ /* Read the file header */
@ -172,7 +172,7 @@ extern int unzip_main(int argc, char **argv)
archive_handle->file_header->mode = S_IFREG | 0777; archive_handle->file_header->mode = S_IFREG | 0777;
if (zip_header.formated.method != 8) { if (zip_header.formated.method != 8) {
error_msg_and_die("Unsupported compression method %d\n", zip_header.formated.method); bb_error_msg_and_die("Unsupported compression method %d\n", zip_header.formated.method);
} }
/* Read filename */ /* Read filename */
@ -198,19 +198,19 @@ extern int unzip_main(int argc, char **argv)
if (archive_handle->action_data) { if (archive_handle->action_data) {
archive_handle->action_data(archive_handle); archive_handle->action_data(archive_handle);
} else { } else {
dst_fd = xopen(archive_handle->file_header->name, O_WRONLY | O_CREAT); dst_fd = bb_xopen(archive_handle->file_header->name, O_WRONLY | O_CREAT);
inflate(archive_handle->src_fd, dst_fd); inflate(archive_handle->src_fd, dst_fd);
close(dst_fd); close(dst_fd);
chmod(archive_handle->file_header->name, archive_handle->file_header->mode); chmod(archive_handle->file_header->name, archive_handle->file_header->mode);
/* Validate decompression - crc */ /* Validate decompression - crc */
if (zip_header.formated.crc32 != (gunzip_crc ^ 0xffffffffL)) { if (zip_header.formated.crc32 != (gunzip_crc ^ 0xffffffffL)) {
error_msg("Invalid compressed data--crc error"); bb_error_msg("Invalid compressed data--crc error");
} }
/* Validate decompression - size */ /* Validate decompression - size */
if (gunzip_bytes_out != zip_header.formated.ucmpsize) { if (gunzip_bytes_out != zip_header.formated.ucmpsize) {
error_msg("Invalid compressed data--length error"); bb_error_msg("Invalid compressed data--length error");
} }
} }

View File

@ -23,13 +23,13 @@ int chvt_main(int argc, char **argv)
int fd, num; int fd, num;
if ((argc != 2) || (**(argv + 1) == '-')) if ((argc != 2) || (**(argv + 1) == '-'))
show_usage(); bb_show_usage();
fd = get_console_fd(); fd = get_console_fd();
num = atoi(argv[1]); num = atoi(argv[1]);
if (ioctl(fd, VT_ACTIVATE, num)) if (ioctl(fd, VT_ACTIVATE, num))
perror_msg_and_die("VT_ACTIVATE"); bb_perror_msg_and_die("VT_ACTIVATE");
if (ioctl(fd, VT_WAITACTIVE, num)) if (ioctl(fd, VT_WAITACTIVE, num))
perror_msg_and_die("VT_WAITACTIVE"); bb_perror_msg_and_die("VT_WAITACTIVE");
return EXIT_SUCCESS; return EXIT_SUCCESS;
} }

View File

@ -19,23 +19,23 @@ int deallocvt_main(int argc, char *argv[])
//if ((argc > 2) || ((argv == 2) && (**(argv + 1) == '-'))) //if ((argc > 2) || ((argv == 2) && (**(argv + 1) == '-')))
if (argc > 2) if (argc > 2)
show_usage(); bb_show_usage();
fd = get_console_fd(); fd = get_console_fd();
if (argc == 1) { if (argc == 1) {
/* deallocate all unused consoles */ /* deallocate all unused consoles */
if (ioctl(fd, VT_DISALLOCATE, 0)) if (ioctl(fd, VT_DISALLOCATE, 0))
perror_msg_and_die("VT_DISALLOCATE"); bb_perror_msg_and_die("VT_DISALLOCATE");
} else { } else {
for (i = 1; i < argc; i++) { for (i = 1; i < argc; i++) {
num = atoi(argv[i]); num = atoi(argv[i]);
if (num == 0) if (num == 0)
error_msg("0: illegal VT number"); bb_error_msg("0: illegal VT number");
else if (num == 1) else if (num == 1)
error_msg("VT 1 cannot be deallocated"); bb_error_msg("VT 1 cannot be deallocated");
else if (ioctl(fd, VT_DISALLOCATE, num)) else if (ioctl(fd, VT_DISALLOCATE, num))
perror_msg_and_die("VT_DISALLOCATE"); bb_perror_msg_and_die("VT_DISALLOCATE");
} }
} }

View File

@ -48,12 +48,12 @@ int dumpkmap_main(int argc, char **argv)
char flags[MAX_NR_KEYMAPS], magic[] = "bkeymap"; char flags[MAX_NR_KEYMAPS], magic[] = "bkeymap";
if (argc>=2 && *argv[1]=='-') { if (argc>=2 && *argv[1]=='-') {
show_usage(); bb_show_usage();
} }
fd = open(CURRENT_VC, O_RDWR); fd = open(CURRENT_VC, O_RDWR);
if (fd < 0) { if (fd < 0) {
perror_msg("Error opening " CURRENT_VC); bb_perror_msg("Error opening " CURRENT_VC);
return EXIT_FAILURE; return EXIT_FAILURE;
} }
@ -81,7 +81,7 @@ int dumpkmap_main(int argc, char **argv)
ke.kb_table = i; ke.kb_table = i;
if (ioctl(fd, KDGKBENT, &ke) < 0) { if (ioctl(fd, KDGKBENT, &ke) < 0) {
error_msg("ioctl returned: %m, %s, %s, %xqq", (char *)&ke.kb_index,(char *)&ke.kb_table,(int)&ke.kb_value); bb_error_msg("ioctl returned: %m, %s, %s, %xqq", (char *)&ke.kb_index,(char *)&ke.kb_table,(int)&ke.kb_value);
} }
else { else {
write(1,(void*)&ke.kb_value,2); write(1,(void*)&ke.kb_value,2);

View File

@ -34,16 +34,16 @@ int loadacm_main(int argc, char **argv)
int fd; int fd;
if (argc>=2 && *argv[1]=='-') { if (argc>=2 && *argv[1]=='-') {
show_usage(); bb_show_usage();
} }
fd = open(CURRENT_VC, O_RDWR); fd = open(CURRENT_VC, O_RDWR);
if (fd < 0) { if (fd < 0) {
perror_msg_and_die("Error opening " CURRENT_VC); bb_perror_msg_and_die("Error opening " CURRENT_VC);
} }
if (screen_map_load(fd, stdin)) { if (screen_map_load(fd, stdin)) {
perror_msg_and_die("Error loading acm"); bb_perror_msg_and_die("Error loading acm");
} }
write(fd, "\033(K", 3); write(fd, "\033(K", 3);
@ -60,7 +60,7 @@ static int screen_map_load(int fd, FILE * fp)
int is_unicode; int is_unicode;
if (fstat(fileno(fp), &stbuf)) if (fstat(fileno(fp), &stbuf))
perror_msg_and_die("Cannot stat map file"); bb_perror_msg_and_die("Cannot stat map file");
/* first try a UTF screen-map: either ASCII (no restriction) or binary (regular file) */ /* first try a UTF screen-map: either ASCII (no restriction) or binary (regular file) */
if (! if (!
@ -70,16 +70,16 @@ static int screen_map_load(int fd, FILE * fp)
if (parse_failed) { if (parse_failed) {
if (-1 == fseek(fp, 0, SEEK_SET)) { if (-1 == fseek(fp, 0, SEEK_SET)) {
if (errno == ESPIPE) if (errno == ESPIPE)
error_msg_and_die("16bit screen-map MUST be a regular file."); bb_error_msg_and_die("16bit screen-map MUST be a regular file.");
else else
perror_msg_and_die("fseek failed reading binary 16bit screen-map"); bb_perror_msg_and_die("fseek failed reading binary 16bit screen-map");
} }
if (fread(wbuf, sizeof(unicode) * E_TABSZ, 1, fp) != 1) if (fread(wbuf, sizeof(unicode) * E_TABSZ, 1, fp) != 1)
perror_msg_and_die("Cannot read [new] map from file"); bb_perror_msg_and_die("Cannot read [new] map from file");
#if 0 #if 0
else else
error_msg("Input screen-map is binary."); bb_error_msg("Input screen-map is binary.");
#endif #endif
} }
@ -87,7 +87,7 @@ static int screen_map_load(int fd, FILE * fp)
/* same if it was binary, ie. if parse_failed */ /* same if it was binary, ie. if parse_failed */
if (parse_failed || is_unicode) { if (parse_failed || is_unicode) {
if (ioctl(fd, PIO_UNISCRNMAP, wbuf)) if (ioctl(fd, PIO_UNISCRNMAP, wbuf))
perror_msg_and_die("PIO_UNISCRNMAP ioctl"); bb_perror_msg_and_die("PIO_UNISCRNMAP ioctl");
else else
return 0; return 0;
} }
@ -96,10 +96,10 @@ static int screen_map_load(int fd, FILE * fp)
/* rewind... */ /* rewind... */
if (-1 == fseek(fp, 0, SEEK_SET)) { if (-1 == fseek(fp, 0, SEEK_SET)) {
if (errno == ESPIPE) if (errno == ESPIPE)
error_msg("Assuming 8bit screen-map - MUST be a regular file."), bb_error_msg("Assuming 8bit screen-map - MUST be a regular file."),
exit(1); exit(1);
else else
perror_msg_and_die("fseek failed assuming 8bit screen-map"); bb_perror_msg_and_die("fseek failed assuming 8bit screen-map");
} }
/* ... and try an old 8-bit screen-map */ /* ... and try an old 8-bit screen-map */
@ -109,25 +109,25 @@ static int screen_map_load(int fd, FILE * fp)
if (-1 == fseek(fp, 0, SEEK_SET)) { if (-1 == fseek(fp, 0, SEEK_SET)) {
if (errno == ESPIPE) if (errno == ESPIPE)
/* should not - it succedeed above */ /* should not - it succedeed above */
error_msg_and_die("fseek() returned ESPIPE !"); bb_error_msg_and_die("fseek() returned ESPIPE !");
else else
perror_msg_and_die("fseek for binary 8bit screen-map"); bb_perror_msg_and_die("fseek for binary 8bit screen-map");
} }
if (fread(buf, E_TABSZ, 1, fp) != 1) if (fread(buf, E_TABSZ, 1, fp) != 1)
perror_msg_and_die("Cannot read [old] map from file"); bb_perror_msg_and_die("Cannot read [old] map from file");
#if 0 #if 0
else else
error_msg("Input screen-map is binary."); bb_error_msg("Input screen-map is binary.");
#endif #endif
} }
if (ioctl(fd, PIO_SCRNMAP, buf)) if (ioctl(fd, PIO_SCRNMAP, buf))
perror_msg_and_die("PIO_SCRNMAP ioctl"); bb_perror_msg_and_die("PIO_SCRNMAP ioctl");
else else
return 0; return 0;
} }
error_msg("Error parsing symbolic map"); bb_error_msg("Error parsing symbolic map");
return(1); return(1);
} }
@ -172,7 +172,7 @@ static int uni_screen_map_read_ascii(FILE * fp, unicode buf[], int *is_unicode)
if (feof(fp)) if (feof(fp))
break; break;
else else
perror_msg_and_die("uni_screen_map_read_ascii() can't read line"); bb_perror_msg_and_die("uni_screen_map_read_ascii() can't read line");
} }
/* get "charset-relative charcode", stripping leading spaces */ /* get "charset-relative charcode", stripping leading spaces */

View File

@ -44,11 +44,11 @@ extern int loadfont_main(int argc, char **argv)
int fd; int fd;
if (argc != 1) if (argc != 1)
show_usage(); bb_show_usage();
fd = open(CURRENT_VC, O_RDWR); fd = open(CURRENT_VC, O_RDWR);
if (fd < 0) if (fd < 0)
perror_msg_and_die("Error opening " CURRENT_VC); bb_perror_msg_and_die("Error opening " CURRENT_VC);
loadnewfont(fd); loadnewfont(fd);
return EXIT_SUCCESS; return EXIT_SUCCESS;
@ -62,7 +62,7 @@ static void do_loadfont(int fd, char *inbuf, int unit, int fontsize)
memset(buf, 0, sizeof(buf)); memset(buf, 0, sizeof(buf));
if (unit < 1 || unit > 32) if (unit < 1 || unit > 32)
error_msg_and_die("Bad character size %d", unit); bb_error_msg_and_die("Bad character size %d", unit);
for (i = 0; i < fontsize; i++) for (i = 0; i < fontsize; i++)
memcpy(buf + (32 * i), inbuf + (unit * i), unit); memcpy(buf + (32 * i), inbuf + (unit * i), unit);
@ -77,11 +77,11 @@ static void do_loadfont(int fd, char *inbuf, int unit, int fontsize)
if (ioctl(fd, PIO_FONTX, &cfd) == 0) if (ioctl(fd, PIO_FONTX, &cfd) == 0)
return; /* success */ return; /* success */
perror_msg("PIO_FONTX ioctl error (trying PIO_FONT)"); bb_perror_msg("PIO_FONTX ioctl error (trying PIO_FONT)");
} }
#endif #endif
if (ioctl(fd, PIO_FONT, buf)) if (ioctl(fd, PIO_FONT, buf))
perror_msg_and_die("PIO_FONT ioctl error"); bb_perror_msg_and_die("PIO_FONT ioctl error");
} }
static void static void
@ -119,11 +119,11 @@ do_loadtable(int fd, unsigned char *inbuf, int tailsz, int fontsize)
if (ioctl(fd, PIO_UNIMAPCLR, &advice)) { if (ioctl(fd, PIO_UNIMAPCLR, &advice)) {
#ifdef ENOIOCTLCMD #ifdef ENOIOCTLCMD
if (errno == ENOIOCTLCMD) { if (errno == ENOIOCTLCMD) {
error_msg("It seems this kernel is older than 1.1.92"); bb_error_msg("It seems this kernel is older than 1.1.92");
error_msg_and_die("No Unicode mapping table loaded."); bb_error_msg_and_die("No Unicode mapping table loaded.");
} else } else
#endif #endif
perror_msg_and_die("PIO_UNIMAPCLR"); bb_perror_msg_and_die("PIO_UNIMAPCLR");
} }
ud.entry_ct = ct; ud.entry_ct = ct;
ud.entries = up; ud.entries = up;
@ -133,7 +133,7 @@ do_loadtable(int fd, unsigned char *inbuf, int tailsz, int fontsize)
/* change advice parameters */ /* change advice parameters */
} }
#endif #endif
perror_msg_and_die("PIO_UNIMAP"); bb_perror_msg_and_die("PIO_UNIMAP");
} }
} }
@ -150,13 +150,13 @@ static void loadnewfont(int fd)
*/ */
inputlth = fread(inbuf, 1, sizeof(inbuf), stdin); inputlth = fread(inbuf, 1, sizeof(inbuf), stdin);
if (ferror(stdin)) if (ferror(stdin))
perror_msg_and_die("Error reading input font"); bb_perror_msg_and_die("Error reading input font");
/* use malloc/realloc in case of giant files; /* use malloc/realloc in case of giant files;
maybe these do not occur: 16kB for the font, maybe these do not occur: 16kB for the font,
and 16kB for the map leaves 32 unicode values and 16kB for the map leaves 32 unicode values
for each font position */ for each font position */
if (!feof(stdin)) if (!feof(stdin))
perror_msg_and_die("Font too large"); bb_perror_msg_and_die("Font too large");
/* test for psf first */ /* test for psf first */
{ {
@ -174,11 +174,11 @@ static void loadnewfont(int fd)
goto no_psf; goto no_psf;
if (psfhdr.mode > PSF_MAXMODE) if (psfhdr.mode > PSF_MAXMODE)
error_msg_and_die("Unsupported psf file mode"); bb_error_msg_and_die("Unsupported psf file mode");
fontsize = ((psfhdr.mode & PSF_MODE512) ? 512 : 256); fontsize = ((psfhdr.mode & PSF_MODE512) ? 512 : 256);
#if !defined( PIO_FONTX ) || defined( __sparc__ ) #if !defined( PIO_FONTX ) || defined( __sparc__ )
if (fontsize != 256) if (fontsize != 256)
error_msg_and_die("Only fontsize 256 supported"); bb_error_msg_and_die("Only fontsize 256 supported");
#endif #endif
hastable = (psfhdr.mode & PSF_MODEHASTAB); hastable = (psfhdr.mode & PSF_MODEHASTAB);
unit = psfhdr.charsize; unit = psfhdr.charsize;
@ -186,7 +186,7 @@ static void loadnewfont(int fd)
head = head0 + fontsize * unit; head = head0 + fontsize * unit;
if (head > inputlth || (!hastable && head != inputlth)) if (head > inputlth || (!hastable && head != inputlth))
error_msg_and_die("Input file: bad length"); bb_error_msg_and_die("Input file: bad length");
do_loadfont(fd, inbuf + head0, unit, fontsize); do_loadfont(fd, inbuf + head0, unit, fontsize);
if (hastable) if (hastable)
do_loadtable(fd, inbuf + head, inputlth - head, fontsize); do_loadtable(fd, inbuf + head, inputlth - head, fontsize);
@ -201,7 +201,7 @@ static void loadnewfont(int fd)
} else { } else {
/* bare font */ /* bare font */
if (inputlth & 0377) if (inputlth & 0377)
error_msg_and_die("Bad input file size"); bb_error_msg_and_die("Bad input file size");
offset = 0; offset = 0;
unit = inputlth / 256; unit = inputlth / 256;
} }

View File

@ -51,18 +51,18 @@ int loadkmap_main(int argc, char **argv)
char flags[MAX_NR_KEYMAPS], buff[7]; char flags[MAX_NR_KEYMAPS], buff[7];
if (argc != 1) if (argc != 1)
show_usage(); bb_show_usage();
fd = open(CURRENT_VC, O_RDWR); fd = open(CURRENT_VC, O_RDWR);
if (fd < 0) if (fd < 0)
perror_msg_and_die("Error opening " CURRENT_VC); bb_perror_msg_and_die("Error opening " CURRENT_VC);
read(0, buff, 7); read(0, buff, 7);
if (0 != strncmp(buff, BINARY_KEYMAP_MAGIC, 7)) if (0 != strncmp(buff, BINARY_KEYMAP_MAGIC, 7))
error_msg_and_die("This is not a valid binary keymap."); bb_error_msg_and_die("This is not a valid binary keymap.");
if (MAX_NR_KEYMAPS != read(0, flags, MAX_NR_KEYMAPS)) if (MAX_NR_KEYMAPS != read(0, flags, MAX_NR_KEYMAPS))
perror_msg_and_die("Error reading keymap flags"); bb_perror_msg_and_die("Error reading keymap flags");
ibuff = (u_short *) xmalloc(ibuffsz); ibuff = (u_short *) xmalloc(ibuffsz);
@ -71,7 +71,7 @@ int loadkmap_main(int argc, char **argv)
pos = 0; pos = 0;
while (pos < ibuffsz) { while (pos < ibuffsz) {
if ((readsz = read(0, (char *) ibuff + pos, ibuffsz - pos)) < 0) if ((readsz = read(0, (char *) ibuff + pos, ibuffsz - pos)) < 0)
perror_msg_and_die("Error reading keymap"); bb_perror_msg_and_die("Error reading keymap");
pos += readsz; pos += readsz;
} }
for (j = 0; j < NR_KEYS; j++) { for (j = 0; j < NR_KEYS; j++) {

View File

@ -43,16 +43,16 @@ int openvt_main(int argc, char **argv)
char * cmd_args = NULL; char * cmd_args = NULL;
if (argc < 3) if (argc < 3)
show_usage(); bb_show_usage();
if (!isdigit(argv[1][0])) if (!isdigit(argv[1][0]))
show_usage(); bb_show_usage();
vtno = (int) atol(argv[1]); vtno = (int) atol(argv[1]);
/* if (vtno <= 0 || vtno > 63) */ /* if (vtno <= 0 || vtno > 63) */
if (vtno <= 0 || vtno > 12) if (vtno <= 0 || vtno > 12)
error_msg_and_die("Illegal vt number (%d)", vtno); bb_error_msg_and_die("Illegal vt number (%d)", vtno);
sprintf(vtname, VTNAME, vtno); sprintf(vtname, VTNAME, vtno);
@ -69,13 +69,13 @@ int openvt_main(int argc, char **argv)
if (setsid() < 0) { if (setsid() < 0) {
#endif #endif
perror_msg_and_die("Unable to set new session"); bb_perror_msg_and_die("Unable to set new session");
} }
close(0); /* so that new vt becomes stdin */ close(0); /* so that new vt becomes stdin */
/* and grab new one */ /* and grab new one */
if ((fd = open(vtname, O_RDWR)) == -1) if ((fd = open(vtname, O_RDWR)) == -1)
perror_msg_and_die("could not open %s", vtname); bb_perror_msg_and_die("could not open %s", vtname);
/* Reassign stdout and sterr */ /* Reassign stdout and sterr */
close(1); close(1);

View File

@ -43,7 +43,7 @@ setkeycodes_main(int argc, char** argv)
struct kbkeycode a; struct kbkeycode a;
if (argc % 2 != 1 || argc < 2) { if (argc % 2 != 1 || argc < 2) {
show_usage(); bb_show_usage();
} }
fd = get_console_fd(); fd = get_console_fd();
@ -52,18 +52,18 @@ setkeycodes_main(int argc, char** argv)
a.keycode = atoi(argv[2]); a.keycode = atoi(argv[2]);
a.scancode = sc = strtol(argv[1], &ep, 16); a.scancode = sc = strtol(argv[1], &ep, 16);
if (*ep) { if (*ep) {
error_msg_and_die("error reading SCANCODE: '%s'", argv[1]); bb_error_msg_and_die("error reading SCANCODE: '%s'", argv[1]);
} }
if (a.scancode > 127) { if (a.scancode > 127) {
a.scancode -= 0xe000; a.scancode -= 0xe000;
a.scancode += 128; a.scancode += 128;
} }
if (a.scancode > 255 || a.keycode > 127) { if (a.scancode > 255 || a.keycode > 127) {
error_msg_and_die("SCANCODE or KEYCODE outside bounds"); bb_error_msg_and_die("SCANCODE or KEYCODE outside bounds");
} }
if (ioctl(fd,KDSETKEYCODE,&a)) { if (ioctl(fd,KDSETKEYCODE,&a)) {
perror("KDSETKEYCODE"); perror("KDSETKEYCODE");
error_msg_and_die("failed to set SCANCODE %x to KEYCODE %d", sc, a.keycode); bb_error_msg_and_die("failed to set SCANCODE %x to KEYCODE %d", sc, a.keycode);
} }
argc -= 2; argc -= 2;
argv += 2; argv += 2;

View File

@ -111,17 +111,31 @@ config CONFIG_DOS2UNIX
Please submit a patch to add help text for this item. Please submit a patch to add help text for this item.
config CONFIG_DU config CONFIG_DU
bool "du" bool "du (default blocksize of 512 bytes)"
default n default n
help help
Please submit a patch to add help text for this item. Please submit a patch to add help text for this item.
config CONFIG_FEATURE_DU_DEFALT_BLOCKSIZE_1K
bool " Use a default blocksize of 1024 bytes (1K)"
default y
depends on CONFIG_DU
help
Please submit a patch to add help text for this item.
config CONFIG_ECHO config CONFIG_ECHO
bool "echo" bool "echo (basic SUSv3 version taking no options"
default n default n
help help
Please submit a patch to add help text for this item. Please submit a patch to add help text for this item.
config CONFIG_FEATURE_FANCY_ECHO
bool " Enable echo options (-n and -e)"
default y
depends on CONFIG_ECHO
help
Please submit a patch to add help text for this item.
config CONFIG_ENV config CONFIG_ENV
bool "env" bool "env"
default n default n
@ -154,6 +168,13 @@ config CONFIG_HEAD
help help
Please submit a patch to add help text for this item. Please submit a patch to add help text for this item.
config CONFIG_FEATURE_FANCY_HEAD
bool " Enable head options (-c, -q, and -v)"
default n
depends on CONFIG_HEAD
help
Please submit a patch to add help text for this item.
config CONFIG_HOSTID config CONFIG_HOSTID
bool "hostid" bool "hostid"
default n default n
@ -313,11 +334,18 @@ config CONFIG_SHA1SUM
Compute and check SHA1 message digest Compute and check SHA1 message digest
config CONFIG_SLEEP config CONFIG_SLEEP
bool "sleep" bool "sleep (single integer arg with no suffix)"
default n default n
help help
Please submit a patch to add help text for this item. Please submit a patch to add help text for this item.
config CONFIG_FEATURE_FANCY_SLEEP
bool " Enable multiple integer args and optional time suffixes"
default n
depends on CONFIG_SLEEP
help
Please submit a patch to add help text for this item.
config CONFIG_SORT config CONFIG_SORT
bool "sort" bool "sort"
default n default n
@ -369,6 +397,13 @@ config CONFIG_TEE
help help
Please submit a patch to add help text for this item. Please submit a patch to add help text for this item.
config CONFIG_FEATURE_TEE_USE_BLOCK_IO
bool " Enable block i/o (larger/faster) instead of byte i/o."
default n
depends on CONFIG_TEE
help
Please submit a patch to add help text for this item.
if CONFIG_ASH || CONFIG_HUSH || CONFIG_LASH || CONFIG_MSH if CONFIG_ASH || CONFIG_HUSH || CONFIG_LASH || CONFIG_MSH
config CONFIG_TEST config CONFIG_TEST
default y default y

View File

@ -21,32 +21,43 @@
* *
*/ */
/* getopt not needed */ /* BB_AUDIT SUSv3 compliant */
/* http://www.opengroup.org/onlinepubs/007904975/utilities/basename.html */
/* Mar 16, 2003 Manuel Novoa III (mjn3@codepoet.org)
*
* Changes:
* 1) Now checks for too many args. Need at least one and at most two.
* 2) Don't check for options, as per SUSv3.
* 3) Save some space by using strcmp(). Calling strncmp() here was silly.
*/
#include <stdlib.h> #include <stdlib.h>
#include "busybox.h" #include <stdio.h>
#include <string.h> #include <string.h>
#include "busybox.h"
extern int basename_main(int argc, char **argv) extern int basename_main(int argc, char **argv)
{ {
int m, n; size_t m, n;
char *s; char *s;
if ((argc < 2) || (**(argv + 1) == '-')) { if (((unsigned int)(argc-2)) >= 2) {
show_usage(); bb_show_usage();
} }
argv++; s = bb_get_last_path_component(*++argv);
s = get_last_path_component(*argv); if (*++argv) {
if (argc>2) {
argv++;
n = strlen(*argv); n = strlen(*argv);
m = strlen(s); m = strlen(s);
if (m>n && strncmp(s+m-n, *argv, n)==0) if ((m > n) && ((strcmp)(s+m-n, *argv) == 0)) {
s[m-n] = '\0'; s[m-n] = '\0';
}
} }
puts(s); puts(s);
return EXIT_SUCCESS;
bb_fflush_stdout_and_exit(EXIT_SUCCESS);
} }

View File

@ -1,3 +1,14 @@
/* NOTE:
*
* Apparently, all "Steven J. Merrifield" did was grab the util-linux cal applet,
* spend maybe 5 minutes integrating it into busybox, slapped a copyright on it,
* and submitted it. I certainly saw no evidence of any attempt at size reduction.
* Not only do I consider his copyright below meaningless, I also consider his
* actions shameful.
*
* Manuel Novoa III (mjn3@codepoet.org)
*/
/* /*
* Calendar implementation for busybox * Calendar implementation for busybox
* *
@ -20,7 +31,16 @@
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* *
*/ */
/* BB_AUDIT SUSv3 compliant with -j and -y extensions (from util-linux). */
/* BB_AUDIT BUG: The output of 'cal -j 1752' is incorrect. The upstream
* BB_AUDIT BUG: version in util-linux seems to be broken as well. */
/* http://www.opengroup.org/onlinepubs/007904975/utilities/cal.html */
/* Mar 16, 2003 Manuel Novoa III (mjn3@codepoet.org)
*
* Major size reduction... over 50% (>1.5k) on i386.
*/
#include <sys/types.h> #include <sys/types.h>
#include <ctype.h> #include <ctype.h>
@ -46,44 +66,30 @@
#define MAXDAYS 42 /* max slots in a month array */ #define MAXDAYS 42 /* max slots in a month array */
#define SPACE -1 /* used in day array */ #define SPACE -1 /* used in day array */
static int days_in_month[2][13] = { static const char days_in_month[] = {
{0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}, 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
{0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
}; };
int sep1752[MAXDAYS] = { static const char sep1752[] = {
SPACE, SPACE, 1, 2, 14, 15, 16, 1, 2, 14, 15, 16,
17, 18, 19, 20, 21, 22, 23, 17, 18, 19, 20, 21, 22, 23,
24, 25, 26, 27, 28, 29, 30, 24, 25, 26, 27, 28, 29, 30
SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE,
SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE,
SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE,
}, j_sep1752[MAXDAYS] = {
SPACE, SPACE, 245, 246, 258, 259, 260,
261, 262, 263, 264, 265, 266, 267,
268, 269, 270, 271, 272, 273, 274,
SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE,
SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE,
SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE,
}, empty[MAXDAYS] = {
SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE,
SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE,
SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE,
SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE,
SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE,
SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE,
}; };
char *month_names[12]; static int julian;
char day_headings[] = " ";
char j_day_headings[] = " ";
/* leap year -- account for gregorian reformation in 1752 */ /* leap year -- account for gregorian reformation in 1752 */
#define leap_year(yr) \ #define leap_year(yr) \
((yr) <= 1752 ? !((yr) % 4) : \ ((yr) <= 1752 ? !((yr) % 4) : \
(!((yr) % 4) && ((yr) % 100)) || !((yr) % 400)) (!((yr) % 4) && ((yr) % 100)) || !((yr) % 400))
static int is_leap_year(int year)
{
return leap_year(year);
}
#undef leap_year
#define leap_year(yr) is_leap_year(yr)
/* number of centuries since 1700, not inclusive */ /* number of centuries since 1700, not inclusive */
#define centuries_since_1700(yr) \ #define centuries_since_1700(yr) \
((yr) > 1700 ? (yr) / 100 - 17 : 0) ((yr) > 1700 ? (yr) / 100 - 17 : 0)
@ -96,178 +102,129 @@ char j_day_headings[] = " ";
#define leap_years_since_year_1(yr) \ #define leap_years_since_year_1(yr) \
((yr) / 4 - centuries_since_1700(yr) + quad_centuries_since_1700(yr)) ((yr) / 4 - centuries_since_1700(yr) + quad_centuries_since_1700(yr))
int julian; static void center __P((char *, int, int));
void ascii_day __P((char *, int)); static void day_array __P((int, int, int *));
void center __P((char *, int, int)); static void trim_trailing_spaces_and_print __P((char *));
void day_array __P((int, int, int *));
int day_in_week __P((int, int, int)); static void blank_string(char *buf, size_t buflen);
int day_in_year __P((int, int, int)); static char *build_row(char *p, int *dp);
void j_yearly __P((int));
void monthly __P((int, int)); #define DAY_LEN 3 /* 3 spaces per day */
void trim_trailing_spaces __P((char *)); #define J_DAY_LEN (DAY_LEN + 1)
void yearly __P((int)); #define WEEK_LEN 20 /* 7 * 3 - one space at the end */
#define J_WEEK_LEN (WEEK_LEN + 7)
#define HEAD_SEP 2 /* spaces between day headings */
int cal_main(int argc, char **argv) int cal_main(int argc, char **argv)
{ {
struct tm *local_time; struct tm *local_time;
static struct tm zero_tm; struct tm zero_tm;
time_t now; time_t now;
int ch, month, year, yflag, i; int month, year, flags, i;
char *month_names[12];
char day_headings[28]; /* 28 for julian, 21 for nonjulian */
char buf[40]; char buf[40];
#ifdef CONFIG_LOCALE_SUPPORT #ifdef CONFIG_LOCALE_SUPPORT
setlocale(LC_TIME, ""); setlocale(LC_TIME, "");
#endif #endif
yflag = 0; flags = bb_getopt_ulflags(argc, argv, "jy");
while ((ch = getopt(argc, argv, "jy")) != -1)
switch(ch) { julian = flags & 1;
case 'j':
julian = 1;
break;
case 'y':
yflag = 1;
break;
default:
show_usage();
}
argc -= optind;
argv += optind; argv += optind;
month = 0; month = 0;
switch(argc) {
case 2: if ((argc -= optind) > 2) {
if ((month = atoi(*argv++)) < 1 || month > 12) bb_show_usage();
error_msg_and_die("Illegal month value: use 1-12"); }
/* FALLTHROUGH */
case 1: if (!argc) {
if ((year = atoi(*argv)) < 1 || year > 9999)
error_msg_and_die("Illegal year value: use 1-9999");
break;
case 0:
time(&now); time(&now);
local_time = localtime(&now); local_time = localtime(&now);
year = local_time->tm_year + 1900; year = local_time->tm_year + 1900;
if (!yflag) if (!(flags & 2)) {
month = local_time->tm_mon + 1; month = local_time->tm_mon + 1;
break; }
default: } else {
show_usage(); if (argc == 2) {
month = bb_xgetularg10_bnd(*argv++, 1, 12);
}
year = bb_xgetularg10_bnd(*argv, 1, 9999);
} }
for (i = 0; i < 12; i++) { blank_string(day_headings, sizeof(day_headings) - 7 + 7*julian);
i = 0;
do {
zero_tm.tm_mon = i; zero_tm.tm_mon = i;
strftime(buf, sizeof(buf), "%B", &zero_tm); strftime(buf, sizeof(buf), "%B", &zero_tm);
month_names[i] = xstrdup(buf); month_names[i] = bb_xstrdup(buf);
}
for (i = 0; i < 7; i++) {
zero_tm.tm_wday = i;
strftime(buf, sizeof(buf), "%a", &zero_tm);
strncpy(day_headings + i * 3, buf, 2);
strncpy(j_day_headings + i * 4 + 1, buf, 2);
}
if (month) if (i < 7) {
monthly(month, year); zero_tm.tm_wday = i;
else if (julian) strftime(buf, sizeof(buf), "%a", &zero_tm);
j_yearly(year); strncpy(day_headings + i * (3+julian) + julian, buf, 2);
else }
yearly(year); } while (++i < 12);
exit(0);
}
#define DAY_LEN 3 /* 3 spaces per day */ if (month) {
#define J_DAY_LEN 4 /* 4 spaces per day */ int row, len, days[MAXDAYS];
#define WEEK_LEN 20 /* 7 * 3 - one space at the end */ int *dp = days;
#define J_WEEK_LEN 27 /* 7 * 4 - one space at the end */ char lineout[30];
#define HEAD_SEP 2 /* spaces between day headings */
#define J_HEAD_SEP 2 day_array(month, year, dp);
len = sprintf(lineout, "%s %d", month_names[month - 1], year);
void monthly(int month, int year) bb_printf("%*s%s\n%s\n",
{ ((7*julian + WEEK_LEN) - len) / 2, "",
int col, row, len, days[MAXDAYS]; lineout, day_headings);
char *p, lineout[30];
day_array(month, year, days);
len = sprintf(lineout, "%s %d", month_names[month - 1], year);
printf("%*s%s\n%s\n",
((julian ? J_WEEK_LEN : WEEK_LEN) - len) / 2, "",
lineout, julian ? j_day_headings : day_headings);
for (row = 0; row < 6; row++) {
for (col = 0, p = lineout; col < 7; col++,
p += julian ? J_DAY_LEN : DAY_LEN)
ascii_day(p, days[row * 7 + col]);
*p = '\0';
trim_trailing_spaces(lineout);
printf("%s\n", lineout);
}
}
void j_yearly(int year)
{
int col, *dp, i, month, row, which_cal;
int days[12][MAXDAYS];
char *p, lineout[80];
sprintf(lineout, "%d", year);
center(lineout, J_WEEK_LEN * 2 + J_HEAD_SEP, 0);
printf("\n\n");
for (i = 0; i < 12; i++)
day_array(i + 1, year, days[i]);
memset(lineout, ' ', sizeof(lineout) - 1);
lineout[sizeof(lineout) - 1] = '\0';
for (month = 0; month < 12; month += 2) {
center(month_names[month], J_WEEK_LEN, J_HEAD_SEP);
center(month_names[month + 1], J_WEEK_LEN, 0);
printf("\n%s%*s%s\n", j_day_headings, J_HEAD_SEP, "",
j_day_headings);
for (row = 0; row < 6; row++) { for (row = 0; row < 6; row++) {
for (which_cal = 0; which_cal < 2; which_cal++) { build_row(lineout, dp)[0] = '\0';
p = lineout + which_cal * (J_WEEK_LEN + 2); dp += 7;
dp = &days[month + which_cal][row * 7]; trim_trailing_spaces_and_print(lineout);
for (col = 0; col < 7; col++, p += J_DAY_LEN) }
ascii_day(p, *dp++); } else {
int row, which_cal, week_len, days[12][MAXDAYS];
int *dp;
char lineout[80];
sprintf(lineout, "%d", year);
center(lineout,
(WEEK_LEN * 3 + HEAD_SEP * 2)
+ julian * (J_WEEK_LEN * 2 + HEAD_SEP
- (WEEK_LEN * 3 + HEAD_SEP * 2)),
0);
puts("\n"); /* two \n's */
for (i = 0; i < 12; i++) {
day_array(i + 1, year, days[i]);
}
blank_string(lineout, sizeof(lineout));
week_len = WEEK_LEN + julian * (J_WEEK_LEN - WEEK_LEN);
for (month = 0; month < 12; month += 3-julian) {
center(month_names[month], week_len, HEAD_SEP);
if (!julian) {
center(month_names[month + 1], week_len, HEAD_SEP);
}
center(month_names[month + 2 - julian], week_len, 0);
bb_printf("\n%s%*s%s", day_headings, HEAD_SEP, "", day_headings);
if (!julian) {
bb_printf("%*s%s", HEAD_SEP, "", day_headings);
}
putchar('\n');
for (row = 0; row < (6*7); row += 7) {
for (which_cal = 0; which_cal < 3-julian; which_cal++) {
dp = days[month + which_cal] + row;
build_row(lineout + which_cal * (week_len + 2), dp);
}
/* blank_string took care of nul termination. */
trim_trailing_spaces_and_print(lineout);
} }
*p = '\0';
trim_trailing_spaces(lineout);
printf("%s\n", lineout);
} }
} }
printf("\n");
}
void yearly(int year) bb_fflush_stdout_and_exit(0);
{
int col, *dp, i, month, row, which_cal;
int days[12][MAXDAYS];
char *p, lineout[80];
sprintf(lineout, "%d", year);
center(lineout, WEEK_LEN * 3 + HEAD_SEP * 2, 0);
printf("\n\n");
for (i = 0; i < 12; i++)
day_array(i + 1, year, days[i]);
memset(lineout, ' ', sizeof(lineout) - 1);
lineout[sizeof(lineout) - 1] = '\0';
for (month = 0; month < 12; month += 3) {
center(month_names[month], WEEK_LEN, HEAD_SEP);
center(month_names[month + 1], WEEK_LEN, HEAD_SEP);
center(month_names[month + 2], WEEK_LEN, 0);
printf("\n%s%*s%s%*s%s\n", day_headings, HEAD_SEP,
"", day_headings, HEAD_SEP, "", day_headings);
for (row = 0; row < 6; row++) {
for (which_cal = 0; which_cal < 3; which_cal++) {
p = lineout + which_cal * (WEEK_LEN + 2);
dp = &days[month + which_cal][row * 7];
for (col = 0; col < 7; col++, p += DAY_LEN)
ascii_day(p, *dp++);
}
*p = '\0';
trim_trailing_spaces(lineout);
printf("%s\n", lineout);
}
}
printf("\n");
} }
/* /*
@ -277,117 +234,128 @@ void yearly(int year)
* out end to end. You would have 42 numbers or spaces. This routine * out end to end. You would have 42 numbers or spaces. This routine
* builds that array for any month from Jan. 1 through Dec. 9999. * builds that array for any month from Jan. 1 through Dec. 9999.
*/ */
void day_array(int month, int year, int *days) static void day_array(int month, int year, int *days)
{
int day, dw, dm;
if ((month == 9) && (year == 1752)) {
memmove(days,
julian ? j_sep1752 : sep1752, MAXDAYS * sizeof(int));
return;
}
memmove(days, empty, MAXDAYS * sizeof(int));
dm = days_in_month[leap_year(year)][month];
dw = day_in_week(1, month, year);
day = julian ? day_in_year(1, month, year) : 1;
while (dm--)
days[dw++] = day++;
}
/*
* day_in_year --
* return the 1 based day number within the year
*/
int day_in_year(int day, int month, int year)
{
int i, leap;
leap = leap_year(year);
for (i = 1; i < month; i++)
day += days_in_month[leap][i];
return (day);
}
/*
* day_in_week
* return the 0 based day number for any date from 1 Jan. 1 to
* 31 Dec. 9999. Assumes the Gregorian reformation eliminates
* 3 Sep. 1752 through 13 Sep. 1752. Returns Thursday for all
* missing days.
*/
int day_in_week(int day, int month, int year)
{ {
long temp; long temp;
int i;
int j_offset;
int day, dw, dm;
temp = (long)(year - 1) * 365 + leap_years_since_year_1(year - 1) memset(days, SPACE, MAXDAYS * sizeof(int));
+ day_in_year(day, month, year);
if (temp < FIRST_MISSING_DAY)
return ((temp - 1 + SATURDAY) % 7);
if (temp >= (FIRST_MISSING_DAY + NUMBER_MISSING_DAYS))
return (((temp - 1 + SATURDAY) - NUMBER_MISSING_DAYS) % 7);
return (THURSDAY);
}
void ascii_day(char *p, int day) if ((month == 9) && (year == 1752)) {
{ j_offset = julian * 244;
int display, val; i = 0;
static char *aday[] = { do {
"", days[i+2] = sep1752[i] + j_offset;
" 1", " 2", " 3", " 4", " 5", " 6", " 7", } while (++i < sizeof(sep1752));
" 8", " 9", "10", "11", "12", "13", "14",
"15", "16", "17", "18", "19", "20", "21",
"22", "23", "24", "25", "26", "27", "28",
"29", "30", "31",
};
if (day == SPACE) {
memset(p, ' ', julian ? J_DAY_LEN : DAY_LEN);
return; return;
} }
if (julian) {
if ((val = day / 100) != 0) { /* day_in_year
day %= 100; * return the 1 based day number within the year
*p++ = val + '0'; */
display = 1; day = 1;
} else { if ((month > 2) && leap_year(year)) {
*p++ = ' '; ++day;
display = 0; }
}
val = day / 10; i = month;
if (val || display) while (i) {
*p++ = val + '0'; day += days_in_month[--i];
else }
*p++ = ' ';
*p++ = day % 10 + '0'; /* day_in_week
} else { * return the 0 based day number for any date from 1 Jan. 1 to
*p++ = aday[day][0]; * 31 Dec. 9999. Assumes the Gregorian reformation eliminates
*p++ = aday[day][1]; * 3 Sep. 1752 through 13 Sep. 1752. Returns Thursday for all
* missing days.
*/
dw = THURSDAY;
temp = (long)(year - 1) * 365 + leap_years_since_year_1(year - 1)
+ day;
if (temp < FIRST_MISSING_DAY) {
dw = ((temp - 1 + SATURDAY) % 7);
} else if (temp >= (FIRST_MISSING_DAY + NUMBER_MISSING_DAYS)) {
dw = (((temp - 1 + SATURDAY) - NUMBER_MISSING_DAYS) % 7);
}
if (!julian) {
day = 1;
}
dm = days_in_month[month];
if ((month == 2) && leap_year(year)) {
++dm;
}
while (dm) {
days[dw++] = day++;
--dm;
} }
*p = ' ';
} }
void trim_trailing_spaces(char *s) static void trim_trailing_spaces_and_print(char *s)
{ {
char *p; char *p = s;
for (p = s; *p; ++p) while (*p) {
continue;
while (p > s && (--p, isspace(*p)))
continue;
if (p > s)
++p; ++p;
*p = '\0'; }
while (p > s) {
--p;
if (!(isspace)(*p)) { /* We want the function... not the inline. */
p[1] = '\0';
break;
}
}
puts(s);
} }
void center(char *str, int len, int separate) static void center(char *str, int len, int separate)
{ {
int n = strlen(str);
len -= strlen(str); len -= n;
printf("%*s%s%*s", len / 2, "", str, len / 2 + len % 2, ""); bb_printf("%*s%*s", (len/2) + n, str, (len/2) + (len % 2) + separate, "");
if (separate)
printf("%*s", separate, "");
} }
static void blank_string(char *buf, size_t buflen)
{
memset(buf, ' ', buflen);
buf[buflen-1] = '\0';
}
static char *build_row(char *p, int *dp)
{
int col, val, day;
memset(p, ' ', (julian + DAY_LEN) * 7);
col = 0;
do {
if ((day = *dp++) != SPACE) {
if (julian) {
*++p;
if (day >= 100) {
*p = '0';
p[-1] = (day / 100) + '0';
day %= 100;
}
}
if ((val = day / 10) > 0) {
*p = val + '0';
}
*++p = day % 10 + '0';
p += 2;
} else {
p += DAY_LEN + julian;
}
} while (++col < 7);
return p;
}
/* /*
* Copyright (c) 1989, 1993, 1994 * Copyright (c) 1989, 1993, 1994

View File

@ -1,9 +1,8 @@
/* vi: set sw=4 ts=4: */ /* vi: set sw=4 ts=4: */
/* /*
* Mini Cat implementation for busybox * cat implementation for busybox
* *
* Copyright (C) 1999,2000 by Lineo, inc. and Erik Andersen * Copyright (C) 2003 Manuel Novoa III <mjn3@codepoet.org>
* Copyright (C) 1999,2000,2001 by Erik Andersen <andersee@debian.org>
* *
* This program is free software; you can redistribute it and/or modify * This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
@ -21,33 +20,48 @@
* *
*/ */
/* BB_AUDIT SUSv3 compliant */
/* http://www.opengroup.org/onlinepubs/007904975/utilities/cat.html */
/* Mar 16, 2003 Manuel Novoa III (mjn3@codepoet.org)
*
* This is a new implementation of 'cat' which aims to be SUSv3 compliant.
*
* Changes from the previous implementation include:
* 1) Multiple '-' args are accepted as required by SUSv3. The previous
* implementation would close stdin and segfault on a subsequent '-'.
* 2) The '-u' options is required by SUSv3. Note that the specified
* behavior for '-u' is done by default, so all we need do is accept
* the option.
*/
#include <stdlib.h> #include <stdlib.h>
#include <string.h> #include <stdio.h>
#include <unistd.h>
#include "busybox.h" #include "busybox.h"
extern int cat_main(int argc, char **argv) extern int cat_main(int argc, char **argv)
{ {
int status = EXIT_SUCCESS; FILE *f;
int retval = EXIT_SUCCESS;
if (argc == 1) { bb_getopt_ulflags(argc, argv, "u");
print_file(stdin);
return status; argv += optind;
if (!*argv) {
*--argv = "-";
} }
while (--argc > 0) { do {
if(!(strcmp(*++argv, "-"))) { if ((f = bb_wfopen_input(*argv)) != NULL) {
print_file(stdin); int r = bb_copyfd(fileno(f), STDOUT_FILENO, 0);
} else if (! print_file_by_name(*argv)) { bb_fclose_nonstdin(f);
status = EXIT_FAILURE; if (r >= 0) {
continue;
}
} }
} retval = EXIT_FAILURE;
return status; } while (*++argv);
}
/* return retval;
Local Variables: }
c-file-style: "linux"
c-basic-offset: 4
tab-width: 4
End:
*/

View File

@ -21,9 +21,12 @@
* *
*/ */
#include <stdio.h> /* BB_AUDIT SUSv3 defects - unsupported options -h, -H, -L, and -P. */
/* BB_AUDIT GNU defects - unsupported options -h, -c, -f, -v, and long options. */
/* BB_AUDIT Note: gnu chgrp does not support -H, -L, or -P. */
/* http://www.opengroup.org/onlinepubs/007904975/utilities/chgrp.html */
#include <stdlib.h> #include <stdlib.h>
#include <string.h>
#include <unistd.h> #include <unistd.h>
#include "busybox.h" #include "busybox.h"
@ -32,53 +35,46 @@
#define lchown chown #define lchown chown
#endif #endif
static long gid;
static int fileAction(const char *fileName, struct stat *statbuf, void* junk) static int fileAction(const char *fileName, struct stat *statbuf, void* junk)
{ {
if (lchown(fileName, statbuf->st_uid, (gid == -1) ? statbuf->st_gid : gid) == 0) { if (lchown(fileName, statbuf->st_uid, *((long *) junk)) == 0) {
return (TRUE); return (TRUE);
} }
perror(fileName); bb_perror_msg("%s", fileName); /* Avoid multibyte problems. */
return (FALSE); return (FALSE);
} }
int chgrp_main(int argc, char **argv) int chgrp_main(int argc, char **argv)
{ {
int opt; long gid;
int recursiveFlag = FALSE; int recursiveFlag;;
char *p=NULL; int retval = EXIT_SUCCESS;
char *p;
/* do normal option parsing */ recursiveFlag = bb_getopt_ulflags(argc, argv, "R");
while ((opt = getopt(argc, argv, "R")) > 0) {
switch (opt) { if (argc - optind < 2) {
case 'R': bb_show_usage();
recursiveFlag = TRUE;
break;
default:
show_usage();
}
} }
if (argc > optind && argc > 2 && argv[optind]) { argv += optind;
/* Find the selected group */
gid = strtoul(argv[optind], &p, 10); /* maybe it's already numeric */ /* Find the selected group */
if (argv[optind] == p) gid = strtoul(*argv, &p, 10); /* maybe it's already numeric */
gid = my_getgrnam(argv[optind]); if (*p || (p == *argv)) { /* trailing chars or nonnumeric */
} else { gid = my_getgrnam(*argv);
error_msg_and_die(too_few_args);
} }
++argv;
/* Ok, ready to do the deed now */ /* Ok, ready to do the deed now */
while (++optind < argc) { do {
if (! recursive_action (argv[optind], recursiveFlag, FALSE, FALSE, if (! recursive_action (*argv, recursiveFlag, FALSE, FALSE,
fileAction, fileAction, NULL)) { fileAction, fileAction, &gid)) {
return EXIT_FAILURE; retval = EXIT_FAILURE;
} }
} } while (*++argv);
return EXIT_SUCCESS;
return retval;
} }
/* /*

View File

@ -24,67 +24,84 @@
* *
*/ */
/* BB_AUDIT SUSv3 compliant */
/* BB_AUDIT GNU defects - unsupported options -c, -f, -v, and long options. */
/* http://www.opengroup.org/onlinepubs/007904975/utilities/chmod.html */
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <string.h> #include <string.h>
#include <unistd.h> #include <unistd.h>
#include <getopt.h> #include <sys/stat.h>
#include "busybox.h" #include "busybox.h"
static int fileAction(const char *fileName, struct stat *statbuf, void* junk) static int fileAction(const char *fileName, struct stat *statbuf, void* junk)
{ {
if (!parse_mode((char *)junk, &(statbuf->st_mode))) if (!bb_parse_mode((char *)junk, &(statbuf->st_mode)))
error_msg_and_die( "unknown mode: %s", (char *)junk); bb_error_msg_and_die( "unknown mode: %s", (char *)junk);
if (chmod(fileName, statbuf->st_mode) == 0) if (chmod(fileName, statbuf->st_mode) == 0)
return (TRUE); return (TRUE);
perror(fileName); bb_perror_msg("%s", fileName); /* Avoid multibyte problems. */
return (FALSE); return (FALSE);
} }
int chmod_main(int argc, char **argv) int chmod_main(int argc, char **argv)
{ {
int opt; int retval = EXIT_SUCCESS;
int recursiveFlag = FALSE; int recursiveFlag = FALSE;
int modeind = 0; /* Index of the mode argument in `argv'. */ int count;
char *smode; char *smode;
static const char chmod_modes[] = "Rrwxstugoa,+-="; char **p;
char *p0;
char opt = '-';
/* do normal option parsing */ ++argv;
while (1) { count = 0;
int thisind = optind ? optind : 1;
opt = getopt(argc, argv, chmod_modes); for (p = argv ; *p ; p++) {
if (opt == EOF) p0 = p[0];
break; if (p0[0] == opt) {
smode = strchr(chmod_modes, opt); if ((p0[1] == '-') && !p0[2]) {
if(smode == NULL) opt = 0; /* Disable further option processing. */
show_usage(); continue;
if(smode == chmod_modes) { /* 'R' */ }
recursiveFlag = TRUE; if (p0[1] == 'R') {
} else { char *s = p0 + 2;
if (modeind != 0 && modeind != thisind) while (*s == 'R') {
show_usage(); ++s;
modeind = thisind; }
if (*s) {
bb_show_usage();
}
recursiveFlag = TRUE;
continue;
}
if (count) {
bb_show_usage();
}
} }
argv[count] = p0;
++count;
} }
if (modeind == 0) argv[count] = NULL;
modeind = optind++;
opt = optind; if (count < 2) {
if (opt >= argc) { bb_show_usage();
error_msg_and_die(too_few_args);
} }
smode = argv[modeind]; smode = *argv;
++argv;
/* Ok, ready to do the deed now */ /* Ok, ready to do the deed now */
for (; opt < argc; opt++) { do {
if (! recursive_action (argv[opt], recursiveFlag, FALSE, FALSE, fileAction, if (! recursive_action (*argv, recursiveFlag, FALSE, FALSE,
fileAction, smode)) { fileAction, fileAction, smode)) {
return EXIT_FAILURE; retval = EXIT_FAILURE;
} }
} } while (*++argv);
return EXIT_SUCCESS;
return retval;
} }
/* /*

View File

@ -21,10 +21,14 @@
* *
*/ */
#include <stdio.h> /* BB_AUDIT SUSv3 defects - unsupported options -h, -H, -L, and -P. */
/* BB_AUDIT GNU defects - unsupported options -h, -c, -f, -v, and long options. */
/* BB_AUDIT Note: gnu chown does not support -H, -L, or -P. */
/* http://www.opengroup.org/onlinepubs/007904975/utilities/chown.html */
#include <stdlib.h> #include <stdlib.h>
#include <string.h>
#include <unistd.h> #include <unistd.h>
#include <string.h>
#include "busybox.h" #include "busybox.h"
/* Don't use lchown for libc5 or glibc older then 2.1.x */ /* Don't use lchown for libc5 or glibc older then 2.1.x */
@ -42,65 +46,67 @@ static int fileAction(const char *fileName, struct stat *statbuf, void* junk)
if (chown_func(fileName, uid, (gid == -1) ? statbuf->st_gid : gid) == 0) { if (chown_func(fileName, uid, (gid == -1) ? statbuf->st_gid : gid) == 0) {
return (TRUE); return (TRUE);
} }
perror(fileName); bb_perror_msg("%s", fileName); /* Avoid multibyte problems. */
return (FALSE); return (FALSE);
} }
#define FLAG_R 1
#define FLAG_h 2
static unsigned long get_ug_id(const char *s, long (*my_getxxnam)(const char *))
{
unsigned long r;
char *p;
r = strtoul(s, &p, 10);
if (*p || (s == p)) {
r = my_getxxnam(s);
}
return r;
}
int chown_main(int argc, char **argv) int chown_main(int argc, char **argv)
{ {
int opt; int flags;
int recursiveFlag = FALSE, int retval = EXIT_SUCCESS;
noderefFlag = FALSE; char *groupName;
char *groupName=NULL;
char *p=NULL;
/* do normal option parsing */ flags = bb_getopt_ulflags(argc, argv, "Rh");
while ((opt = getopt(argc, argv, "Rh")) > 0) {
switch (opt) { if (flags & FLAG_h) chown_func = lchown;
case 'R':
recursiveFlag = TRUE; if (argc - optind < 2) {
break; bb_show_usage();
case 'h':
noderefFlag = TRUE;
break;
default:
show_usage();
}
} }
if (noderefFlag) chown_func = lchown; argv += optind;
if (argc > optind && argc > 2 && argv[optind]) { /* First, check if there is a group name here */
/* First, check if there is a group name here */ if ((groupName = strchr(*argv, '.')) == NULL) {
groupName = strchr(argv[optind], '.'); groupName = strchr(*argv, ':');
if (groupName == NULL)
groupName = strchr(argv[optind], ':');
if (groupName) {
*groupName++ = '\0';
gid = strtoul(groupName, &p, 10);
if (groupName == p)
gid = my_getgrnam(groupName);
} else {
gid = -1;
}
/* Now check for the username */
uid = strtoul(argv[optind], &p, 10); /* Is is numeric? */
if (argv[optind] == p) {
uid = my_getpwnam(argv[optind]);
}
} else {
error_msg_and_die(too_few_args);
} }
gid = -1;
if (groupName) {
*groupName++ = '\0';
gid = get_ug_id(groupName, my_getgrnam);
}
/* Now check for the username */
uid = get_ug_id(*argv, my_getpwnam);
++argv;
/* Ok, ready to do the deed now */ /* Ok, ready to do the deed now */
while (++optind < argc) { do {
if (! recursive_action (argv[optind], recursiveFlag, FALSE, FALSE, if (! recursive_action (*argv, (flags & FLAG_R), FALSE, FALSE,
fileAction, fileAction, NULL)) { fileAction, fileAction, NULL)) {
return EXIT_FAILURE; retval = EXIT_FAILURE;
} }
} } while (*++argv);
return EXIT_SUCCESS;
return retval;
} }
/* /*

View File

@ -21,6 +21,8 @@
* *
*/ */
/* BB_AUDIT SUSv3 N/A -- Matches GNU behavior. */
#include <stdlib.h> #include <stdlib.h>
#include <stdio.h> #include <stdio.h>
#include <unistd.h> #include <unistd.h>
@ -29,46 +31,24 @@
int chroot_main(int argc, char **argv) int chroot_main(int argc, char **argv)
{ {
char *prog; if (argc < 2) {
bb_show_usage();
if ((argc < 2) || (**(argv + 1) == '-')) {
show_usage();
} }
argc--;
argv++;
++argv;
if (chroot(*argv) || (chdir("/"))) { if (chroot(*argv) || (chdir("/"))) {
perror_msg_and_die("cannot change root directory to %s", *argv); bb_perror_msg_and_die("cannot change root directory to %s", *argv);
} }
argc--; ++argv;
argv++; if (argc == 2) {
if (argc >= 1) { argv -= 2;
prog = *argv; if (!(*argv = getenv("SHELL"))) {
execvp(*argv, argv); *argv = (char *) "/bin/sh";
} else { }
#if defined shell_main && defined CONFIG_FEATURE_SH_STANDALONE_SHELL argv[1] = (char *) "-i";
char shell[] = "/bin/sh";
char *shell_argv[2] = { shell, NULL };
applet_name = shell;
shell_main(1, shell_argv);
return EXIT_SUCCESS;
#else
prog = getenv("SHELL");
if (!prog)
prog = "/bin/sh";
execlp(prog, prog, NULL);
#endif
} }
perror_msg_and_die("cannot execute %s", prog);
execvp(*argv, argv);
bb_perror_msg_and_die("cannot execute %s", *argv);
} }
/*
Local Variables:
c-file-style: "linux"
c-basic-offset: 4
tab-width: 4
End:
*/

View File

@ -20,59 +20,133 @@
* *
*/ */
/* BB_AUDIT SUSv3 (virtually) compliant -- uses nicer GNU format for -l. */
/* http://www.opengroup.org/onlinepubs/007904975/utilities/cmp.html */
/* Mar 16, 2003 Manuel Novoa III (mjn3@codepoet.org)
*
* Original version majorly reworked for SUSv3 compliance, bug fixes, and
* size optimizations. Changes include:
* 1) Now correctly distingusishes between errors and actual file differences.
* 2) Proper handling of '-' args.
* 3) Actual error checking of i/o.
* 4) Accept SUSv3 -l option. Note that we use the slightly nicer gnu format
* in the '-l' case.
*/
#include <stdio.h> #include <stdio.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h> #include <stdlib.h>
#include <getopt.h> #include <unistd.h>
#include "busybox.h" #include "busybox.h"
static FILE *cmp_xfopen_input(const char *filename)
{
FILE *fp;
if ((fp = bb_wfopen_input(filename)) != NULL) {
return fp;
}
exit(bb_default_error_retval); /* We already output an error message. */
}
static const char fmt_eof[] = "cmp: EOF on %s\n";
static const char fmt_differ[] = "%s %s differ: char %d, line %d\n";
#if 0
static const char fmt_l_opt[] = "%.0s%.0s%d %o %o\n"; /* SUSv3 format */
#else
static const char fmt_l_opt[] = "%.0s%.0s%d %3o %3o\n"; /* nicer gnu format */
#endif
static const char opt_chars[] = "sl";
enum {
OPT_s = 1,
OPT_l = 2
};
int cmp_main(int argc, char **argv) int cmp_main(int argc, char **argv)
{ {
FILE *fp1 = NULL, *fp2 = stdin; FILE *fp1, *fp2, *outfile = stdout;
char *filename1, *filename2 = "-"; const char *filename1, *filename2;
int c, c1, c2, char_pos = 1, line_pos = 1, silent = FALSE; const char *fmt;
int c1, c2, char_pos, line_pos;
int opt_flags;
int exit_val = 0;
while ((c = getopt(argc, argv, "s")) != EOF) { bb_default_error_retval = 2; /* 1 is returned if files are different. */
switch (c) {
case 's': opt_flags = bb_getopt_ulflags(argc, argv, opt_chars);
silent = TRUE;
break; if ((opt_flags == 3) || (((unsigned int)(--argc - optind)) > 1)) {
default: bb_show_usage();
show_usage();
}
} }
filename1 = argv[optind]; fp1 = cmp_xfopen_input(filename1 = *(argv += optind));
switch (argc - optind) {
case 2: filename2 = "-";
fp2 = xfopen(filename2 = argv[optind + 1], "r"); if (*++argv) {
case 1: filename2 = *argv;
fp1 = xfopen(filename1, "r"); }
break; fp2 = cmp_xfopen_input(filename2);
default:
show_usage(); if (fp1 == fp2) { /* Paranioa check... stdin == stdin? */
/* Note that we don't bother reading stdin. Neither does gnu wc.
* But perhaps we should, so that other apps down the chain don't
* get the input. Consider 'echo hello | (cmp - - && cat -)'.
*/
return 0;
} }
fmt = fmt_differ;
if (opt_flags == OPT_l) {
fmt = fmt_l_opt;
}
char_pos = 0;
line_pos = 1;
do { do {
c1 = fgetc(fp1); c1 = getc(fp1);
c2 = fgetc(fp2); c2 = getc(fp2);
if (c1 != c2) { ++char_pos;
if (silent) if (c1 != c2) { /* Remember -- a read error may have occurred. */
return EXIT_FAILURE; exit_val = 1; /* But assume the files are different for now. */
if (c1 == EOF) if (c2 == EOF) {
printf("EOF on %s\n", filename1); /* We know that fp1 isn't at EOF or in an error state. But to
else if (c2 == EOF) * save space below, things are setup to expect an EOF in fp1
printf("EOF on %s\n", filename2); * if an EOF occurred. So, swap things around.
else */
printf("%s %s differ: char %d, line %d\n", filename1, filename2, fp1 = fp2;
char_pos, line_pos); filename1 = filename2;
return EXIT_FAILURE; c1 = c2;
}
if (c1 == EOF) {
bb_xferror(fp1, filename1);
fmt = fmt_eof; /* Well, no error, so it must really be EOF. */
outfile = stderr;
/* There may have been output to stdout (option -l), so
* make sure we fflush before writing to stderr. */
bb_xfflush_stdout();
}
if (opt_flags != OPT_s) {
if (opt_flags == OPT_l) {
line_pos = c1; /* line_pos is unused in the -l case. */
}
bb_fprintf(outfile, fmt, filename1, filename2, char_pos, line_pos, c2);
if (opt_flags) { /* This must be -l since not -s. */
/* If we encountered and EOF, the while check will catch it. */
continue;
}
}
break;
}
if (c1 == '\n') {
++line_pos;
} }
char_pos++;
if (c1 == '\n')
line_pos++;
} while (c1 != EOF); } while (c1 != EOF);
return EXIT_SUCCESS; bb_xferror(fp1, filename1);
bb_xferror(fp2, filename2);
bb_fflush_stdout_and_exit(exit_val);
} }

View File

@ -2,7 +2,6 @@
/* /*
* Mini cp implementation for busybox * Mini cp implementation for busybox
* *
*
* Copyright (C) 2000 by Matt Kraai <kraai@alumni.carnegiemellon.edu> * Copyright (C) 2000 by Matt Kraai <kraai@alumni.carnegiemellon.edu>
* *
* This program is free software; you can redistribute it and/or modify * This program is free software; you can redistribute it and/or modify
@ -21,6 +20,15 @@
* *
*/ */
/* BB_AUDIT SUSv3 defects - unsupported options -H, -L, and -P. */
/* BB_AUDIT GNU defects - only extension options supported are -a and -d. */
/* http://www.opengroup.org/onlinepubs/007904975/utilities/cp.html */
/* Mar 16, 2003 Manuel Novoa III (mjn3@codepoet.org)
*
* Size reduction.
*/
#include <sys/types.h> #include <sys/types.h>
#include <sys/stat.h> #include <sys/stat.h>
#include <unistd.h> #include <unistd.h>
@ -29,86 +37,76 @@
#include <errno.h> #include <errno.h>
#include <dirent.h> #include <dirent.h>
#include <stdlib.h> #include <stdlib.h>
#include <assert.h>
#include "busybox.h" #include "busybox.h"
#include "libcoreutils/coreutils.h"
static const char cp_opts[] = "pdRfia"; /* WARNING!! ORDER IS IMPORTANT!! */
extern int cp_main(int argc, char **argv) extern int cp_main(int argc, char **argv)
{ {
struct stat source_stat;
struct stat dest_stat;
const char *last;
const char *dest;
int s_flags;
int d_flags;
int flags;
int status = 0; int status = 0;
int opt;
int flags = FILEUTILS_DEREFERENCE;
int i;
while ((opt = getopt(argc, argv, "adfipR")) != -1) /* Since these are enums, #if tests will not work. So use assert()s. */
switch (opt) { assert(FILEUTILS_PRESERVE_STATUS == 1);
case 'a': assert(FILEUTILS_DEREFERENCE == 2);
flags |= FILEUTILS_PRESERVE_STATUS | FILEUTILS_RECUR; assert(FILEUTILS_RECUR == 4);
/* fallthrough */ assert(FILEUTILS_FORCE == 8);
case 'd': assert(FILEUTILS_INTERACTIVE == 16);
flags &= ~FILEUTILS_DEREFERENCE;
break; flags = bb_getopt_ulflags(argc, argv, cp_opts);
case 'f':
flags |= FILEUTILS_FORCE; if (flags & 32) {
break; flags |= (FILEUTILS_PRESERVE_STATUS | FILEUTILS_RECUR | FILEUTILS_DEREFERENCE);
case 'i': }
flags |= FILEUTILS_INTERACTIVE;
break; flags ^= FILEUTILS_DEREFERENCE; /* The sense of this flag was reversed. */
case 'p':
flags |= FILEUTILS_PRESERVE_STATUS; if (optind + 2 > argc) {
break; bb_show_usage();
case 'R': }
flags |= FILEUTILS_RECUR;
break; last = argv[argc - 1];
default: argv += optind;
show_usage();
}
if (optind + 2 > argc)
show_usage();
/* If there are only two arguments and... */ /* If there are only two arguments and... */
if (optind + 2 == argc) { if (optind + 2 == argc) {
struct stat source_stat; s_flags = cp_mv_stat2(*argv, &source_stat,
struct stat dest_stat; (flags & FILEUTILS_DEREFERENCE) ? stat : lstat);
int source_exists = 1; if ((s_flags < 0) || ((d_flags = cp_mv_stat(last, &dest_stat)) < 0)) {
int dest_exists = 1; exit(EXIT_FAILURE);
if ((!(flags & FILEUTILS_DEREFERENCE) &&
lstat(argv[optind], &source_stat) < 0) ||
((flags & FILEUTILS_DEREFERENCE) &&
stat(argv[optind], &source_stat))) {
if (errno != ENOENT)
perror_msg_and_die("unable to stat `%s'", argv[optind]);
source_exists = 0;
} }
if (stat(argv[optind + 1], &dest_stat) < 0) {
if (errno != ENOENT)
perror_msg_and_die("unable to stat `%s'", argv[optind + 1]);
dest_exists = 0;
}
/* ...if neither is a directory or... */ /* ...if neither is a directory or... */
if (((!source_exists || !S_ISDIR(source_stat.st_mode)) && if ( !((s_flags | d_flags) & 2) ||
(!dest_exists || !S_ISDIR(dest_stat.st_mode))) || /* ...recursing, the 1st is a directory, and the 2nd doesn't exist... */
/* ...recursing, the first is a directory, and the /* ((flags & FILEUTILS_RECUR) && (s_flags & 2) && !d_flags) */
* second doesn't exist, then... */ /* Simplify the above since FILEUTILS_RECUR >> 1 == 2. */
((flags & FILEUTILS_RECUR) && S_ISDIR(source_stat.st_mode) && ((((flags & FILEUTILS_RECUR) >> 1) & s_flags) && !d_flags)
!dest_exists)) { ) {
/* ...do a simple copy. */ /* ...do a simple copy. */
if (copy_file(argv[optind], argv[optind + 1], flags) < 0) dest = last;
status = 1; goto DO_COPY; /* Note: optind+2==argc implies argv[1]==last below. */
return status;
} }
} }
for (i = optind; i < argc - 1; i++) { do {
char *dest = concat_path_file(argv[argc - 1], dest = concat_path_file(last, bb_get_last_path_component(*argv));
get_last_path_component(argv[i])); DO_COPY:
if (copy_file(argv[i], dest, flags) < 0) if (copy_file(*argv, dest, flags) < 0) {
status = 1; status = 1;
free(dest); }
} if (*++argv == last) {
break;
}
free((void *) dest);
} while (1);
return status; exit(status);
} }

View File

@ -92,7 +92,7 @@ static void parse_lists(char *lists)
} else { } else {
s = strtoul(ntok, &junk, 10); s = strtoul(ntok, &junk, 10);
if(*junk != '\0' || s < 0) if(*junk != '\0' || s < 0)
error_msg_and_die("invalid byte or field list"); bb_error_msg_and_die("invalid byte or field list");
/* account for the fact that arrays are zero based, while the user /* account for the fact that arrays are zero based, while the user
* expects the first char on the line to be char # 1 */ * expects the first char on the line to be char # 1 */
@ -109,7 +109,7 @@ static void parse_lists(char *lists)
} else { } else {
e = strtoul(ntok, &junk, 10); e = strtoul(ntok, &junk, 10);
if(*junk != '\0' || e < 0) if(*junk != '\0' || e < 0)
error_msg_and_die("invalid byte or field list"); bb_error_msg_and_die("invalid byte or field list");
/* if the user specified and end position of 0, that means "til the /* if the user specified and end position of 0, that means "til the
* end of the line */ * end of the line */
if (e == 0) if (e == 0)
@ -121,7 +121,7 @@ static void parse_lists(char *lists)
/* if there's something left to tokenize, the user past an invalid list */ /* if there's something left to tokenize, the user past an invalid list */
if (ltok) if (ltok)
error_msg_and_die("invalid byte or field list"); bb_error_msg_and_die("invalid byte or field list");
/* add the new list */ /* add the new list */
cut_lists = xrealloc(cut_lists, sizeof(struct cut_list) * (++nlists)); cut_lists = xrealloc(cut_lists, sizeof(struct cut_list) * (++nlists));
@ -131,7 +131,7 @@ static void parse_lists(char *lists)
/* make sure we got some cut positions out of all that */ /* make sure we got some cut positions out of all that */
if (nlists == 0) if (nlists == 0)
error_msg_and_die("missing list of positions"); bb_error_msg_and_die("missing list of positions");
/* now that the lists are parsed, we need to sort them to make life easier /* now that the lists are parsed, we need to sort them to make life easier
* on us when it comes time to print the chars / fields / lines */ * on us when it comes time to print the chars / fields / lines */
@ -267,8 +267,7 @@ static void cut_file(FILE *file)
unsigned int linenum = 0; /* keep these zero-based to be consistent */ unsigned int linenum = 0; /* keep these zero-based to be consistent */
/* go through every line in the file */ /* go through every line in the file */
while ((line = get_line_from_file(file)) != NULL) { while ((line = bb_get_chomped_line_from_file(file)) != NULL) {
chomp(line);
/* cut based on chars/bytes XXX: only works when sizeof(char) == byte */ /* cut based on chars/bytes XXX: only works when sizeof(char) == byte */
if (part == 'c' || part == 'b') if (part == 'c' || part == 'b')
@ -299,14 +298,14 @@ extern int cut_main(int argc, char **argv)
case 'f': case 'f':
/* make sure they didn't ask for two types of lists */ /* make sure they didn't ask for two types of lists */
if (part != 0) { if (part != 0) {
error_msg_and_die("only one type of list may be specified"); bb_error_msg_and_die("only one type of list may be specified");
} }
part = (char)opt; part = (char)opt;
parse_lists(optarg); parse_lists(optarg);
break; break;
case 'd': case 'd':
if (strlen(optarg) > 1) { if (strlen(optarg) > 1) {
error_msg_and_die("the delimiter must be a single character"); bb_error_msg_and_die("the delimiter must be a single character");
} }
delim = optarg[0]; delim = optarg[0];
break; break;
@ -320,17 +319,17 @@ extern int cut_main(int argc, char **argv)
} }
if (part == 0) { if (part == 0) {
error_msg_and_die("you must specify a list of bytes, characters, or fields"); bb_error_msg_and_die("you must specify a list of bytes, characters, or fields");
} }
/* non-field (char or byte) cutting has some special handling */ /* non-field (char or byte) cutting has some special handling */
if (part != 'f') { if (part != 'f') {
if (supress_non_delimited_lines) { if (supress_non_delimited_lines) {
error_msg_and_die("suppressing non-delimited lines makes sense" bb_error_msg_and_die("suppressing non-delimited lines makes sense"
" only when operating on fields"); " only when operating on fields");
} }
if (delim != '\t' && part != 'f') { if (delim != '\t' && part != 'f') {
error_msg_and_die("a delimiter may be specified only when operating on fields"); bb_error_msg_and_die("a delimiter may be specified only when operating on fields");
} }
} }
@ -344,7 +343,7 @@ extern int cut_main(int argc, char **argv)
int i; int i;
FILE *file; FILE *file;
for (i = optind; i < argc; i++) { for (i = optind; i < argc; i++) {
file = wfopen(argv[i], "r"); file = bb_wfopen(argv[i], "r");
if(file) { if(file) {
cut_file(file); cut_file(file);
fclose(file); fclose(file);

View File

@ -53,7 +53,7 @@ static struct tm *date_conv_time(struct tm *tm_time, const char *t_string)
&(tm_time->tm_year)); &(tm_time->tm_year));
if (nr < 4 || nr > 5) { if (nr < 4 || nr > 5) {
error_msg_and_die(invalid_date, t_string); bb_error_msg_and_die(bb_msg_invalid_date, t_string);
} }
/* correct for century - minor Y2K problem here? */ /* correct for century - minor Y2K problem here? */
@ -108,7 +108,7 @@ static struct tm *date_conv_ftime(struct tm *tm_time, const char *t_string)
t.tm_year -= 1900; /* Adjust years */ t.tm_year -= 1900; /* Adjust years */
t.tm_mon -= 1; /* Adjust dates from 1-12 to 0-11 */ t.tm_mon -= 1; /* Adjust dates from 1-12 to 0-11 */
} else { } else {
error_msg_and_die(invalid_date, t_string); bb_error_msg_and_die(bb_msg_invalid_date, t_string);
} }
*tm_time = t; *tm_time = t;
return (tm_time); return (tm_time);
@ -145,25 +145,25 @@ int date_main(int argc, char **argv)
case 's': case 's':
set_time = 1; set_time = 1;
if ((date_str != NULL) || ((date_str = optarg) == NULL)) { if ((date_str != NULL) || ((date_str = optarg) == NULL)) {
show_usage(); bb_show_usage();
} }
break; break;
case 'u': case 'u':
utc = 1; utc = 1;
if (putenv("TZ=UTC0") != 0) if (putenv("TZ=UTC0") != 0)
error_msg_and_die(memory_exhausted); bb_error_msg_and_die(bb_msg_memory_exhausted);
break; break;
case 'd': case 'd':
use_arg = 1; use_arg = 1;
if ((date_str != NULL) || ((date_str = optarg) == NULL)) if ((date_str != NULL) || ((date_str = optarg) == NULL))
show_usage(); bb_show_usage();
break; break;
#ifdef CONFIG_FEATURE_DATE_ISOFMT #ifdef CONFIG_FEATURE_DATE_ISOFMT
case 'I': case 'I':
if (!optarg) if (!optarg)
ifmt = 1; ifmt = 1;
else { else {
int ifmt_len = xstrlen(optarg); int ifmt_len = bb_strlen(optarg);
if ((ifmt_len <= 4) if ((ifmt_len <= 4)
&& (strncmp(optarg, "date", ifmt_len) == 0)) { && (strncmp(optarg, "date", ifmt_len) == 0)) {
@ -180,11 +180,11 @@ int date_main(int argc, char **argv)
} }
} }
if (ifmt) { if (ifmt) {
break; /* else show_usage(); */ break; /* else bb_show_usage(); */
} }
#endif #endif
default: default:
show_usage(); bb_show_usage();
} }
} }
@ -220,15 +220,15 @@ int date_main(int argc, char **argv)
/* Correct any day of week and day of year etc. fields */ /* Correct any day of week and day of year etc. fields */
tm = mktime(&tm_time); tm = mktime(&tm_time);
if (tm < 0) { if (tm < 0) {
error_msg_and_die(invalid_date, date_str); bb_error_msg_and_die(bb_msg_invalid_date, date_str);
} }
if (utc && (putenv("TZ=UTC0") != 0)) { if (utc && (putenv("TZ=UTC0") != 0)) {
error_msg_and_die(memory_exhausted); bb_error_msg_and_die(bb_msg_memory_exhausted);
} }
/* if setting time, set it */ /* if setting time, set it */
if (set_time && (stime(&tm) < 0)) { if (set_time && (stime(&tm) < 0)) {
perror_msg("cannot set date"); bb_perror_msg("cannot set date");
} }
} }

View File

@ -62,19 +62,19 @@ int dd_main(int argc, char **argv)
int ifd; int ifd;
int ofd; int ofd;
int i; int i;
char *infile = NULL; const char *infile = NULL;
char *outfile = NULL; const char *outfile = NULL;
char *buf; char *buf;
for (i = 1; i < argc; i++) { for (i = 1; i < argc; i++) {
if (strncmp("bs=", argv[i], 3) == 0) if (strncmp("bs=", argv[i], 3) == 0)
bs = parse_number(argv[i]+3, dd_suffixes); bs = bb_xparse_number(argv[i]+3, dd_suffixes);
else if (strncmp("count=", argv[i], 6) == 0) else if (strncmp("count=", argv[i], 6) == 0)
count = parse_number(argv[i]+6, dd_suffixes); count = bb_xparse_number(argv[i]+6, dd_suffixes);
else if (strncmp("seek=", argv[i], 5) == 0) else if (strncmp("seek=", argv[i], 5) == 0)
seek = parse_number(argv[i]+5, dd_suffixes); seek = bb_xparse_number(argv[i]+5, dd_suffixes);
else if (strncmp("skip=", argv[i], 5) == 0) else if (strncmp("skip=", argv[i], 5) == 0)
skip = parse_number(argv[i]+5, dd_suffixes); skip = bb_xparse_number(argv[i]+5, dd_suffixes);
else if (strncmp("if=", argv[i], 3) == 0) else if (strncmp("if=", argv[i], 3) == 0)
infile = argv[i]+3; infile = argv[i]+3;
else if (strncmp("of=", argv[i], 3) == 0) else if (strncmp("of=", argv[i], 3) == 0)
@ -92,7 +92,7 @@ int dd_main(int argc, char **argv)
noerror = TRUE; noerror = TRUE;
buf += 7; buf += 7;
} else { } else {
error_msg_and_die("invalid conversion `%s'", argv[i]+5); bb_error_msg_and_die("invalid conversion `%s'", argv[i]+5);
} }
if (buf[0] == '\0') if (buf[0] == '\0')
break; break;
@ -100,18 +100,18 @@ int dd_main(int argc, char **argv)
buf++; buf++;
} }
} else } else
show_usage(); bb_show_usage();
} }
buf = xmalloc(bs); buf = xmalloc(bs);
if (infile != NULL) { if (infile != NULL) {
if ((ifd = open(infile, O_RDONLY)) < 0) { if ((ifd = open(infile, O_RDONLY)) < 0) {
perror_msg_and_die("%s", infile); bb_perror_msg_and_die("%s", infile);
} }
} else { } else {
ifd = STDIN_FILENO; ifd = STDIN_FILENO;
infile = "standard input"; infile = bb_msg_standard_input;
} }
if (outfile != NULL) { if (outfile != NULL) {
@ -122,7 +122,7 @@ int dd_main(int argc, char **argv)
} }
if ((ofd = open(outfile, oflag, 0666)) < 0) { if ((ofd = open(outfile, oflag, 0666)) < 0) {
perror_msg_and_die("%s", outfile); bb_perror_msg_and_die("%s", outfile);
} }
if (seek && trunc) { if (seek && trunc) {
@ -131,24 +131,24 @@ int dd_main(int argc, char **argv)
if (fstat (ofd, &st) < 0 || S_ISREG (st.st_mode) || if (fstat (ofd, &st) < 0 || S_ISREG (st.st_mode) ||
S_ISDIR (st.st_mode)) { S_ISDIR (st.st_mode)) {
perror_msg_and_die("%s", outfile); bb_perror_msg_and_die("%s", outfile);
} }
} }
} }
} else { } else {
ofd = STDOUT_FILENO; ofd = STDOUT_FILENO;
outfile = "standard output"; outfile = bb_msg_standard_output;
} }
if (skip) { if (skip) {
if (lseek(ifd, skip * bs, SEEK_CUR) < 0) { if (lseek(ifd, skip * bs, SEEK_CUR) < 0) {
perror_msg_and_die("%s", infile); bb_perror_msg_and_die("%s", infile);
} }
} }
if (seek) { if (seek) {
if (lseek(ofd, seek * bs, SEEK_CUR) < 0) { if (lseek(ofd, seek * bs, SEEK_CUR) < 0) {
perror_msg_and_die("%s", outfile); bb_perror_msg_and_die("%s", outfile);
} }
} }
@ -161,9 +161,9 @@ int dd_main(int argc, char **argv)
if (n < 0) { if (n < 0) {
if (noerror) { if (noerror) {
n = bs; n = bs;
perror_msg("%s", infile); bb_perror_msg("%s", infile);
} else { } else {
perror_msg_and_die("%s", infile); bb_perror_msg_and_die("%s", infile);
} }
} }
if (n == 0) { if (n == 0) {
@ -178,9 +178,9 @@ int dd_main(int argc, char **argv)
memset(buf + n, '\0', bs - n); memset(buf + n, '\0', bs - n);
n = bs; n = bs;
} }
n = full_write(ofd, buf, n); n = bb_full_write(ofd, buf, n);
if (n < 0) { if (n < 0) {
perror_msg_and_die("%s", outfile); bb_perror_msg_and_die("%s", outfile);
} }
if (n == bs) { if (n == bs) {
out_full++; out_full++;
@ -190,15 +190,16 @@ int dd_main(int argc, char **argv)
} }
if (close (ifd) < 0) { if (close (ifd) < 0) {
perror_msg_and_die("%s", infile); bb_perror_msg_and_die("%s", infile);
} }
if (close (ofd) < 0) { if (close (ofd) < 0) {
perror_msg_and_die("%s", outfile); bb_perror_msg_and_die("%s", outfile);
} }
fprintf(stderr, "%ld+%ld records in\n", (long)in_full, (long)in_part); fprintf(stderr, "%ld+%ld records in\n%ld+%ld records out\n",
fprintf(stderr, "%ld+%ld records out\n", (long)out_full, (long)out_part); (long)in_full, (long)in_part,
(long)out_full, (long)out_part);
return EXIT_SUCCESS; return EXIT_SUCCESS;
} }

View File

@ -22,74 +22,45 @@
* *
*/ */
/* BB_AUDIT SUSv3 _NOT_ compliant -- options -P and -t missing. Also blocksize. */
/* http://www.opengroup.org/onlinepubs/007904975/utilities/df.html */
/* Mar 16, 2003 Manuel Novoa III (mjn3@codepoet.org)
*
* Size reduction. Removed floating point dependency. Added error checking
* on output. Output stats on 0-sized filesystems if specificly listed on
* the command line. Properly round *-blocks, Used, and Available quantities.
*/
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <string.h> #include <string.h>
#include <unistd.h>
#include <mntent.h> #include <mntent.h>
#include <sys/vfs.h> #include <sys/vfs.h>
#include <getopt.h>
#include "busybox.h" #include "busybox.h"
extern const char mtab_file[]; /* Defined in utility.c */ #ifndef CONFIG_FEATURE_HUMAN_READABLE
#ifdef CONFIG_FEATURE_HUMAN_READABLE static long kscale(long b, long bs)
static unsigned long df_disp_hr = KILOBYTE;
#endif
static int do_df(char *device, const char *mount_point)
{ {
struct statfs s; return ( b * (long long) bs + KILOBYTE/2 ) / KILOBYTE;
long blocks_used;
long blocks_percent_used;
if (statfs(mount_point, &s) != 0) {
perror_msg("%s", mount_point);
return FALSE;
}
if (s.f_blocks > 0) {
blocks_used = s.f_blocks - s.f_bfree;
if(blocks_used == 0)
blocks_percent_used = 0;
else {
blocks_percent_used = (long)
(blocks_used * 100.0 / (blocks_used + s.f_bavail) + 0.5);
}
if (strcmp(device, "/dev/root") == 0) {
/* Adjusts device to be the real root device,
* or leaves device alone if it can't find it */
device = find_real_root_device_name(device);
if(device==NULL)
return FALSE;
}
#ifdef CONFIG_FEATURE_HUMAN_READABLE
printf("%-20s %9s ", device,
make_human_readable_str(s.f_blocks, s.f_bsize, df_disp_hr));
printf("%9s ",
make_human_readable_str( (s.f_blocks - s.f_bfree), s.f_bsize, df_disp_hr));
printf("%9s %3ld%% %s\n",
make_human_readable_str(s.f_bavail, s.f_bsize, df_disp_hr),
blocks_percent_used, mount_point);
#else
printf("%-20s %9ld %9ld %9ld %3ld%% %s\n",
device,
(long) (s.f_blocks * (s.f_bsize / (double)KILOBYTE)),
(long) ((s.f_blocks - s.f_bfree)*(s.f_bsize/(double)KILOBYTE)),
(long) (s.f_bavail * (s.f_bsize / (double)KILOBYTE)),
blocks_percent_used, mount_point);
#endif
}
return TRUE;
} }
#endif
extern int df_main(int argc, char **argv) extern int df_main(int argc, char **argv)
{ {
long blocks_used;
long blocks_percent_used;
#ifdef CONFIG_FEATURE_HUMAN_READABLE
unsigned long df_disp_hr = KILOBYTE;
#endif
int status = EXIT_SUCCESS; int status = EXIT_SUCCESS;
int opt = 0; int opt;
int i = 0; FILE *mount_table;
char disp_units_hdr[80] = "1k-blocks"; /* default display is kilobytes */ struct mntent *mount_entry;
struct statfs s;
static const char hdr_1k[] = "1k-blocks"; /* default display is kilobytes */;
const char *disp_units_hdr = hdr_1k;
while ((opt = getopt(argc, argv, "k" while ((opt = getopt(argc, argv, "k"
#ifdef CONFIG_FEATURE_HUMAN_READABLE #ifdef CONFIG_FEATURE_HUMAN_READABLE
@ -101,52 +72,106 @@ extern int df_main(int argc, char **argv)
#ifdef CONFIG_FEATURE_HUMAN_READABLE #ifdef CONFIG_FEATURE_HUMAN_READABLE
case 'h': case 'h':
df_disp_hr = 0; df_disp_hr = 0;
strcpy(disp_units_hdr, " Size"); disp_units_hdr = " Size";
break; break;
case 'm': case 'm':
df_disp_hr = MEGABYTE; df_disp_hr = MEGABYTE;
strcpy(disp_units_hdr, "1M-blocks"); disp_units_hdr = "1M-blocks";
break; break;
#endif #endif
case 'k': case 'k':
/* default display is kilobytes */ /* default display is kilobytes */
#ifdef CONFIG_FEATURE_HUMAN_READABLE
df_disp_hr = KILOBYTE;
disp_units_hdr = hdr_1k;
#endif
break; break;
default: default:
show_usage(); bb_show_usage();
} }
} }
printf("%-20s %-14s %s %s %s %s\n", "Filesystem", disp_units_hdr, bb_printf("Filesystem%11s%-15sUsed Available Use%% Mounted on\n",
"Used", "Available", "Use%", "Mounted on"); "", disp_units_hdr);
if(optind < argc) { mount_table = NULL;
struct mntent *mount_entry; argv += optind;
for(i = optind; i < argc; i++) if (optind >= argc) {
{ if (!(mount_table = setmntent(bb_path_mtab_file, "r"))) {
if ((mount_entry = find_mount_point(argv[i], mtab_file)) == 0) { bb_perror_msg_and_die(bb_path_mtab_file);
error_msg("%s: can't find mount point.", argv[i]);
status = EXIT_FAILURE;
} else if (!do_df(mount_entry->mnt_fsname, mount_entry->mnt_dir))
status = EXIT_FAILURE;
} }
} else {
FILE *mount_table;
struct mntent *mount_entry;
mount_table = setmntent(mtab_file, "r");
if (mount_table == 0) {
perror_msg("%s", mtab_file);
return EXIT_FAILURE;
}
while ((mount_entry = getmntent(mount_table))) {
if (!do_df(mount_entry->mnt_fsname, mount_entry->mnt_dir))
status = EXIT_FAILURE;
}
endmntent(mount_table);
} }
return status; do {
const char *device;
const char *mount_point;
if (mount_table) {
if (!(mount_entry = getmntent(mount_table))) {
endmntent(mount_table);
break;
}
} else {
if (!(mount_point = *argv++)) {
break;
}
if (!(mount_entry = find_mount_point(mount_point, bb_path_mtab_file))) {
bb_error_msg("%s: can't find mount point.", mount_point);
SET_ERROR:
status = EXIT_FAILURE;
continue;
}
}
device = mount_entry->mnt_fsname;
mount_point = mount_entry->mnt_dir;
if (statfs(mount_point, &s) != 0) {
bb_perror_msg("%s", mount_point);
goto SET_ERROR;
}
if ((s.f_blocks > 0) || !mount_table){
blocks_used = s.f_blocks - s.f_bfree;
blocks_percent_used = 0;
if (blocks_used + s.f_bavail) {
blocks_percent_used = (((long long) blocks_used) * 100
+ (blocks_used + s.f_bavail)/2
) / (blocks_used + s.f_bavail);
}
if (strcmp(device, "/dev/root") == 0) {
/* Adjusts device to be the real root device,
* or leaves device alone if it can't find it */
if ((device = find_real_root_device_name(device)) != NULL) {
goto SET_ERROR;
}
}
#ifdef CONFIG_FEATURE_HUMAN_READABLE
bb_printf("%-21s%9s ", device,
make_human_readable_str(s.f_blocks, s.f_bsize, df_disp_hr));
bb_printf("%9s ",
make_human_readable_str( (s.f_blocks - s.f_bfree),
s.f_bsize, df_disp_hr));
bb_printf("%9s %3ld%% %s\n",
make_human_readable_str(s.f_bavail, s.f_bsize, df_disp_hr),
blocks_percent_used, mount_point);
#else
bb_printf("%-21s%9ld %9ld %9ld %3ld%% %s\n",
device,
kscale(s.f_blocks, s.f_bsize),
kscale(s.f_blocks-s.f_bfree, s.f_bsize),
kscale(s.f_bavail, s.f_bsize),
blocks_percent_used, mount_point);
#endif
}
} while (1);
bb_fflush_stdout_and_exit(status);
} }
/* /*

View File

@ -21,20 +21,20 @@
* *
*/ */
/* getopt not needed */ /* BB_AUDIT SUSv3 compliant */
/* http://www.opengroup.org/onlinepubs/007904975/utilities/dirname.html */
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <string.h>
#include "busybox.h" #include "busybox.h"
extern int dirname_main(int argc, char **argv) extern int dirname_main(int argc, char **argv)
{ {
if ((argc < 2) || (**(argv + 1) == '-')) if (argc != 2) {
show_usage(); bb_show_usage();
argv++; }
puts (dirname (argv[0])); puts(dirname(argv[1]));
return EXIT_SUCCESS; bb_fflush_stdout_and_exit(EXIT_SUCCESS);
} }

View File

@ -35,6 +35,10 @@
#include <sys/time.h> #include <sys/time.h>
#include "busybox.h" #include "busybox.h"
#define CT_AUTO 0
#define CT_UNIX2DOS 1
#define CT_DOS2UNIX 2
/* We are making a lame pseudo-random string generator here. in /* We are making a lame pseudo-random string generator here. in
* convert(), each pass through the while loop will add more and more * convert(), each pass through the while loop will add more and more
* stuff into value, which is _supposed_ to wrap. We don't care about * stuff into value, which is _supposed_ to wrap. We don't care about
@ -55,15 +59,13 @@ static int convert(char *fn, int ConvType)
FILE *in = stdin, *out = stdout; FILE *in = stdin, *out = stdout;
if (fn != NULL) { if (fn != NULL) {
if ((in = wfopen(fn, "rw")) == NULL) { in = bb_xfopen(fn, "rw");
return -1;
}
safe_strncpy(tempFn, fn, sizeof(tempFn)); safe_strncpy(tempFn, fn, sizeof(tempFn));
c = strlen(tempFn); c = strlen(tempFn);
tempFn[c] = '.'; tempFn[c] = '.';
while(1) { while(1) {
if (c >=BUFSIZ) if (c >=BUFSIZ)
error_msg_and_die("unique name not found"); bb_error_msg_and_die("unique name not found");
/* Get some semi random stuff to try and make a /* Get some semi random stuff to try and make a
* random filename based (and in the same dir as) * random filename based (and in the same dir as)
* the input file... */ * the input file... */
@ -92,7 +94,7 @@ static int convert(char *fn, int ConvType)
// file is alredy in DOS format so it is not necessery to touch it // file is alredy in DOS format so it is not necessery to touch it
remove(tempFn); remove(tempFn);
if (fclose(in) < 0 || fclose(out) < 0) { if (fclose(in) < 0 || fclose(out) < 0) {
perror_msg(NULL); bb_perror_nomsg();
return -2; return -2;
} }
return 0; return 0;
@ -106,7 +108,7 @@ static int convert(char *fn, int ConvType)
// file is alredy in UNIX format so it is not necessery to touch it // file is alredy in UNIX format so it is not necessery to touch it
remove(tempFn); remove(tempFn);
if ((fclose(in) < 0) || (fclose(out) < 0)) { if ((fclose(in) < 0) || (fclose(out) < 0)) {
perror_msg(NULL); bb_perror_nomsg();
return -2; return -2;
} }
return 0; return 0;
@ -137,7 +139,7 @@ static int convert(char *fn, int ConvType)
if (fn != NULL) { if (fn != NULL) {
if (fclose(in) < 0 || fclose(out) < 0) { if (fclose(in) < 0 || fclose(out) < 0) {
perror_msg(NULL); bb_perror_nomsg();
remove(tempFn); remove(tempFn);
return -2; return -2;
} }
@ -146,7 +148,7 @@ static int convert(char *fn, int ConvType)
* should be true since we put them into the same directory * should be true since we put them into the same directory
* so we _should_ be ok, but you never know... */ * so we _should_ be ok, but you never know... */
if (rename(tempFn, fn) < 0) { if (rename(tempFn, fn) < 0) {
perror_msg("unable to rename '%s' as '%s'", tempFn, fn); bb_perror_msg("unable to rename '%s' as '%s'", tempFn, fn);
return -1; return -1;
} }
} }
@ -177,7 +179,7 @@ int dos2unix_main(int argc, char *argv[])
ConvType = CT_DOS2UNIX; ConvType = CT_DOS2UNIX;
break; break;
default: default:
show_usage(); bb_show_usage();
} }
} }

View File

@ -22,45 +22,65 @@
* *
*/ */
#include <sys/types.h> /* BB_AUDIT SUSv3 compliant (unless default blocksize set to 1k) */
#include <fcntl.h> /* http://www.opengroup.org/onlinepubs/007904975/utilities/du.html */
#include <dirent.h>
#include <stdio.h> /* Mar 16, 2003 Manuel Novoa III (mjn3@codepoet.org)
*
* Mostly rewritten for SUSv3 compliance and to fix bugs/defects.
* 1) Added support for SUSv3 -a, -H, -L, gnu -c, and (busybox) -d options.
* The -d option allows setting of max depth (similar to gnu --max-depth).
* 2) Fixed incorrect size calculations for links and directories, especially
* when errors occurred. Calculates sizes should now match gnu du output.
* 3) Added error checking of output.
* 4) Fixed busybox bug #1284 involving long overflow with human_readable.
*/
#include <stdlib.h> #include <stdlib.h>
#include <getopt.h> #include <limits.h>
#include <string.h> #include <unistd.h>
#include <errno.h> #include <dirent.h>
#include <sys/stat.h>
#include "busybox.h" #include "busybox.h"
#ifdef CONFIG_FEATURE_HUMAN_READABLE #ifdef CONFIG_FEATURE_HUMAN_READABLE
# ifdef CONFIG_FEATURE_DU_DEFALT_BLOCKSIZE_1K
static unsigned long disp_hr = KILOBYTE; static unsigned long disp_hr = KILOBYTE;
# else
static unsigned long disp_hr = 512;
# endif
#elif defined CONFIG_FEATURE_DU_DEFALT_BLOCKSIZE_1K
static unsigned int disp_k = 1;
#else
static unsigned int disp_k; /* bss inits to 0 */
#endif #endif
static int du_depth /*= 0*/; static int max_print_depth = INT_MAX;
static int count_hardlinks /*= 0*/; static int count_hardlinks = INT_MAX;
static int one_file_system /*= 0*/;
static int status
#if EXIT_SUCCESS == 0
= EXIT_SUCCESS
#endif
;
static int print_files;
static int slink_depth;
static int du_depth;
static int one_file_system;
static dev_t dir_dev; static dev_t dir_dev;
static void (*print) (long, char *);
static void print_normal(long size, char *filename) static void print(long size, char *filename)
{ {
/* TODO - May not want to defer error checking here. */
#ifdef CONFIG_FEATURE_HUMAN_READABLE #ifdef CONFIG_FEATURE_HUMAN_READABLE
printf("%s\t%s\n", make_human_readable_str(size << 10, 1, disp_hr), bb_printf("%s\t%s\n", make_human_readable_str(size, 512, disp_hr),
filename); filename);
#else #else
printf("%ld\t%s\n", size, filename); bb_printf("%ld\t%s\n", size >> disp_k, filename);
#endif #endif
} }
static void print_summary(long size, char *filename)
{
if (du_depth == 1) {
print_normal(size, filename);
}
}
/* tiny recursive du */ /* tiny recursive du */
static long du(char *filename) static long du(char *filename)
{ {
@ -68,23 +88,43 @@ static long du(char *filename)
long sum; long sum;
if ((lstat(filename, &statbuf)) != 0) { if ((lstat(filename, &statbuf)) != 0) {
perror_msg("%s", filename); bb_perror_msg("%s", filename);
status = EXIT_FAILURE;
return 0; return 0;
} }
if (du_depth == 0)
dir_dev = statbuf.st_dev;
else if (one_file_system && dir_dev != statbuf.st_dev)
return 0;
du_depth++; if (one_file_system) {
sum = (statbuf.st_blocks >> 1); if (du_depth == 0) {
dir_dev = statbuf.st_dev;
/* Don't add in stuff pointed to by symbolic links */ } else if (dir_dev != statbuf.st_dev) {
if (S_ISLNK(statbuf.st_mode)) { return 0;
sum = 0L;
if (du_depth == 1) {
} }
} }
sum = statbuf.st_blocks;
if (S_ISLNK(statbuf.st_mode)) {
if (slink_depth > du_depth) { /* -H or -L */
if ((stat(filename, &statbuf)) != 0) {
bb_perror_msg("%s", filename);
status = EXIT_FAILURE;
return 0;
}
sum = statbuf.st_blocks;
if (slink_depth == 1) {
slink_depth = INT_MAX; /* Convert -H to -L. */
}
}
}
if (statbuf.st_nlink > count_hardlinks) {
/* Add files/directories with links only once */
if (is_in_ino_dev_hashtable(&statbuf, NULL)) {
return 0;
}
add_to_ino_dev_hashtable(&statbuf, NULL);
}
if (S_ISDIR(statbuf.st_mode)) { if (S_ISDIR(statbuf.st_mode)) {
DIR *dir; DIR *dir;
struct dirent *entry; struct dirent *entry;
@ -92,8 +132,9 @@ static long du(char *filename)
dir = opendir(filename); dir = opendir(filename);
if (!dir) { if (!dir) {
du_depth--; bb_perror_msg("%s", filename);
return 0; status = EXIT_FAILURE;
return sum;
} }
newfile = last_char_is(filename, '/'); newfile = last_char_is(filename, '/');
@ -103,54 +144,86 @@ static long du(char *filename)
while ((entry = readdir(dir))) { while ((entry = readdir(dir))) {
char *name = entry->d_name; char *name = entry->d_name;
if ((strcmp(name, "..") == 0) if ((name[0] == '.') && (!name[1] || (name[1] == '.' && !name[2]))) {
|| (strcmp(name, ".") == 0)) {
continue; continue;
} }
newfile = concat_path_file(filename, name); newfile = concat_path_file(filename, name);
++du_depth;
sum += du(newfile); sum += du(newfile);
--du_depth;
free(newfile); free(newfile);
} }
closedir(dir); closedir(dir);
print(sum, filename); } else if (du_depth > print_files) {
} else if (statbuf.st_nlink > 1 && !count_hardlinks) { return sum;
/* Add files with hard links only once */ }
if (is_in_ino_dev_hashtable(&statbuf, NULL)) { if (du_depth <= max_print_depth) {
sum = 0L; print(sum, filename);
if (du_depth == 1)
print(sum, filename);
} else {
add_to_ino_dev_hashtable(&statbuf, NULL);
}
} }
du_depth--;
return sum; return sum;
} }
int du_main(int argc, char **argv) int du_main(int argc, char **argv)
{ {
int status = EXIT_SUCCESS; long total;
int i; int slink_depth_save;
int print_final_total = 0;
int c; int c;
/* default behaviour */ #ifdef CONFIG_FEATURE_DU_DEFALT_BLOCKSIZE_1K
print = print_normal; if (getenv("POSIXLY_CORRECT")) { /* TODO - a new libbb function? */
#ifdef CONFIG_FEATURE_HUMAN_READABLE
disp_hr = 512;
#else
disp_k = 0;
#endif
}
#endif
/* parse argv[] */ /* Note: SUSv3 specifies that -a and -s options can not be used together
while ((c = getopt(argc, argv, "slx" * in strictly conforming applications. However, it also says that some
* du implementations may produce output when -a and -s are used together.
* gnu du exits with an error code in this case. We choose to simply
* ignore -a. This is consistent with -s being equivalent to -d 0.
*/
while ((c = getopt(argc, argv, "aHkLsx" "d:" "lc"
#ifdef CONFIG_FEATURE_HUMAN_READABLE #ifdef CONFIG_FEATURE_HUMAN_READABLE
"hm" "hm"
#endif #endif
"k")) != EOF) { )) > 0) {
switch (c) { switch (c) {
case 'a':
print_files = INT_MAX;
break;
case 'H':
slink_depth = 1;
break;
case 'k':
#ifdef CONFIG_FEATURE_HUMAN_READABLE
disp_hr = KILOBYTE;
#elif !defined CONFIG_FEATURE_DU_DEFALT_BLOCKSIZE_1K
disp_k = 1;
#endif
break;
case 'L':
slink_depth = INT_MAX;
break;
case 's': case 's':
print = print_summary; max_print_depth = 0;
break;
case 'x':
one_file_system = 1;
break;
case 'd':
max_print_depth = bb_xgetularg10_bnd(optarg, 0, INT_MAX);
break; break;
case 'l': case 'l':
count_hardlinks = 1; count_hardlinks = 1;
break; break;
case 'x': case 'c':
one_file_system = 1; print_final_total = 1;
break; break;
#ifdef CONFIG_FEATURE_HUMAN_READABLE #ifdef CONFIG_FEATURE_HUMAN_READABLE
case 'h': case 'h':
@ -160,37 +233,31 @@ int du_main(int argc, char **argv)
disp_hr = MEGABYTE; disp_hr = MEGABYTE;
break; break;
#endif #endif
case 'k':
break;
default: default:
show_usage(); bb_show_usage();
} }
} }
/* go through remaining args (if any) */ /* go through remaining args (if any) */
argv += optind;
if (optind >= argc) { if (optind >= argc) {
if (du(".") == 0) *--argv = ".";
status = EXIT_FAILURE; if (slink_depth == 1) {
} else { slink_depth = 0;
long sum;
for (i = optind; i < argc; i++) {
sum = du(argv[i]);
if (is_directory(argv[i], FALSE, NULL) == FALSE) {
print_normal(sum, argv[i]);
}
reset_ino_dev_hashtable();
} }
} }
return status; slink_depth_save = slink_depth;
} total = 0;
do {
total += du(*argv);
slink_depth = slink_depth_save;
} while (*++argv);
reset_ino_dev_hashtable();
/* $Id: du.c,v 1.55 2002/08/23 07:28:45 aaronl Exp $ */ if (print_final_total) {
/* print(total, "total");
Local Variables: }
c-file-style: "linux"
c-basic-offset: 4 bb_fflush_stdout_and_exit(status);
tab-width: 4 }
End:
*/

View File

@ -22,94 +22,107 @@
* Original copyright notice is retained at the end of this file. * Original copyright notice is retained at the end of this file.
*/ */
/* BB_AUDIT SUSv3 compliant -- unless configured as fancy echo. */
/* http://www.opengroup.org/onlinepubs/007904975/utilities/echo.html */
/* Mar 16, 2003 Manuel Novoa III (mjn3@codepoet.org)
*
* Because of behavioral differences, implemented configureable SUSv3
* or 'fancy' gnu-ish behaviors. Also, reduced size and fixed bugs.
* 1) In handling '\c' escape, the previous version only suppressed the
* trailing newline. SUSv3 specifies _no_ output after '\c'.
* 2) SUSv3 specifies that octal escapes are of the form \0{#{#{#}}}.
* The previous version version did not allow 4-digit octals.
*/
#include <stdio.h> #include <stdio.h>
#include <string.h> #include <string.h>
#include <stdlib.h> #include <stdlib.h>
#include "busybox.h" #include "busybox.h"
extern int extern int echo_main(int argc, char** argv)
echo_main(int argc, char** argv)
{ {
int nflag = 0; #ifndef CONFIG_FEATURE_FANCY_ECHO
#define eflag '\\'
++argv;
#else
const char *p;
int nflag = 1;
int eflag = 0; int eflag = 0;
/* Skip argv[0]. */ while (*++argv && (**argv == '-')) {
argc--; /* If it appears that we are handling options, then make sure
argv++;
while (argc > 0 && *argv[0] == '-')
{
register char *temp;
register int ix;
/*
* If it appears that we are handling options, then make sure
* that all of the options specified are actually valid. * that all of the options specified are actually valid.
* Otherwise, the string should just be echoed. * Otherwise, the string should just be echoed.
*/ */
temp = argv[0] + 1;
if (!*(p = *argv + 1)) { /* A single '-', so echo it. */
for (ix = 0; temp[ix]; ix++)
{
if (strrchr("neE", temp[ix]) == 0)
goto just_echo;
}
if (!*temp)
goto just_echo; goto just_echo;
/*
* All of the options in temp are valid options to echo.
* Handle them.
*/
while (*temp)
{
if (*temp == 'n')
nflag = 1;
else if (*temp == 'e')
eflag = 1;
else if (*temp == 'E')
eflag = 0;
else
goto just_echo;
temp++;
} }
argc--;
argv++; do {
if (strrchr("neE", *p) == 0) {
goto just_echo;
}
} while (*++p);
/* All of the options in this arg are valid, so handle them. */
p = *argv + 1;
do {
if (*p == 'n') {
nflag = 0;
} else if (*p == 'e') {
eflag = '\\';
} else {
eflag = 0;
}
} while (*++p);
} }
just_echo: just_echo:
while (argc > 0) { #endif
const char *arg = argv[0]; while (*argv) {
register int c; register int c;
while ((c = *arg++)) { while ((c = *(*argv)++)) {
if (c == eflag) { /* Check for escape seq. */
/* Check for escape sequence. */ if (**argv == 'c') {
if (c == '\\' && eflag && *arg) { /* '\c' means cancel newline and
if (*arg == 'c') { * ignore all subsequent chars. */
/* '\c' means cancel newline. */ goto DONE;
nflag = 1; }
arg++; #ifndef CONFIG_FEATURE_FANCY_ECHO
continue; /* SUSv3 specifies that octal escapes must begin with '0'. */
} else { if (((unsigned int)(**argv - '1')) >= 7)
c = process_escape_sequence(&arg); #endif
{
/* Since SUSv3 mandates a first digit of 0, 4-digit octals
* of the form \0### are accepted. */
if ((**argv == '0') && (((unsigned int)(argv[0][1] - '0')) < 8)) {
(*argv)++;
}
/* bb_process_escape_sequence can handle nul correctly */
c = bb_process_escape_sequence((const char **) argv);
} }
} }
putchar(c); putchar(c);
} }
argc--;
argv++;
if (argc > 0)
putchar(' ');
}
if (!nflag)
putchar('\n');
fflush(stdout);
return EXIT_SUCCESS; if (*++argv) {
putchar(' ');
}
}
#ifdef CONFIG_FEATURE_FANCY_ECHO
if (nflag) {
putchar('\n');
}
#else
putchar('\n');
#endif
DONE:
bb_fflush_stdout_and_exit(EXIT_SUCCESS);
} }
/*- /*-

View File

@ -24,50 +24,66 @@
* Modified for BusyBox by Erik Andersen <andersen@lineo.com>, <andersee@debian.org> * Modified for BusyBox by Erik Andersen <andersen@lineo.com>, <andersee@debian.org>
*/ */
/* BB_AUDIT SUSv3 compliant */
/* http://www.opengroup.org/onlinepubs/007904975/utilities/env.html */
/* Mar 16, 2003 Manuel Novoa III (mjn3@codepoet.org)
*
* Fixed bug involving exit return codes if execvp fails. Also added
* output error checking.
*/
#include <stdio.h> #include <stdio.h>
#include <string.h> #include <string.h>
#include <getopt.h>
#include <stdlib.h> #include <stdlib.h>
#include <errno.h>
#include <unistd.h> #include <unistd.h>
#include "busybox.h" #include "busybox.h"
extern int env_main(int argc, char** argv) extern int env_main(int argc, char** argv)
{ {
char **ep, *p; char **ep, *p;
char *cleanenv[1]; char *cleanenv[1] = { NULL };
int ignore_environment = 0;
int ch; int ch;
while ((ch = getopt(argc, argv, "+iu:")) != -1) { while ((ch = getopt(argc, argv, "iu:")) > 0) {
switch(ch) { switch(ch) {
case 'i': case 'i':
ignore_environment = 1; environ = cleanenv;
break; break;
case 'u': case 'u':
unsetenv(optarg); unsetenv(optarg);
break; break;
default: default:
show_usage(); bb_show_usage();
} }
} }
if (optind != argc && !strcmp(argv[optind], "-")) {
ignore_environment = 1; argv += optind;
argv++;
} if (*argv && (argv[0][0] == '-') && !argv[0][1]) {
if (ignore_environment) {
environ = cleanenv; environ = cleanenv;
cleanenv[0] = NULL; ++argv;
} }
for (argv += optind; *argv && (p = strchr(*argv, '=')); ++argv)
if (putenv(*argv) < 0) while (*argv && ((p = strchr(*argv, '=')) != NULL)) {
perror_msg_and_die("%s", *argv); if (putenv(*argv) < 0) {
bb_perror_msg_and_die("putenv");
}
++argv;
}
if (*argv) { if (*argv) {
execvp(*argv, argv); execvp(*argv, argv);
perror_msg_and_die("%s", *argv); bb_perror_msg("%s", *argv); /* Avoid multibyte problems. */
return (errno == ENOENT) ? 127 : 126; /* SUSv3-mandated exit codes. */
} }
for (ep = environ; *ep; ep++)
for (ep = environ; *ep; ep++) {
puts(*ep); puts(*ep);
return 0; }
bb_fflush_stdout_and_exit(0);
} }
/* /*

View File

@ -78,14 +78,14 @@ int expr_main (int argc, char **argv)
VALUE *v; VALUE *v;
if (argc == 1) { if (argc == 1) {
error_msg_and_die("too few arguments"); bb_error_msg_and_die("too few arguments");
} }
args = argv + 1; args = argv + 1;
v = eval (); v = eval ();
if (*args) if (*args)
error_msg_and_die ("syntax error"); bb_error_msg_and_die ("syntax error");
if (v->type == integer) if (v->type == integer)
printf ("%d\n", v->u.i); printf ("%d\n", v->u.i);
@ -147,7 +147,7 @@ static int null (VALUE *v)
static void tostring (VALUE *v) static void tostring (VALUE *v)
{ {
if (v->type == integer) { if (v->type == integer) {
bb_asprintf (&(v->u.s), "%d", v->u.i); bb_xasprintf (&(v->u.s), "%d", v->u.i);
v->type = string; v->type = string;
} }
} }
@ -216,7 +216,7 @@ static \
int name (VALUE *l, VALUE *r) \ int name (VALUE *l, VALUE *r) \
{ \ { \
if (!toarith (l) || !toarith (r)) \ if (!toarith (l) || !toarith (r)) \
error_msg_and_die ("non-numeric argument"); \ bb_error_msg_and_die ("non-numeric argument"); \
return l->u.i op r->u.i; \ return l->u.i op r->u.i; \
} }
@ -224,9 +224,9 @@ int name (VALUE *l, VALUE *r) \
static int name (VALUE *l, VALUE *r) \ static int name (VALUE *l, VALUE *r) \
{ \ { \
if (!toarith (l) || !toarith (r)) \ if (!toarith (l) || !toarith (r)) \
error_msg_and_die ( "non-numeric argument"); \ bb_error_msg_and_die ( "non-numeric argument"); \
if (r->u.i == 0) \ if (r->u.i == 0) \
error_msg_and_die ( "division by zero"); \ bb_error_msg_and_die ( "division by zero"); \
return l->u.i op r->u.i; \ return l->u.i op r->u.i; \
} }
@ -270,7 +270,7 @@ of a basic regular expression is not portable; it is being ignored",
re_syntax_options = RE_SYNTAX_POSIX_BASIC; re_syntax_options = RE_SYNTAX_POSIX_BASIC;
errmsg = re_compile_pattern (pv->u.s, len, &re_buffer); errmsg = re_compile_pattern (pv->u.s, len, &re_buffer);
if (errmsg) { if (errmsg) {
error_msg_and_die("%s", errmsg); bb_error_msg_and_die("%s", errmsg);
} }
len = re_match (&re_buffer, sv->u.s, strlen (sv->u.s), 0, &re_regs); len = re_match (&re_buffer, sv->u.s, strlen (sv->u.s), 0, &re_regs);
@ -301,19 +301,19 @@ static VALUE *eval7 (void)
VALUE *v; VALUE *v;
if (!*args) if (!*args)
error_msg_and_die ( "syntax error"); bb_error_msg_and_die ( "syntax error");
if (nextarg ("(")) { if (nextarg ("(")) {
args++; args++;
v = eval (); v = eval ();
if (!nextarg (")")) if (!nextarg (")"))
error_msg_and_die ( "syntax error"); bb_error_msg_and_die ( "syntax error");
args++; args++;
return v; return v;
} }
if (nextarg (")")) if (nextarg (")"))
error_msg_and_die ( "syntax error"); bb_error_msg_and_die ( "syntax error");
return str_value (*args++); return str_value (*args++);
} }
@ -327,7 +327,7 @@ static VALUE *eval6 (void)
if (nextarg ("quote")) { if (nextarg ("quote")) {
args++; args++;
if (!*args) if (!*args)
error_msg_and_die ( "syntax error"); bb_error_msg_and_die ( "syntax error");
return str_value (*args++); return str_value (*args++);
} }
else if (nextarg ("length")) { else if (nextarg ("length")) {
@ -373,7 +373,7 @@ static VALUE *eval6 (void)
else { else {
v = xmalloc (sizeof(VALUE)); v = xmalloc (sizeof(VALUE));
v->type = string; v->type = string;
v->u.s = xstrndup(l->u.s + i1->u.i - 1, i2->u.i); v->u.s = bb_xstrndup(l->u.s + i1->u.i - 1, i2->u.i);
} }
freev (l); freev (l);
freev (i1); freev (i1);

View File

@ -21,7 +21,8 @@
* *
*/ */
/* getopt not needed */ /* BB_AUDIT SUSv3 compliant */
/* http://www.opengroup.org/onlinepubs/007904975/utilities/false.html */
#include <stdlib.h> #include <stdlib.h>
#include "busybox.h" #include "busybox.h"

View File

@ -1,9 +1,8 @@
/* vi: set sw=4 ts=4: */ /* vi: set sw=4 ts=4: */
/* /*
* Mini head implementation for busybox * head implementation for busybox
* *
* Copyright (C) 1999 by Lineo, inc. and John Beppu * Copyright (C) 2003 Manuel Novoa III <mjn3@codepoet.org>
* Copyright (C) 1999,2000,2001 by John Beppu <beppu@codepoet.org>
* *
* This program is free software; you can redistribute it and/or modify * This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
@ -21,82 +20,119 @@
* *
*/ */
/* BB_AUDIT SUSv3 compliant */
/* BB_AUDIT GNU compatible -c, -q, and -v options in 'fancy' configuration. */
/* http://www.opengroup.org/onlinepubs/007904975/utilities/head.html */
#include <stdio.h> #include <stdio.h>
#include <getopt.h>
#include <stdlib.h> #include <stdlib.h>
#include <string.h> #include <limits.h>
#include <ctype.h> #include <ctype.h>
#include <unistd.h>
#include "busybox.h" #include "busybox.h"
static int head(int len, FILE *fp) static const char head_opts[] =
{ "n:"
int i; #ifdef CONFIG_FEATURE_FANCY_HEAD
char *input; "c:qv"
#endif
;
for (i = 0; i < len; i++) { static const char header_fmt_str[] = "\n==> %s <==\n";
if ((input = get_line_from_file(fp)) == NULL)
break;
fputs(input, stdout);
free(input);
}
return 0;
}
/* BusyBoxed head(1) */
int head_main(int argc, char **argv) int head_main(int argc, char **argv)
{ {
unsigned long count = 10;
unsigned long i;
#ifdef CONFIG_FEATURE_FANCY_HEAD
int count_bytes = 0;
int header_threshhold = 1;
#endif
FILE *fp; FILE *fp;
int need_headers, opt, len = 10, status = EXIT_SUCCESS; const char *fmt;
char *p;
int opt;
int c;
int retval = EXIT_SUCCESS;
if (( argc >= 2 ) && ( argv [1][0] == '-' ) && isdigit ( argv [1][1] )) { /* Allow legacy syntax of an initial numeric option without -n. */
len = atoi ( &argv [1][1] ); if ((argc > 1) && (argv[1][0] == '-')
optind = 2; /* && (isdigit)(argv[1][1]) */
&& (((unsigned int)(argv[1][1] - '0')) <= 9)
) {
--argc;
++argv;
p = (*argv) + 1;
goto GET_COUNT;
} }
/* parse argv[] */ while ((opt = getopt(argc, argv, head_opts)) > 0) {
while ((opt = getopt(argc, argv, "n:")) > 0) { switch(opt) {
switch (opt) { #ifdef CONFIG_FEATURE_FANCY_HEAD
case 'n': case 'q':
len = atoi(optarg); header_threshhold = INT_MAX;
if (len >= 0)
break; break;
/* fallthrough */ case 'v':
default: header_threshhold = -1;
show_usage(); break;
case 'c':
count_bytes = 1;
/* fall through */
#endif
case 'n':
p = optarg;
GET_COUNT:
count = bb_xgetularg10(p);
break;
default:
bb_show_usage();
} }
} }
/* get rest of argv[] or stdin if nothing's left */ argv += optind;
if (argv[optind] == NULL) { if (!*argv) {
head(len, stdin); *--argv = "-";
return status;
}
need_headers = optind != (argc - 1);
while (argv[optind]) {
if (strcmp(argv[optind], "-") == 0) {
fp = stdin;
argv[optind] = "standard input";
} else {
if ((fp = wfopen(argv[optind], "r")) == NULL)
status = EXIT_FAILURE;
}
if (fp) {
if (need_headers) {
printf("==> %s <==\n", argv[optind]);
}
head(len, fp);
if (ferror(fp)) {
perror_msg("%s", argv[optind]);
status = EXIT_FAILURE;
}
if (optind < argc - 1)
putchar('\n');
if (fp != stdin)
fclose(fp);
}
optind++;
} }
return status; fmt = header_fmt_str + 1;
#ifdef CONFIG_FEATURE_FANCY_HEAD
if (argc - optind <= header_threshhold) {
header_threshhold = 0;
}
#else
if (argc <= optind + 1) {
fmt += 11;
}
/* Now define some things here to avoid #ifdefs in the code below.
* These should optimize out of the if conditions below. */
#define header_threshhold 1
#define count_bytes 0
#endif
do {
if ((fp = bb_wfopen_input(*argv)) != NULL) {
if (fp == stdin) {
*argv = (char *) bb_msg_standard_input;
}
if (header_threshhold) {
bb_printf(fmt, *argv);
}
i = count;
while (i && ((c = getc(fp)) != EOF)) {
if (count_bytes || (c == '\n')) {
--i;
}
putchar(c);
}
if (bb_fclose_nonstdin(fp)) {
bb_perror_msg("%s", *argv); /* Avoid multibyte problems. */
retval = EXIT_FAILURE;
}
bb_xferror_stdout();
}
fmt = header_fmt_str;
} while (*++argv);
bb_fflush_stdout_and_exit(retval);
} }

View File

@ -20,13 +20,19 @@
* *
*/ */
#include <stdio.h> /* BB_AUDIT SUSv3 N/A -- Matches GNU behavior. */
#include <stdlib.h> #include <stdlib.h>
#include <unistd.h> #include <unistd.h>
#include "busybox.h" #include "busybox.h"
extern int hostid_main(int argc, char **argv) extern int hostid_main(int argc, char **argv)
{ {
printf("%lx\n", gethostid()); if (argc > 1) {
return EXIT_SUCCESS; bb_show_usage();
}
bb_printf("%lx\n", gethostid());
bb_fflush_stdout_and_exit(EXIT_SUCCESS);
} }

View File

@ -20,6 +20,8 @@
* *
*/ */
/* BB_AUDIT SUSv3 _NOT_ compliant -- option -G is not currently supported. */
#include "busybox.h" #include "busybox.h"
#include <stdio.h> #include <stdio.h>
#include <unistd.h> #include <unistd.h>
@ -27,70 +29,58 @@
#include <string.h> #include <string.h>
#include <sys/types.h> #include <sys/types.h>
#define NO_GROUP 1
#define NO_USER 2
#define PRINT_REAL 4
#define NAME_NOT_NUMBER 8
extern int id_main(int argc, char **argv) extern int id_main(int argc, char **argv)
{ {
int no_user = 0, no_group = 0, print_real = 0;
int name_not_number = 0;
char user[9], group[9]; char user[9], group[9];
long gid;
long pwnam, grnam; long pwnam, grnam;
int opt; int uid, gid;
int flags;
gid = 0; flags = bb_getopt_ulflags(argc, argv, "ugrn");
while ((opt = getopt(argc, argv, "ugrn")) > 0) { if (((flags & (NO_USER | NO_GROUP)) == (NO_USER | NO_GROUP))
switch (opt) { || (argc > optind + 1)
case 'u': ) {
no_group++; bb_show_usage();
break;
case 'g':
no_user++;
break;
case 'r':
print_real++;
break;
case 'n':
name_not_number++;
break;
default:
show_usage();
}
} }
if (no_user && no_group) show_usage();
if (argv[optind] == NULL) { if (argv[optind] == NULL) {
if (print_real) { if (flags & PRINT_REAL) {
my_getpwuid(user, getuid()); uid = getuid();
my_getgrgid(group, getgid()); gid = getgid();
} else { } else {
my_getpwuid(user, geteuid()); uid = geteuid();
my_getgrgid(group, getegid()); gid = getegid();
} }
my_getpwuid(user, uid);
} else { } else {
safe_strncpy(user, argv[optind], sizeof(user)); safe_strncpy(user, argv[optind], sizeof(user));
gid = my_getpwnamegid(user); gid = my_getpwnamegid(user);
my_getgrgid(group, gid);
} }
my_getgrgid(group, gid);
pwnam=my_getpwnam(user); pwnam=my_getpwnam(user);
grnam=my_getgrnam(group); grnam=my_getgrnam(group);
if (no_group) { if (flags & (NO_GROUP | NO_USER)) {
if(name_not_number) char *s = group;
puts(user); if (flags & NO_GROUP) {
else s = user;
printf("%ld\n", pwnam); grnam = pwnam;
} else if (no_user) { }
if(name_not_number) if (flags & NAME_NOT_NUMBER) {
puts(group); puts(s);
else } else {
printf("%ld\n", grnam); printf("%ld\n", grnam);
}
} else { } else {
printf("uid=%ld(%s) gid=%ld(%s)\n", pwnam, user, grnam, group); printf("uid=%ld(%s) gid=%ld(%s)\n", pwnam, user, grnam, group);
} }
return(0);
bb_fflush_stdout_and_exit(0);
} }
/* END CODE */

View File

@ -1,4 +1,7 @@
/* vi: set sw=4 ts=4: */ /* vi: set sw=4 ts=4: */
/* BB_AUDIT SUSv3 N/A -- Apparently a busybox (obsolete?) extension. */
#include <stdlib.h> #include <stdlib.h>
#include <string.h> #include <string.h>
#include <stdio.h> #include <stdio.h>
@ -6,8 +9,11 @@
extern int length_main(int argc, char **argv) extern int length_main(int argc, char **argv)
{ {
if (argc != 2 || **(argv + 1) == '-') if ((argc != 2) || (**(++argv) == '-')) {
show_usage(); bb_show_usage();
printf("%lu\n", (long)strlen(argv[1])); }
return EXIT_SUCCESS;
bb_printf("%lu\n", (unsigned long)strlen(*argv));
bb_fflush_stdout_and_exit(EXIT_SUCCESS);
} }

View File

@ -0,0 +1,30 @@
# Makefile for busybox
#
# Copyright (C) 1999-2002 Erik Andersen <andersee@debian.org>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
TOPDIR:= ../../
LIBCOREUTILS_DIR:=./
include $(TOPDIR).config
include $(TOPDIR)Rules.mak
include Makefile.in
all: $(libraries-y)
-include $(TOPDIR).depend
clean:
rm -f *.o *.a $(AR_TARGET)

View File

@ -0,0 +1,32 @@
# Makefile for busybox
#
# Copyright (C) 1999-2002 Erik Andersen <andersee@debian.org>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
LIBCOREUTILS_AR:=libcoreutils.a
ifndef $(LIBCOREUTILS_DIR)
LIBCOREUTILS_DIR:=$(TOPDIR)coreutils/libcoreutils/
endif
LIBCOREUTILS_SRC:= cp_mv_stat.c getopt_mk_fifo_nod.c xgetoptfile_sort_uniq.c
LIBCOREUTILS_OBJS=$(patsubst %.c,$(LIBCOREUTILS_DIR)%.o, $(LIBCOREUTILS_SRC))
libraries-y+=$(LIBCOREUTILS_DIR)$(LIBCOREUTILS_AR)
$(LIBCOREUTILS_DIR)$(LIBCOREUTILS_AR): $(LIBCOREUTILS_OBJS)
$(AR) -ro $@ $(LIBCOREUTILS_OBJS)

View File

@ -0,0 +1,12 @@
#ifndef COREUTILS_H
#define COREUTILS_H 1
typedef int (*stat_func)(const char *fn, struct stat *ps);
extern int cp_mv_stat2(const char *fn, struct stat *fn_stat, stat_func sf);
extern int cp_mv_stat(const char *fn, struct stat *fn_stat);
extern mode_t getopt_mk_fifo_nod(int argc, char **argv);
extern FILE *xgetoptfile_sort_uniq(char **argv, const char *mode);
#endif

View File

@ -0,0 +1,45 @@
/* vi: set sw=4 ts=4: */
/*
* coreutils utility routine
*
* Copyright (C) 2003 Manuel Novoa III <mjn3@codepoet.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
#include <errno.h>
#include <sys/stat.h>
#include "libbb.h"
#include "coreutils.h"
extern int cp_mv_stat2(const char *fn, struct stat *fn_stat, stat_func sf)
{
if (sf(fn, fn_stat) < 0) {
if (errno != ENOENT) {
bb_perror_msg("unable to stat `%s'", fn);
return -1;
}
return 0;
} else if (S_ISDIR(fn_stat->st_mode)) {
return 3;
}
return 1;
}
extern int cp_mv_stat(const char *fn, struct stat *fn_stat)
{
return cp_mv_stat2(fn, fn_stat, stat);
}

View File

@ -0,0 +1,45 @@
/* vi: set sw=4 ts=4: */
/*
* coreutils utility routine
*
* Copyright (C) 2003 Manuel Novoa III <mjn3@codepoet.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include "libbb.h"
#include "coreutils.h"
extern mode_t getopt_mk_fifo_nod(int argc, char **argv)
{
mode_t mode = 0666;
int opt;
while ((opt = getopt(argc, argv, "m:")) > 0) {
if (opt == 'm') {
mode = 0666;
if (bb_parse_mode(optarg, &mode)) {
umask(0);
continue;
}
}
bb_show_usage();
}
return mode;
}

View File

@ -0,0 +1,38 @@
/* vi: set sw=4 ts=4: */
/*
* coreutils utility routine
*
* Copyright (C) 2003 Manuel Novoa III <mjn3@codepoet.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
#include <stdio.h>
#include <unistd.h>
#include "libbb.h"
#include "coreutils.h"
extern FILE *xgetoptfile_sort_uniq(char **argv, const char *mode)
{
const char *n;
if ((n = *argv) != NULL) {
if ((*n != '-') || n[1]) {
return bb_xfopen(n, mode);
}
}
return (*mode == 'r') ? stdin : stdout;
}

View File

@ -21,113 +21,86 @@
* *
*/ */
#include <stdio.h> /* BB_AUDIT SUSv3 compliant */
#include <dirent.h> /* BB_AUDIT GNU options missing: -b, -d, -F, -i, -S, and -v. */
#include <string.h> /* http://www.opengroup.org/onlinepubs/007904975/utilities/ln.html */
/* Mar 16, 2003 Manuel Novoa III (mjn3@codepoet.org)
*
* Fixed bug involving -n option. Essentially, -n was always in effect.
*/
#include <stdlib.h> #include <stdlib.h>
#include <errno.h>
#include <unistd.h> #include <unistd.h>
#include "busybox.h" #include "busybox.h"
#define LN_SYMLINK 1
static const int LN_SYMLINK = 1; #define LN_FORCE 2
static const int LN_FORCE = 2; #define LN_NODEREFERENCE 4
static const int LN_NODEREFERENCE = 4;
/*
* linkDestName is where the link points to,
* linkSrcName is the name of the link to be created.
*/
static int fs_link(const char *link_destname, const char *link_srcname,
const int flag)
{
int status;
int src_is_dir;
char *src_name = 0;
const char *src;
if (link_destname==NULL)
return(FALSE);
if (link_srcname==NULL)
src = link_destname;
else
src = link_srcname;
if (flag&LN_NODEREFERENCE)
src_is_dir = is_directory(src, TRUE, NULL);
else
src_is_dir = is_directory(src, FALSE, NULL);
if ((src_is_dir==TRUE)&&((flag&LN_NODEREFERENCE)==0)) {
char* srcdir_name;
srcdir_name = xstrdup(link_destname);
src_name = concat_path_file(src, get_last_path_component(srcdir_name));
src = src_name;
free(srcdir_name);
}
if (flag&LN_FORCE)
unlink(src);
if (flag&LN_SYMLINK)
status = symlink(link_destname, src);
else
status = link(link_destname, src);
if (status != 0) {
perror_msg(src);
status = FALSE;
} else {
status = TRUE;
}
free(src_name);
return status;
}
extern int ln_main(int argc, char **argv) extern int ln_main(int argc, char **argv)
{ {
int status = EXIT_SUCCESS; int status = EXIT_SUCCESS;
int flag = 0; int flag;
int opt; char *last;
char *src_name;
/* Parse any options */ const char *src;
while ((opt=getopt(argc, argv, "sfn")) != -1) { int (*link_func)(const char *, const char *);
switch(opt) {
case 's': flag = bb_getopt_ulflags(argc, argv, "sfn");
flag |= LN_SYMLINK;
break; if (argc == optind) {
case 'f': bb_show_usage();
flag |= LN_FORCE; }
break;
case 'n': last = argv[argc - 1];
flag |= LN_NODEREFERENCE; argv += optind;
break;
default: if (argc == optind + 1) {
show_usage(); *--argv = last;
last = bb_get_last_path_component(bb_xstrdup(last));
}
do {
src_name = 0;
src = last;
if (is_directory(src,
(flag & LN_NODEREFERENCE) ^ LN_NODEREFERENCE,
NULL)) {
src_name = bb_xstrdup(*argv);
src = concat_path_file(src, bb_get_last_path_component(src_name));
free(src_name);
src_name = (char *)src;
} }
}
if (optind > (argc-1)) { if (flag & LN_FORCE) {
show_usage(); unlink(src);
} }
if (optind == (argc-1)) {
if (fs_link(argv[optind], link_func = link;
get_last_path_component(argv[optind]), flag)==FALSE) if (flag & LN_SYMLINK) {
status = EXIT_FAILURE; link_func = symlink;
} }
while(optind<(argc-1)) {
if (fs_link(argv[optind], argv[argc-1], flag)==FALSE) if (link_func(*argv, src) != 0) {
status = EXIT_FAILURE; bb_perror_msg(src);
optind++; status = EXIT_FAILURE;;
} }
free(src_name);
} while ((++argv)[1]);
return status; return status;
} }
/*
Local Variables:
c-file-style: "linux"
c-basic-offset: 4
tab-width: 4
End:
*/

View File

@ -20,6 +20,19 @@
* *
*/ */
/* BB_AUDIT SUSv3 compliant */
/* http://www.opengroup.org/onlinepubs/007904975/utilities/logname.html */
/* Mar 16, 2003 Manuel Novoa III (mjn3@codepoet.org)
*
* SUSv3 specifies the string used is that returned from getlogin().
* The previous implementation used getpwuid() for geteuid(), which
* is _not_ the same. Erik apparently made this change almost 3 years
* ago to avoid failing when no utmp was available. However, the
* correct course of action wrt SUSv3 for a failing getlogin() is
* a dianostic message and an error return.
*/
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <unistd.h> #include <unistd.h>
@ -27,14 +40,16 @@
extern int logname_main(int argc, char **argv) extern int logname_main(int argc, char **argv)
{ {
char user[9]; const char *p;
if (argc > 1) if (argc > 1) {
show_usage(); bb_show_usage();
if (my_getpwuid(user, geteuid())) {
puts(user);
return EXIT_SUCCESS;
} }
error_msg_and_die("no login name");
if ((p = getlogin()) != NULL) {
puts(p);
bb_fflush_stdout_and_exit(EXIT_SUCCESS);
}
bb_perror_msg_and_die("getlogin");
} }

View File

@ -73,58 +73,76 @@ enum {
#endif #endif
/* what is the overall style of the listing */ /* what is the overall style of the listing */
enum { #define STYLE_AUTO (0)
STYLE_AUTO = 0, #define STYLE_COLUMNS (1U<<21) /* fill columns */
STYLE_LONG = 1, /* one record per line, extended info */ #define STYLE_LONG (2U<<21) /* one record per line, extended info */
STYLE_SINGLE = 2, /* one record per line */ #define STYLE_SINGLE (3U<<21) /* one record per line */
STYLE_COLUMNS = 3 /* fill columns */
}; #define STYLE_MASK STYLE_SINGLE
#define STYLE_ONE_RECORD_FLAG STYLE_LONG
/* 51306 lrwxrwxrwx 1 root root 2 May 11 01:43 /bin/view -> vi* */ /* 51306 lrwxrwxrwx 1 root root 2 May 11 01:43 /bin/view -> vi* */
/* what file information will be listed */ /* what file information will be listed */
#define LIST_INO (1<<0) #define LIST_INO (1U<<0)
#define LIST_BLOCKS (1<<1) #define LIST_BLOCKS (1U<<1)
#define LIST_MODEBITS (1<<2) #define LIST_MODEBITS (1U<<2)
#define LIST_NLINKS (1<<3) #define LIST_NLINKS (1U<<3)
#define LIST_ID_NAME (1<<4) #define LIST_ID_NAME (1U<<4)
#define LIST_ID_NUMERIC (1<<5) #define LIST_ID_NUMERIC (1U<<5)
#define LIST_SIZE (1<<6) #define LIST_SIZE (1U<<6)
#define LIST_DEV (1<<7) #define LIST_DEV (1U<<7)
#define LIST_DATE_TIME (1<<8) #define LIST_DATE_TIME (1U<<8)
#define LIST_FULLTIME (1<<9) #define LIST_FULLTIME (1U<<9)
#define LIST_FILENAME (1<<10) #define LIST_FILENAME (1U<<10)
#define LIST_SYMLINK (1<<11) #define LIST_SYMLINK (1U<<11)
#define LIST_FILETYPE (1<<12) #define LIST_FILETYPE (1U<<12)
#define LIST_EXEC (1<<13) #define LIST_EXEC (1U<<13)
#define LIST_MASK ((LIST_EXEC << 1) - 1)
/* what files will be displayed */ /* what files will be displayed */
#define DISP_NORMAL (0) /* show normal filenames */ /* TODO -- We may be able to make DISP_NORMAL 0 to save a bit slot. */
#define DISP_DIRNAME (1<<0) /* 2 or more items? label directories */ #define DISP_NORMAL (1U<<14) /* show normal filenames */
#define DISP_HIDDEN (1<<1) /* show filenames starting with . */ #define DISP_DIRNAME (1U<<15) /* 2 or more items? label directories */
#define DISP_DOT (1<<2) /* show . and .. */ #define DISP_HIDDEN (1U<<16) /* show filenames starting with . */
#define DISP_NOLIST (1<<3) /* show directory as itself, not contents */ #define DISP_DOT (1U<<17) /* show . and .. */
#define DISP_RECURSIVE (1<<4) /* show directory and everything below it */ #define DISP_NOLIST (1U<<18) /* show directory as itself, not contents */
#define DISP_ROWS (1<<5) /* print across rows */ #define DISP_RECURSIVE (1U<<19) /* show directory and everything below it */
#define DISP_ROWS (1U<<20) /* print across rows */
#define DISP_MASK (((DISP_ROWS << 1) - 1) & ~(DISP_NORMAL - 1))
#ifdef CONFIG_FEATURE_LS_SORTFILES #ifdef CONFIG_FEATURE_LS_SORTFILES
/* how will the files be sorted */ /* how will the files be sorted */
static const int SORT_FORWARD = 0; /* sort in reverse order */ #define SORT_ORDER_FORWARD 0 /* sort in reverse order */
static const int SORT_REVERSE = 1; /* sort in reverse order */ #define SORT_ORDER_REVERSE (1U<<27) /* sort in reverse order */
static const int SORT_NAME = 2; /* sort by file name */
static const int SORT_SIZE = 3; /* sort by file size */ #define SORT_NAME 0 /* sort by file name */
static const int SORT_ATIME = 4; /* sort by last access time */ #define SORT_SIZE (1U<<28) /* sort by file size */
static const int SORT_CTIME = 5; /* sort by last change time */ #define SORT_ATIME (2U<<28) /* sort by last access time */
static const int SORT_MTIME = 6; /* sort by last modification time */ #define SORT_CTIME (3U<<28) /* sort by last change time */
static const int SORT_VERSION = 7; /* sort by version */ #define SORT_MTIME (4U<<28) /* sort by last modification time */
static const int SORT_EXT = 8; /* sort by file name extension */ #define SORT_VERSION (5U<<28) /* sort by version */
static const int SORT_DIR = 9; /* sort by file or directory */ #define SORT_EXT (6U<<28) /* sort by file name extension */
#define SORT_DIR (7U<<28) /* sort by file or directory */
#define SORT_MASK (7U<<28)
#endif #endif
#ifdef CONFIG_FEATURE_LS_TIMESTAMPS #ifdef CONFIG_FEATURE_LS_TIMESTAMPS
/* which of the three times will be used */ /* which of the three times will be used */
static const int TIME_MOD = 0; #define TIME_MOD 0
static const int TIME_CHANGE = 1; #define TIME_CHANGE (1U<<23)
static const int TIME_ACCESS = 2; #define TIME_ACCESS (1U<<24)
#define TIME_MASK (3U<<23)
#endif
#ifdef CONFIG_FEATURE_LS_FOLLOWLINKS
#define FOLLOW_LINKS (1U<<25)
#endif
#ifdef CONFIG_FEATURE_HUMAN_READABLE
#define LS_DISP_HR (1U<<26)
#endif #endif
#define LIST_SHORT (LIST_FILENAME) #define LIST_SHORT (LIST_FILENAME)
@ -133,9 +151,9 @@ static const int TIME_ACCESS = 2;
LIST_DATE_TIME | LIST_FILENAME | LIST_SYMLINK) LIST_DATE_TIME | LIST_FILENAME | LIST_SYMLINK)
#define LIST_ILONG (LIST_INO | LIST_LONG) #define LIST_ILONG (LIST_INO | LIST_LONG)
static const int SPLIT_DIR = 0; #define SPLIT_DIR 1
static const int SPLIT_FILE = 1; #define SPLIT_FILE 0
static const int SPLIT_SUBDIR = 2; #define SPLIT_SUBDIR 2
#define TYPEINDEX(mode) (((mode) >> 12) & 0x0f) #define TYPEINDEX(mode) (((mode) >> 12) & 0x0f)
#define TYPECHAR(mode) ("0pcCd?bB-?l?s???" [TYPEINDEX(mode)]) #define TYPECHAR(mode) ("0pcCd?bB-?l?s???" [TYPEINDEX(mode)])
@ -169,20 +187,7 @@ static struct dnode **list_dir(const char *);
static struct dnode **dnalloc(int); static struct dnode **dnalloc(int);
static int list_single(struct dnode *); static int list_single(struct dnode *);
static unsigned int disp_opts; static unsigned int all_fmt;
static unsigned int style_fmt;
static unsigned int list_fmt;
#ifdef CONFIG_FEATURE_LS_SORTFILES
static unsigned int sort_opts;
static unsigned int sort_order;
#endif
#ifdef CONFIG_FEATURE_LS_TIMESTAMPS
static unsigned int time_fmt;
#endif
#ifdef CONFIG_FEATURE_LS_FOLLOWLINKS
static unsigned int follow_links = FALSE;
#endif
#ifdef CONFIG_FEATURE_AUTOWIDTH #ifdef CONFIG_FEATURE_AUTOWIDTH
static unsigned short terminal_width = TERMINAL_WIDTH; static unsigned short terminal_width = TERMINAL_WIDTH;
@ -194,26 +199,22 @@ static unsigned short tabstops = COLUMN_GAP;
static int status = EXIT_SUCCESS; static int status = EXIT_SUCCESS;
#ifdef CONFIG_FEATURE_HUMAN_READABLE
static unsigned long ls_disp_hr = 0;
#endif
static struct dnode *my_stat(char *fullname, char *name) static struct dnode *my_stat(char *fullname, char *name)
{ {
struct stat dstat; struct stat dstat;
struct dnode *cur; struct dnode *cur;
#ifdef CONFIG_FEATURE_LS_FOLLOWLINKS #ifdef CONFIG_FEATURE_LS_FOLLOWLINKS
if (follow_links) { if (all_fmt & FOLLOW_LINKS) {
if (stat(fullname, &dstat)) { if (stat(fullname, &dstat)) {
perror_msg("%s", fullname); bb_perror_msg("%s", fullname);
status = EXIT_FAILURE; status = EXIT_FAILURE;
return 0; return 0;
} }
} else } else
#endif #endif
if (lstat(fullname, &dstat)) { if (lstat(fullname, &dstat)) {
perror_msg("%s", fullname); bb_perror_msg("%s", fullname);
status = EXIT_FAILURE; status = EXIT_FAILURE;
return 0; return 0;
} }
@ -253,9 +254,9 @@ static char bgcolor(mode_t mode)
#if defined(CONFIG_FEATURE_LS_FILETYPES) || defined(CONFIG_FEATURE_LS_COLOR) #if defined(CONFIG_FEATURE_LS_FILETYPES) || defined(CONFIG_FEATURE_LS_COLOR)
static char append_char(mode_t mode) static char append_char(mode_t mode)
{ {
if (!(list_fmt & LIST_FILETYPE)) if (!(all_fmt & LIST_FILETYPE))
return '\0'; return '\0';
if ((list_fmt & LIST_EXEC) && S_ISREG(mode) if ((all_fmt & LIST_EXEC) && S_ISREG(mode)
&& (mode & (S_IXUSR | S_IXGRP | S_IXOTH))) && (mode & (S_IXUSR | S_IXGRP | S_IXOTH)))
return '*'; return '*';
return APPCHAR(mode); return APPCHAR(mode);
@ -263,13 +264,11 @@ static char append_char(mode_t mode)
#endif #endif
/*----------------------------------------------------------------------*/ /*----------------------------------------------------------------------*/
static int is_subdir(struct dnode *dn)
{
return (S_ISDIR(dn->dstat.st_mode) && strcmp(dn->name, ".") != 0 &&
strcmp(dn->name, "..") != 0);
}
static int countdirs(struct dnode **dn, int nfiles) #define countdirs(A,B) count_dirs((A), (B), 1)
#define countsubdirs(A,B) count_dirs((A), (B), 0)
static int count_dirs(struct dnode **dn, int nfiles, int notsubdirs)
{ {
int i, dirs; int i, dirs;
@ -277,25 +276,17 @@ static int countdirs(struct dnode **dn, int nfiles)
return (0); return (0);
dirs = 0; dirs = 0;
for (i = 0; i < nfiles; i++) { for (i = 0; i < nfiles; i++) {
if (S_ISDIR(dn[i]->dstat.st_mode)) if (S_ISDIR(dn[i]->dstat.st_mode)
&& (notsubdirs
|| ((dn[i]->name[0] != '.')
|| (dn[i]->name[1]
&& ((dn[i]->name[1] != '.')
|| dn[i]->name[2])))))
dirs++; dirs++;
} }
return (dirs); return (dirs);
} }
static int countsubdirs(struct dnode **dn, int nfiles)
{
int i, subdirs;
if (dn == NULL || nfiles < 1)
return 0;
subdirs = 0;
for (i = 0; i < nfiles; i++)
if (is_subdir(dn[i]))
subdirs++;
return subdirs;
}
static int countfiles(struct dnode **dnp) static int countfiles(struct dnode **dnp)
{ {
int nfiles; int nfiles;
@ -364,18 +355,18 @@ static struct dnode **splitdnarray(struct dnode **dn, int nfiles, int which)
/* copy the entrys into the file or dir array */ /* copy the entrys into the file or dir array */
for (d = i = 0; i < nfiles; i++) { for (d = i = 0; i < nfiles; i++) {
if (which == SPLIT_DIR) { if (S_ISDIR(dn[i]->dstat.st_mode)) {
if (S_ISDIR(dn[i]->dstat.st_mode)) { if (which & (SPLIT_DIR|SPLIT_SUBDIR)) {
dnp[d++] = dn[i]; if ((which & SPLIT_DIR)
} /* else skip the file */ || ((dn[i]->name[0] != '.')
} else if (which == SPLIT_SUBDIR) { || (dn[i]->name[1]
if (is_subdir(dn[i])) { && ((dn[i]->name[1] != '.')
dnp[d++] = dn[i]; || dn[i]->name[2])))) {
} /* else skip the file or dir */ dnp[d++] = dn[i];
} else { }
if (!(S_ISDIR(dn[i]->dstat.st_mode))) { }
dnp[d++] = dn[i]; } else if (!(which & (SPLIT_DIR|SPLIT_SUBDIR))) {
} /* else skip the dir */ dnp[d++] = dn[i];
} }
} }
return (dnp); return (dnp);
@ -385,29 +376,24 @@ static struct dnode **splitdnarray(struct dnode **dn, int nfiles, int which)
#ifdef CONFIG_FEATURE_LS_SORTFILES #ifdef CONFIG_FEATURE_LS_SORTFILES
static int sortcmp(struct dnode *d1, struct dnode *d2) static int sortcmp(struct dnode *d1, struct dnode *d2)
{ {
int cmp, dif; unsigned int sort_opts = all_fmt & SORT_MASK;
int dif;
cmp = 0; dif = 0; /* assume SORT_NAME */
if (sort_opts == SORT_SIZE) { if (sort_opts == SORT_SIZE) {
dif = (int) (d1->dstat.st_size - d2->dstat.st_size); dif = (int) (d2->dstat.st_size - d1->dstat.st_size);
} else if (sort_opts == SORT_ATIME) { } else if (sort_opts == SORT_ATIME) {
dif = (int) (d1->dstat.st_atime - d2->dstat.st_atime); dif = (int) (d2->dstat.st_atime - d1->dstat.st_atime);
} else if (sort_opts == SORT_CTIME) { } else if (sort_opts == SORT_CTIME) {
dif = (int) (d1->dstat.st_ctime - d2->dstat.st_ctime); dif = (int) (d2->dstat.st_ctime - d1->dstat.st_ctime);
} else if (sort_opts == SORT_MTIME) { } else if (sort_opts == SORT_MTIME) {
dif = (int) (d1->dstat.st_mtime - d2->dstat.st_mtime); dif = (int) (d2->dstat.st_mtime - d1->dstat.st_mtime);
} else if (sort_opts == SORT_DIR) { } else if (sort_opts == SORT_DIR) {
dif = S_ISDIR(d1->dstat.st_mode) - S_ISDIR(d2->dstat.st_mode); dif = S_ISDIR(d2->dstat.st_mode) - S_ISDIR(d1->dstat.st_mode);
/* } else if (sort_opts == SORT_VERSION) { */ /* } else if (sort_opts == SORT_VERSION) { */
/* } else if (sort_opts == SORT_EXT) { */ /* } else if (sort_opts == SORT_EXT) { */
} else { /* assume SORT_NAME */
dif = 0;
} }
if (dif > 0)
cmp = -1;
if (dif < 0)
cmp = 1;
if (dif == 0) { if (dif == 0) {
/* sort by name- may be a tie_breaker for time or size cmp */ /* sort by name- may be a tie_breaker for time or size cmp */
#ifdef CONFIG_LOCALE_SUPPORT #ifdef CONFIG_LOCALE_SUPPORT
@ -415,16 +401,12 @@ static int sortcmp(struct dnode *d1, struct dnode *d2)
#else #else
dif = strcmp(d1->name, d2->name); dif = strcmp(d1->name, d2->name);
#endif #endif
if (dif > 0)
cmp = 1;
if (dif < 0)
cmp = -1;
} }
if (sort_order == SORT_REVERSE) { if (all_fmt & SORT_ORDER_REVERSE) {
cmp = -1 * cmp; dif = -dif;
} }
return (cmp); return (dif);
} }
/*----------------------------------------------------------------------*/ /*----------------------------------------------------------------------*/
@ -463,20 +445,17 @@ static void showfiles(struct dnode **dn, int nfiles)
if (dn == NULL || nfiles < 1) if (dn == NULL || nfiles < 1)
return; return;
switch (style_fmt) { if (all_fmt & STYLE_ONE_RECORD_FLAG) {
case STYLE_LONG: /* one record per line, extended info */
case STYLE_SINGLE: /* one record per line */
ncols = 1; ncols = 1;
break; } else {
default: /* find the longest file name- use that as the column width */
/* find the longest file name- use that as the column width */ for (i = 0; i < nfiles; i++) {
for (i = 0; i < nfiles; i++) {
int len = strlen(dn[i]->name) + int len = strlen(dn[i]->name) +
((list_fmt & LIST_INO) ? 8 : 0) + ((all_fmt & LIST_INO) ? 8 : 0) +
((list_fmt & LIST_BLOCKS) ? 5 : 0); ((all_fmt & LIST_BLOCKS) ? 5 : 0);
if (column_width < len) if (column_width < len)
column_width = len; column_width = len;
} }
column_width += tabstops; column_width += tabstops;
ncols = (int) (terminal_width / column_width); ncols = (int) (terminal_width / column_width);
} }
@ -494,7 +473,7 @@ static void showfiles(struct dnode **dn, int nfiles)
for (nc = 0; nc < ncols; nc++) { for (nc = 0; nc < ncols; nc++) {
/* reach into the array based on the column and row */ /* reach into the array based on the column and row */
i = (nc * nrows) + row; /* assume display by column */ i = (nc * nrows) + row; /* assume display by column */
if (disp_opts & DISP_ROWS) if (all_fmt & DISP_ROWS)
i = (row * ncols) + nc; /* display across row */ i = (row * ncols) + nc; /* display across row */
if (i < nfiles) { if (i < nfiles) {
if (column > 0) { if (column > 0) {
@ -528,7 +507,7 @@ static void showdirs(struct dnode **dn, int ndirs)
return; return;
for (i = 0; i < ndirs; i++) { for (i = 0; i < ndirs; i++) {
if (disp_opts & (DISP_DIRNAME | DISP_RECURSIVE)) { if (all_fmt & (DISP_DIRNAME | DISP_RECURSIVE)) {
printf("\n%s:\n", dn[i]->fullname); printf("\n%s:\n", dn[i]->fullname);
} }
subdnp = list_dir(dn[i]->fullname); subdnp = list_dir(dn[i]->fullname);
@ -540,7 +519,7 @@ static void showdirs(struct dnode **dn, int ndirs)
#endif #endif
showfiles(subdnp, nfiles); showfiles(subdnp, nfiles);
#ifdef CONFIG_FEATURE_LS_RECURSIVE #ifdef CONFIG_FEATURE_LS_RECURSIVE
if (disp_opts & DISP_RECURSIVE) { if (all_fmt & DISP_RECURSIVE) {
/* recursive- list the sub-dirs */ /* recursive- list the sub-dirs */
dnd = splitdnarray(subdnp, nfiles, SPLIT_SUBDIR); dnd = splitdnarray(subdnp, nfiles, SPLIT_SUBDIR);
dndirs = countsubdirs(subdnp, nfiles); dndirs = countsubdirs(subdnp, nfiles);
@ -573,7 +552,7 @@ static struct dnode **list_dir(const char *path)
nfiles = 0; nfiles = 0;
dir = opendir(path); dir = opendir(path);
if (dir == NULL) { if (dir == NULL) {
perror_msg("%s", path); bb_perror_msg("%s", path);
status = EXIT_FAILURE; status = EXIT_FAILURE;
return (NULL); /* could not open the dir */ return (NULL); /* could not open the dir */
} }
@ -585,9 +564,9 @@ static struct dnode **list_dir(const char *path)
if ((entry->d_name[1] == 0 || ( if ((entry->d_name[1] == 0 || (
entry->d_name[1] == '.' entry->d_name[1] == '.'
&& entry->d_name[2] == 0)) && entry->d_name[2] == 0))
&& !(disp_opts & DISP_DOT)) && !(all_fmt & DISP_DOT))
continue; continue;
if (!(disp_opts & DISP_HIDDEN)) if (!(all_fmt & DISP_HIDDEN))
continue; continue;
} }
fullname = concat_path_file(path, entry->d_name); fullname = concat_path_file(path, entry->d_name);
@ -636,9 +615,9 @@ static int list_single(struct dnode *dn)
#ifdef CONFIG_FEATURE_LS_TIMESTAMPS #ifdef CONFIG_FEATURE_LS_TIMESTAMPS
ttime = dn->dstat.st_mtime; /* the default time */ ttime = dn->dstat.st_mtime; /* the default time */
if (time_fmt & TIME_ACCESS) if (all_fmt & TIME_ACCESS)
ttime = dn->dstat.st_atime; ttime = dn->dstat.st_atime;
if (time_fmt & TIME_CHANGE) if (all_fmt & TIME_CHANGE)
ttime = dn->dstat.st_ctime; ttime = dn->dstat.st_ctime;
filetime = ctime(&ttime); filetime = ctime(&ttime);
#endif #endif
@ -647,7 +626,7 @@ static int list_single(struct dnode *dn)
#endif #endif
for (i = 0; i <= 31; i++) { for (i = 0; i <= 31; i++) {
switch (list_fmt & (1 << i)) { switch (all_fmt & (1 << i)) {
case LIST_INO: case LIST_INO:
column += printf("%7ld ", (long int) dn->dstat.st_ino); column += printf("%7ld ", (long int) dn->dstat.st_ino);
break; break;
@ -659,7 +638,7 @@ static int list_single(struct dnode *dn)
#endif #endif
break; break;
case LIST_MODEBITS: case LIST_MODEBITS:
column += printf("%-10s ", (char *) mode_string(dn->dstat.st_mode)); column += printf("%-10s ", (char *) bb_mode_string(dn->dstat.st_mode));
break; break;
case LIST_NLINKS: case LIST_NLINKS:
column += printf("%4ld ", (long) dn->dstat.st_nlink); column += printf("%4ld ", (long) dn->dstat.st_nlink);
@ -683,7 +662,7 @@ static int list_single(struct dnode *dn)
(int) MINOR(dn->dstat.st_rdev)); (int) MINOR(dn->dstat.st_rdev));
} else { } else {
#ifdef CONFIG_FEATURE_HUMAN_READABLE #ifdef CONFIG_FEATURE_HUMAN_READABLE
if (ls_disp_hr == TRUE) { if (all_fmt & LS_DISP_HR) {
column += printf("%9s ", column += printf("%9s ",
make_human_readable_str(dn->dstat.st_size, 1, 0)); make_human_readable_str(dn->dstat.st_size, 1, 0));
} else } else
@ -700,7 +679,7 @@ static int list_single(struct dnode *dn)
#ifdef CONFIG_FEATURE_LS_TIMESTAMPS #ifdef CONFIG_FEATURE_LS_TIMESTAMPS
case LIST_FULLTIME: case LIST_FULLTIME:
case LIST_DATE_TIME: case LIST_DATE_TIME:
if (list_fmt & LIST_FULLTIME) { if (all_fmt & LIST_FULLTIME) {
printf("%24.24s ", filetime); printf("%24.24s ", filetime);
column += 25; column += 25;
break; break;
@ -774,6 +753,93 @@ static int list_single(struct dnode *dn)
} }
/*----------------------------------------------------------------------*/ /*----------------------------------------------------------------------*/
static const char ls_opts[] = "1AaCdgilnsx"
#ifdef CONFIG_FEATURE_LS_FILETYPES
"Fp"
#endif
#ifdef CONFIG_FEATURE_LS_RECURSIVE
"R"
#endif
#ifdef CONFIG_FEATURE_LS_SORTFILES
"rSvX"
#endif
#ifdef CONFIG_FEATURE_LS_TIMESTAMPS
"ecut"
#endif
#ifdef CONFIG_FEATURE_LS_FOLLOWLINKS
"L"
#endif
#ifdef CONFIG_FEATURE_HUMAN_READABLE
"h"
#endif
"k"
#ifdef CONFIG_FEATURE_AUTOWIDTH
"T:w:"
#endif
;
#define LIST_MASK_TRIGGER LIST_SHORT
#define STYLE_MASK_TRIGGER STYLE_MASK
#define SORT_MASK_TRIGGER SORT_MASK
#define DISP_MASK_TRIGGER DISP_ROWS
#define TIME_MASK_TRIGGER TIME_MASK
static const unsigned opt_flags[] = {
LIST_SHORT | STYLE_SINGLE, /* 1 */
DISP_HIDDEN, /* A */
DISP_HIDDEN | DISP_DOT, /* a */
LIST_SHORT | STYLE_COLUMNS, /* C */
DISP_NOLIST, /* d */
0, /* g - ingored */
LIST_INO, /* i */
LIST_LONG | STYLE_LONG, /* l - remember LS_DISP_HR in mask! */
LIST_ID_NUMERIC, /* n */
LIST_BLOCKS, /* s */
DISP_ROWS, /* x */
#ifdef CONFIG_FEATURE_LS_FILETYPES
LIST_FILETYPE | LIST_EXEC, /* F */
LIST_FILETYPE, /* p */
#endif
#ifdef CONFIG_FEATURE_LS_RECURSIVE
DISP_RECURSIVE, /* R */
#endif
#ifdef CONFIG_FEATURE_LS_SORTFILES
SORT_ORDER_REVERSE, /* r */
SORT_SIZE, /* S */
SORT_VERSION, /* v */
SORT_EXT, /* v */
#endif
#ifdef CONFIG_FEATURE_LS_TIMESTAMPS
LIST_FULLTIME, /* e */
#ifdef CONFIG_FEATURE_LS_SORTFILES
TIME_CHANGE | SORT_CTIME, /* c */
#else
TIME_CHANGE, /* c */
#endif
#ifdef CONFIG_FEATURE_LS_SORTFILES
TIME_ACCESS | SORT_ATIME, /* u */
#else
TIME_ACCESS, /* u */
#endif
#ifdef CONFIG_FEATURE_LS_SORTFILES
SORT_MTIME, /* t */
#else
0, /* t - ignored -- is this correct? */
#endif
#endif
#ifdef CONFIG_FEATURE_LS_FOLLOWLINKS
FOLLOW_LINKS, /* L */
#endif
#ifdef CONFIG_FEATURE_HUMAN_READABLE
LS_DISP_HR, /* h */
#endif
0, /* k - ingored */
};
/*----------------------------------------------------------------------*/
extern int ls_main(int argc, char **argv) extern int ls_main(int argc, char **argv)
{ {
struct dnode **dnf, **dnd; struct dnode **dnf, **dnd;
@ -788,16 +854,14 @@ extern int ls_main(int argc, char **argv)
struct winsize win = { 0, 0, 0, 0 }; struct winsize win = { 0, 0, 0, 0 };
#endif #endif
disp_opts = DISP_NORMAL; all_fmt = LIST_SHORT | DISP_NORMAL | STYLE_AUTO
style_fmt = STYLE_AUTO;
list_fmt = LIST_SHORT;
#ifdef CONFIG_FEATURE_LS_SORTFILES
sort_opts = SORT_NAME;
sort_order = SORT_FORWARD;
#endif
#ifdef CONFIG_FEATURE_LS_TIMESTAMPS #ifdef CONFIG_FEATURE_LS_TIMESTAMPS
time_fmt = TIME_MOD; | TIME_MOD
#endif #endif
#ifdef CONFIG_FEATURE_LS_SORTFILES
| SORT_NAME | SORT_ORDER_FORWARD
#endif
;
#ifdef CONFIG_FEATURE_AUTOWIDTH #ifdef CONFIG_FEATURE_AUTOWIDTH
ioctl(fileno(stdout), TIOCGWINSZ, &win); ioctl(fileno(stdout), TIOCGWINSZ, &win);
if (win.ws_col > 0) if (win.ws_col > 0)
@ -811,163 +875,78 @@ extern int ls_main(int argc, char **argv)
#endif #endif
/* process options */ /* process options */
while ((opt = getopt(argc, argv, "1AaCdgilnsx" while ((opt = getopt(argc, argv, ls_opts)) > 0) {
#ifdef CONFIG_FEATURE_AUTOWIDTH #ifdef CONFIG_FEATURE_AUTOWIDTH
"T:w:" if (opt == 'T') {
#endif
#ifdef CONFIG_FEATURE_LS_FILETYPES
"Fp"
#endif
#ifdef CONFIG_FEATURE_LS_RECURSIVE
"R"
#endif
#ifdef CONFIG_FEATURE_LS_SORTFILES
"rSvX"
#endif
#ifdef CONFIG_FEATURE_LS_TIMESTAMPS
"cetu"
#endif
#ifdef CONFIG_FEATURE_LS_FOLLOWLINKS
"L"
#endif
#ifdef CONFIG_FEATURE_HUMAN_READABLE
"h"
#endif
"k")) > 0) {
switch (opt) {
case '1':
style_fmt = STYLE_SINGLE;
list_fmt = LIST_SHORT;
break;
case 'A':
disp_opts |= DISP_HIDDEN;
break;
case 'a':
disp_opts |= DISP_HIDDEN | DISP_DOT;
break;
case 'C':
style_fmt = STYLE_COLUMNS;
list_fmt = LIST_SHORT;
break;
case 'd':
disp_opts |= DISP_NOLIST;
break;
case 'g': /* ignore -- for ftp servers */
break;
case 'i':
list_fmt |= LIST_INO;
break;
case 'l':
style_fmt = STYLE_LONG;
list_fmt |= LIST_LONG;
#ifdef CONFIG_FEATURE_HUMAN_READABLE
ls_disp_hr = FALSE;
#endif
break;
case 'n':
list_fmt |= LIST_ID_NUMERIC;
break;
case 's':
list_fmt |= LIST_BLOCKS;
break;
case 'x':
disp_opts = DISP_ROWS;
break;
#ifdef CONFIG_FEATURE_LS_FILETYPES
case 'F':
list_fmt |= LIST_FILETYPE | LIST_EXEC;
break;
case 'p':
list_fmt |= LIST_FILETYPE;
break;
#endif
#ifdef CONFIG_FEATURE_LS_RECURSIVE
case 'R':
disp_opts |= DISP_RECURSIVE;
break;
#endif
#ifdef CONFIG_FEATURE_LS_SORTFILES
case 'r':
sort_order |= SORT_REVERSE;
break;
case 'S':
sort_opts = SORT_SIZE;
break;
case 'v':
sort_opts = SORT_VERSION;
break;
case 'X':
sort_opts = SORT_EXT;
break;
#endif
#ifdef CONFIG_FEATURE_LS_TIMESTAMPS
case 'e':
list_fmt |= LIST_FULLTIME;
break;
case 'c':
time_fmt = TIME_CHANGE;
#ifdef CONFIG_FEATURE_LS_SORTFILES
sort_opts = SORT_CTIME;
#endif
break;
case 'u':
time_fmt = TIME_ACCESS;
#ifdef CONFIG_FEATURE_LS_SORTFILES
sort_opts = SORT_ATIME;
#endif
break;
case 't':
#ifdef CONFIG_FEATURE_LS_SORTFILES
sort_opts = SORT_MTIME;
#endif
break;
#endif
#ifdef CONFIG_FEATURE_LS_FOLLOWLINKS
case 'L':
follow_links = TRUE;
break;
#endif
#ifdef CONFIG_FEATURE_AUTOWIDTH
case 'T':
tabstops = atoi(optarg); tabstops = atoi(optarg);
break; continue;
case 'w': }
if (opt == 'w') {
terminal_width = atoi(optarg); terminal_width = atoi(optarg);
break; continue;
#endif }
#ifdef CONFIG_FEATURE_HUMAN_READABLE if (opt == ':') {
case 'h':
ls_disp_hr = TRUE;
break;
#endif
case 'k':
break;
default:
goto print_usage_message; goto print_usage_message;
} }
#endif
{
unsigned int flags;
const char *p = strchr(ls_opts, opt);
if (!p) { /* shouldn't be necessary */
goto print_usage_message;
}
flags = opt_flags[(int)(p - ls_opts)];
if (flags & LIST_MASK_TRIGGER) {
all_fmt &= ~LIST_MASK;
}
if (flags & STYLE_MASK_TRIGGER) {
all_fmt &= ~STYLE_MASK;
}
if (flags & SORT_MASK_TRIGGER) {
all_fmt &= ~SORT_MASK;
}
if (flags & DISP_MASK_TRIGGER) {
all_fmt &= ~DISP_MASK;
}
if (flags & TIME_MASK_TRIGGER) {
all_fmt &= ~TIME_MASK;
}
#ifdef CONFIG_FEATURE_HUMAN_READABLE
if (opt == 'l') {
all_fmt &= ~LS_DISP_HR;
}
#endif
all_fmt |= flags;
}
} }
/* sort out which command line options take precedence */ /* sort out which command line options take precedence */
#ifdef CONFIG_FEATURE_LS_RECURSIVE #ifdef CONFIG_FEATURE_LS_RECURSIVE
if (disp_opts & DISP_NOLIST) if (all_fmt & DISP_NOLIST)
disp_opts &= ~DISP_RECURSIVE; /* no recurse if listing only dir */ all_fmt &= ~DISP_RECURSIVE; /* no recurse if listing only dir */
#endif #endif
#if defined (CONFIG_FEATURE_LS_TIMESTAMPS) && defined (CONFIG_FEATURE_LS_SORTFILES) #if defined (CONFIG_FEATURE_LS_TIMESTAMPS) && defined (CONFIG_FEATURE_LS_SORTFILES)
if (time_fmt & TIME_CHANGE) if (all_fmt & TIME_CHANGE)
sort_opts = SORT_CTIME; all_fmt = (all_fmt & ~SORT_MASK) | SORT_CTIME;
if (time_fmt & TIME_ACCESS) if (all_fmt & TIME_ACCESS)
sort_opts = SORT_ATIME; all_fmt = (all_fmt & ~SORT_MASK) | SORT_ATIME;
#endif #endif
if (style_fmt != STYLE_LONG) /* only for long list */ if ((all_fmt & STYLE_MASK) != STYLE_LONG) /* only for long list */
list_fmt &= ~(LIST_ID_NUMERIC|LIST_FULLTIME|LIST_ID_NAME|LIST_ID_NUMERIC); all_fmt &= ~(LIST_ID_NUMERIC|LIST_FULLTIME|LIST_ID_NAME|LIST_ID_NUMERIC);
#ifdef CONFIG_FEATURE_LS_USERNAME #ifdef CONFIG_FEATURE_LS_USERNAME
if (style_fmt == STYLE_LONG && (list_fmt & LIST_ID_NUMERIC)) if ((all_fmt & STYLE_MASK) == STYLE_LONG && (all_fmt & LIST_ID_NUMERIC))
list_fmt &= ~LIST_ID_NAME; /* don't list names if numeric uid */ all_fmt &= ~LIST_ID_NAME; /* don't list names if numeric uid */
#endif #endif
/* choose a display format */ /* choose a display format */
if (style_fmt == STYLE_AUTO) if ((all_fmt & STYLE_MASK) == STYLE_AUTO)
style_fmt = isatty(fileno(stdout)) ? STYLE_COLUMNS : STYLE_SINGLE; #if STYLE_AUTO != 0
all_fmt = (all_fmt & ~STYLE_MASK)
| (isatty(fileno(stdout)) ? STYLE_COLUMNS : STYLE_SINGLE);
#else
all_fmt |= (isatty(fileno(stdout)) ? STYLE_COLUMNS : STYLE_SINGLE);
#endif
/* /*
* when there are no cmd line args we have to supply a default "." arg. * when there are no cmd line args we have to supply a default "." arg.
@ -979,7 +958,7 @@ extern int ls_main(int argc, char **argv)
ac = argc - optind; /* how many cmd line args are left */ ac = argc - optind; /* how many cmd line args are left */
if (ac < 1) { if (ac < 1) {
av = (char **) xcalloc((size_t) 1, (size_t) (sizeof(char *))); av = (char **) xcalloc((size_t) 1, (size_t) (sizeof(char *)));
av[0] = xstrdup("."); av[0] = bb_xstrdup(".");
ac = 1; ac = 1;
} else { } else {
av = (char **) xcalloc((size_t) ac, (size_t) (sizeof(char *))); av = (char **) xcalloc((size_t) ac, (size_t) (sizeof(char *)));
@ -990,12 +969,12 @@ extern int ls_main(int argc, char **argv)
/* now, everything is in the av array */ /* now, everything is in the av array */
if (ac > 1) if (ac > 1)
disp_opts |= DISP_DIRNAME; /* 2 or more items? label directories */ all_fmt |= DISP_DIRNAME; /* 2 or more items? label directories */
/* stuff the command line file names into an dnode array */ /* stuff the command line file names into an dnode array */
dn = NULL; dn = NULL;
for (oi = 0; oi < ac; oi++) { for (oi = 0; oi < ac; oi++) {
char *fullname = xstrdup(av[oi]); char *fullname = bb_xstrdup(av[oi]);
cur = my_stat(fullname, fullname); cur = my_stat(fullname, fullname);
if (!cur) if (!cur)
@ -1015,7 +994,7 @@ extern int ls_main(int argc, char **argv)
} }
if (disp_opts & DISP_NOLIST) { if (all_fmt & DISP_NOLIST) {
#ifdef CONFIG_FEATURE_LS_SORTFILES #ifdef CONFIG_FEATURE_LS_SORTFILES
shellsort(dnp, nfiles); shellsort(dnp, nfiles);
#endif #endif
@ -1042,5 +1021,5 @@ extern int ls_main(int argc, char **argv)
return (status); return (status);
print_usage_message: print_usage_message:
show_usage(); bb_show_usage();
} }

View File

@ -770,13 +770,13 @@ static int md5_file(const char *filename,
have_read_stdin = 1; have_read_stdin = 1;
fp = stdin; fp = stdin;
} else { } else {
fp = wfopen(filename, "r"); fp = bb_wfopen(filename, "r");
if (fp == NULL) if (fp == NULL)
return FALSE; return FALSE;
} }
if (md5_stream(fp, md5_result)) { if (md5_stream(fp, md5_result)) {
perror_msg("%s", filename); bb_perror_msg("%s", filename);
if (fp != stdin) if (fp != stdin)
fclose(fp); fclose(fp);
@ -784,7 +784,7 @@ static int md5_file(const char *filename,
} }
if (fp != stdin && fclose(fp) == EOF) { if (fp != stdin && fclose(fp) == EOF) {
perror_msg("%s", filename); bb_perror_msg("%s", filename);
return FALSE; return FALSE;
} }
@ -805,7 +805,7 @@ static int md5_check(const char *checkfile_name)
have_read_stdin = 1; have_read_stdin = 1;
checkfile_stream = stdin; checkfile_stream = stdin;
} else { } else {
checkfile_stream = wfopen(checkfile_name, "r"); checkfile_stream = bb_wfopen(checkfile_name, "r");
if (checkfile_stream == NULL) if (checkfile_stream == NULL)
return FALSE; return FALSE;
} }
@ -836,7 +836,7 @@ static int md5_check(const char *checkfile_name)
if (split_3(line, line_length, &md5num, &filename) if (split_3(line, line_length, &md5num, &filename)
|| !hex_digits(md5num)) { || !hex_digits(md5num)) {
if (warn) { if (warn) {
error_msg("%s: %lu: improperly formatted MD5 checksum line", bb_error_msg("%s: %lu: improperly formatted MD5 checksum line",
checkfile_name, (unsigned long) line_number); checkfile_name, (unsigned long) line_number);
} }
} else { } else {
@ -881,18 +881,18 @@ static int md5_check(const char *checkfile_name)
while (!feof(checkfile_stream) && !ferror(checkfile_stream)); while (!feof(checkfile_stream) && !ferror(checkfile_stream));
if (ferror(checkfile_stream)) { if (ferror(checkfile_stream)) {
error_msg("%s: read error", checkfile_name); bb_error_msg("%s: read error", checkfile_name);
return FALSE; return FALSE;
} }
if (checkfile_stream != stdin && fclose(checkfile_stream) == EOF) { if (checkfile_stream != stdin && fclose(checkfile_stream) == EOF) {
perror_msg("md5sum: %s", checkfile_name); bb_perror_msg("md5sum: %s", checkfile_name);
return FALSE; return FALSE;
} }
if (n_properly_formated_lines == 0) { if (n_properly_formated_lines == 0) {
/* Warn if no tests are found. */ /* Warn if no tests are found. */
error_msg("%s: no properly formatted MD5 checksum lines found", bb_error_msg("%s: no properly formatted MD5 checksum lines found",
checkfile_name); checkfile_name);
return FALSE; return FALSE;
} else { } else {
@ -901,13 +901,13 @@ static int md5_check(const char *checkfile_name)
- n_open_or_read_failures); - n_open_or_read_failures);
if (n_open_or_read_failures > 0) { if (n_open_or_read_failures > 0) {
error_msg("WARNING: %d of %d listed files could not be read", bb_error_msg("WARNING: %d of %d listed files could not be read",
n_open_or_read_failures, n_properly_formated_lines); n_open_or_read_failures, n_properly_formated_lines);
return FALSE; return FALSE;
} }
if (n_mismatched_checksums > 0) { if (n_mismatched_checksums > 0) {
error_msg("WARNING: %d of %d computed checksums did NOT match", bb_error_msg("WARNING: %d of %d computed checksums did NOT match",
n_mismatched_checksums, n_computed_checkums); n_mismatched_checksums, n_computed_checkums);
return FALSE; return FALSE;
} }
@ -965,31 +965,31 @@ int md5sum_main(int argc,
break; break;
default: default:
show_usage(); bb_show_usage();
} }
} }
if (file_type_specified && do_check) { if (file_type_specified && do_check) {
error_msg_and_die("the -b and -t options are meaningless when verifying checksums"); bb_error_msg_and_die("the -b and -t options are meaningless when verifying checksums");
} }
if (n_strings > 0 && do_check) { if (n_strings > 0 && do_check) {
error_msg_and_die("the -g and -c options are mutually exclusive"); bb_error_msg_and_die("the -g and -c options are mutually exclusive");
} }
if (status_only && !do_check) { if (status_only && !do_check) {
error_msg_and_die("the -s option is meaningful only when verifying checksums"); bb_error_msg_and_die("the -s option is meaningful only when verifying checksums");
} }
if (warn && !do_check) { if (warn && !do_check) {
error_msg_and_die("the -w option is meaningful only when verifying checksums"); bb_error_msg_and_die("the -w option is meaningful only when verifying checksums");
} }
if (n_strings > 0) { if (n_strings > 0) {
size_t i; size_t i;
if (optind < argc) { if (optind < argc) {
error_msg_and_die("no files may be specified when using -g"); bb_error_msg_and_die("no files may be specified when using -g");
} }
for (i = 0; i < n_strings; ++i) { for (i = 0; i < n_strings; ++i) {
size_t cnt; size_t cnt;
@ -1002,7 +1002,7 @@ int md5sum_main(int argc,
} }
} else if (do_check) { } else if (do_check) {
if (optind + 1 < argc) { if (optind + 1 < argc) {
error_msg("only one argument may be specified when using -c"); bb_error_msg("only one argument may be specified when using -c");
} }
err = md5_check ((optind == argc) ? "-" : argv[optind]); err = md5_check ((optind == argc) ? "-" : argv[optind]);
@ -1060,11 +1060,11 @@ int md5sum_main(int argc,
} }
if (fclose (stdout) == EOF) { if (fclose (stdout) == EOF) {
error_msg_and_die("write error"); bb_error_msg_and_die("write error");
} }
if (have_read_stdin && fclose (stdin) == EOF) { if (have_read_stdin && fclose (stdin) == EOF) {
error_msg_and_die("standard input"); bb_error_msg_and_die(bb_msg_standard_input);
} }
if (err == 0) if (err == 0)

View File

@ -20,46 +20,50 @@
* *
*/ */
#include <errno.h> /* BB_AUDIT SUSv3 compliant */
#include <getopt.h> /* http://www.opengroup.org/onlinepubs/007904975/utilities/mkdir.html */
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
/* Mar 16, 2003 Manuel Novoa III (mjn3@codepoet.org)
*
* Fixed broken permission setting when -p was used; especially in
* conjunction with -m.
*/
#include <stdlib.h>
#include <unistd.h>
#include "busybox.h" #include "busybox.h"
extern int mkdir_main (int argc, char **argv) extern int mkdir_main (int argc, char **argv)
{ {
mode_t mode = -1; mode_t mode = (mode_t)(-1);
int status = EXIT_SUCCESS;
int flags = 0; int flags = 0;
int i, opt; int opt;
while ((opt = getopt (argc, argv, "m:p")) != -1) { while ((opt = getopt (argc, argv, "m:p")) > 0) {
switch (opt) { if (opt == 'm') {
case 'm':
mode = 0777; mode = 0777;
if (!parse_mode (optarg, &mode)) { if (!bb_parse_mode (optarg, &mode)) {
error_msg_and_die ("invalid mode `%s'", optarg); bb_error_msg_and_die ("invalid mode `%s'", optarg);
} }
umask(0); } else if (opt == 'p') {
break;
case 'p':
flags |= FILEUTILS_RECUR; flags |= FILEUTILS_RECUR;
break; } else {
default: bb_show_usage();
show_usage ();
} }
} }
if (optind == argc) if (optind == argc) {
show_usage (); bb_show_usage();
for (i = optind; i < argc; i++) {
make_directory (argv[i], mode, flags);
} }
return(EXIT_SUCCESS); argv += optind;
do {
if (bb_make_directory(*argv, mode, flags)) {
status = EXIT_FAILURE;
}
} while (*++argv);
return status;
} }

View File

@ -1,8 +1,8 @@
/* vi: set sw=4 ts=4: */ /* vi: set sw=4 ts=4: */
/* /*
* Mini mkfifo implementation for busybox * mkfifo implementation for busybox
* *
* Copyright (C) 1999 by Randolph Chung <tausq@debian.org> * Copyright (C) 2003 Manuel Novoa III <mjn3@codepoet.org>
* *
* This program is free software; you can redistribute it and/or modify * This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
@ -20,41 +20,32 @@
* *
*/ */
#include <stdio.h> /* BB_AUDIT SUSv3 compliant */
#include <sys/types.h> /* http://www.opengroup.org/onlinepubs/007904975/utilities/mkfifo.html */
#include <errno.h>
#include <stdlib.h> #include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include "busybox.h" #include "busybox.h"
#include "libcoreutils/coreutils.h"
extern int mkfifo_main(int argc, char **argv) extern int mkfifo_main(int argc, char **argv)
{ {
char *thisarg; mode_t mode;
mode_t mode = 0666; int retval = EXIT_SUCCESS;
argc--; mode = getopt_mk_fifo_nod(argc, argv);
argv++;
/* Parse any options */ if (!*(argv += optind)) {
while (argc > 1) { bb_show_usage();
if (**argv != '-')
show_usage();
thisarg = *argv;
thisarg++;
switch (*thisarg) {
case 'm':
argc--;
argv++;
parse_mode(*argv, &mode);
break;
default:
show_usage();
}
argc--;
argv++;
} }
if (argc < 1 || *argv[0] == '-')
show_usage(); do {
if (mkfifo(*argv, mode) < 0) if (mkfifo(*argv, mode) < 0) {
perror_msg_and_die("mkfifo"); bb_perror_msg("%s", *argv); /* Avoid multibyte problems. */
return EXIT_SUCCESS; retval = EXIT_FAILURE;
}
} while (*++argv);
return retval;
} }

View File

@ -1,9 +1,8 @@
/* vi: set sw=4 ts=4: */ /* vi: set sw=4 ts=4: */
/* /*
* Mini mknod implementation for busybox * mknod implementation for busybox
* *
* Copyright (C) 1995, 1996 by Bruce Perens <bruce@pixar.com>. * Copyright (C) 2003 Manuel Novoa III <mjn3@codepoet.org>
* Copyright (C) 1999-2002 by Erik Andersen <andersee@debian.org>
* *
* This program is free software; you can redistribute it and/or modify * This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
@ -21,73 +20,44 @@
* *
*/ */
#include <stdio.h> /* BB_AUDIT SUSv3 N/A -- Matches GNU behavior. */
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h> #include <stdlib.h>
#include <sys/types.h> #include <string.h>
#include <sys/stat.h> #include <sys/stat.h>
#include <unistd.h>
#include "busybox.h" #include "busybox.h"
#include "libcoreutils/coreutils.h"
int mknod_main(int argc, char **argv) static const char modes_chars[] = { 'p', 'c', 'u', 'b', 0, 1, 1, 2 };
static const mode_t modes_cubp[] = { S_IFIFO, S_IFCHR, S_IFBLK };
extern int mknod_main(int argc, char **argv)
{ {
char *thisarg; mode_t mode;
mode_t mode = 0; dev_t dev;
mode_t perm = 0666; const char *name;
dev_t dev = (dev_t) 0;
argc--; mode = getopt_mk_fifo_nod(argc, argv);
argv++; argv += optind;
argc -= optind;
/* Parse any options */ if ((argc >= 2) && ((name = strchr(modes_chars, argv[1][0])) != NULL)) {
while (argc > 1) { mode |= modes_cubp[(int)(name[4])];
if (**argv != '-')
break; dev = 0;
thisarg = *argv; if ((*name != 'p') && ((argc -= 2) == 0)) {
thisarg++; dev = (bb_xgetularg10_bnd(argv[2], 0, 255) << 8)
switch (*thisarg) { + bb_xgetularg10_bnd(argv[3], 0, 255);
case 'm':
argc--;
argv++;
parse_mode(*argv, &perm);
umask(0);
break;
default:
show_usage();
} }
argc--;
argv++; if (argc == 2) {
} name = *argv;
if (argc != 4 && argc != 2) { if (mknod(name, mode, dev) == 0) {
show_usage(); return EXIT_SUCCESS;
} }
switch (argv[1][0]) { bb_perror_msg_and_die("%s", name);
case 'c':
case 'u':
mode = S_IFCHR;
break;
case 'b':
mode = S_IFBLK;
break;
case 'p':
mode = S_IFIFO;
if (argc != 2) {
show_usage();
} }
break;
default:
show_usage();
} }
bb_show_usage();
if (mode == S_IFCHR || mode == S_IFBLK) {
dev = (dev_t) ((atoi(argv[2]) << 8) | atoi(argv[3]));
}
mode |= perm;
if (mknod(argv[0], mode, dev) != 0)
perror_msg_and_die("%s", argv[0]);
return EXIT_SUCCESS;
} }

View File

@ -2,7 +2,6 @@
/* /*
* Mini mv implementation for busybox * Mini mv implementation for busybox
* *
*
* Copyright (C) 2000 by Matt Kraai <kraai@alumni.carnegiemellon.edu> * Copyright (C) 2000 by Matt Kraai <kraai@alumni.carnegiemellon.edu>
* *
* This program is free software; you can redistribute it and/or modify * This program is free software; you can redistribute it and/or modify
@ -21,148 +20,122 @@
* *
*/ */
/* Mar 16, 2003 Manuel Novoa III (mjn3@codepoet.org)
*
* Size reduction and improved error checking.
*/
#include <sys/types.h> #include <sys/types.h>
#include <sys/stat.h> #include <sys/stat.h>
#include <unistd.h> #include <unistd.h>
#include <dirent.h> #include <dirent.h>
#include <errno.h> #include <errno.h>
#include <stdlib.h> #include <stdlib.h>
#include "busybox.h" #include "busybox.h"
#include "libcoreutils/coreutils.h"
static int flags; static const char *fmt = "cannot overwrite %sdirectory with %sdirectory";
static int manual_rename(const char *source, const char *dest)
{
struct stat source_stat;
struct stat dest_stat;
int source_exists = 1;
int dest_exists = 1;
if (stat(source, &source_stat) < 0) {
if (errno != ENOENT) {
perror_msg("unable to stat `%s'", source);
return -1;
}
source_exists = 0;
}
if (stat(dest, &dest_stat) < 0) {
if (errno != ENOENT) {
perror_msg("unable to stat `%s'", dest);
return -1;
}
dest_exists = 0;
}
if (dest_exists) {
if (S_ISDIR(dest_stat.st_mode) &&
(!source_exists || !S_ISDIR(source_stat.st_mode))) {
error_msg("cannot overwrite directory with non-directory");
return -1;
}
if (!S_ISDIR(dest_stat.st_mode) && source_exists &&
S_ISDIR(source_stat.st_mode)) {
error_msg("cannot overwrite non-directory with directory");
return -1;
}
if (unlink(dest) < 0) {
perror_msg("cannot remove `%s'", dest);
return -1;
}
}
if (copy_file(source, dest,
FILEUTILS_RECUR | FILEUTILS_PRESERVE_STATUS) < 0)
return -1;
if (remove_file(source, FILEUTILS_RECUR | FILEUTILS_FORCE) < 0)
return -1;
return 0;
}
static int move_file(const char *source, const char *dest)
{
struct stat dest_stat;
int dest_exists = 1;
if (stat(dest, &dest_stat) < 0) {
if (errno != ENOENT) {
perror_msg("unable to stat `%s'", dest);
return -1;
}
dest_exists = 0;
}
if (dest_exists && !(flags & FILEUTILS_FORCE) &&
((access(dest, W_OK) < 0 && isatty(0)) ||
(flags & FILEUTILS_INTERACTIVE))) {
fprintf(stderr, "mv: overwrite `%s'? ", dest);
if (!ask_confirmation())
return 0;
}
if (rename(source, dest) < 0) {
if (errno == EXDEV)
return manual_rename(source, dest);
perror_msg("unable to rename `%s'", source);
return -1;
}
return 0;
}
extern int mv_main(int argc, char **argv) extern int mv_main(int argc, char **argv)
{ {
int status = 0; struct stat source_stat;
struct stat dest_stat;
const char *last;
const char *dest;
int dest_exists;
int source_exists;
int opt; int opt;
int i; int flags = 0;
int status = 0;
while ((opt = getopt(argc, argv, "fi")) != -1) while ((opt = getopt(argc, argv, "fi")) > 0) {
switch (opt) { flags &= ~(FILEUTILS_INTERACTIVE | FILEUTILS_FORCE);
case 'f': if (opt == 'i') {
flags &= ~FILEUTILS_INTERACTIVE;
flags |= FILEUTILS_FORCE;
break;
case 'i':
flags &= ~FILEUTILS_FORCE;
flags |= FILEUTILS_INTERACTIVE; flags |= FILEUTILS_INTERACTIVE;
break; } else if (opt == 'f') {
default: flags |= FILEUTILS_FORCE;
show_usage(); } else {
bb_show_usage();
} }
}
if (optind + 2 > argc) if (optind + 2 > argc)
show_usage(); bb_show_usage();
last = argv[argc - 1];
argv += optind;
if (optind + 2 == argc) { if (optind + 2 == argc) {
struct stat dest_stat; if ((dest_exists = cp_mv_stat(last, &dest_stat)) < 0) {
int dest_exists = 1; return 1;
if (stat(argv[optind + 1], &dest_stat) < 0) {
if (errno != ENOENT)
perror_msg_and_die("unable to stat `%s'", argv[optind + 1]);
dest_exists = 0;
} }
if (!dest_exists || !S_ISDIR(dest_stat.st_mode)) { if (!(dest_exists & 2)) {
if (move_file(argv[optind], argv[optind + 1]) < 0) dest = last;
status = 1; goto DO_MOVE;
return status;
} }
} }
do {
dest = concat_path_file(last,
bb_get_last_path_component(*argv));
for (i = optind; i < argc - 1; i++) { if ((dest_exists = cp_mv_stat(dest, &dest_stat)) < 0) {
char *dest = concat_path_file(argv[argc - 1], goto RET_1;
get_last_path_component(argv[i])); }
if (move_file(argv[i], dest) < 0)
DO_MOVE:
if (dest_exists && !(flags & FILEUTILS_FORCE) &&
((access(dest, W_OK) < 0 && isatty(0)) ||
(flags & FILEUTILS_INTERACTIVE))) {
if (fprintf(stderr, "mv: overwrite `%s'? ", dest) < 0) {
goto RET_1; /* Ouch! fprintf failed! */
}
if (!bb_ask_confirmation())
goto RET_0;
}
if (rename(*argv, dest) < 0) {
if (errno != EXDEV) {
bb_perror_msg("unable to rename `%s'", *argv);
} else if ((source_exists = cp_mv_stat(*argv, &source_stat)) >= 0) {
if (dest_exists) {
if (dest_exists & 2) {
if (!(source_exists & 2)) {
bb_error_msg(fmt, "", "non-");
goto RET_1;
}
} else {
if (source_exists & 2) {
bb_error_msg(fmt, "non-", "");
goto RET_1;
}
}
if (unlink(dest) < 0) {
bb_perror_msg("cannot remove `%s'", dest);
goto RET_1;
}
}
if ((copy_file(*argv, dest,
FILEUTILS_RECUR | FILEUTILS_PRESERVE_STATUS) >= 0)
&& (remove_file(*argv, FILEUTILS_RECUR | FILEUTILS_FORCE) >= 0)
) {
goto RET_0;
}
}
RET_1:
status = 1; status = 1;
free(dest); }
}
return status; RET_0:
if (dest != last) {
free((void *) dest);
}
} while (*++argv != last);
exit(status);
} }

View File

@ -23,22 +23,18 @@
*/ */
#include <ctype.h> #include <ctype.h>
#include <string.h>
#include <getopt.h> #include <getopt.h>
#include <stdlib.h> #include <stdlib.h>
#include "dump.h"
#include "busybox.h" #include "busybox.h"
#include "dump.h"
extern FS *fshead; /* head of format strings */ #define isdecdigit(c) (isdigit)(c)
extern int blocksize; /* data block size */ #define ishexdigit(c) (isxdigit)(c)
extern int length; /* max bytes to read */
#define ishexdigit(c) \
((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F'))
static void static void
odoffset(int argc, char ***argvp) odoffset(int argc, char ***argvp)
{ {
extern off_t skip;
register char *num, *p; register char *num, *p;
int base; int base;
char *end; char *end;
@ -62,13 +58,15 @@ odoffset(int argc, char ***argvp)
return; return;
} }
if (*p != '+' && (argc < 2 || if ((*p != '+')
(!isdigit(p[0]) && (p[0] != 'x' || !ishexdigit(p[1]))))) && (argc < 2
|| (!isdecdigit(p[0])
&& ((p[0] != 'x') || !ishexdigit(p[1])))))
return; return;
base = 0; base = 0;
/* /*
* skip over leading '+', 'x[0-9a-fA-f]' or '0x', and * bb_dump_skip over leading '+', 'x[0-9a-fA-f]' or '0x', and
* set base. * set base.
*/ */
if (p[0] == '+') if (p[0] == '+')
@ -81,11 +79,11 @@ odoffset(int argc, char ***argvp)
base = 16; base = 16;
} }
/* skip over the number */ /* bb_dump_skip over the number */
if (base == 16) if (base == 16)
for (num = p; ishexdigit(*p); ++p); for (num = p; ishexdigit(*p); ++p);
else else
for (num = p; isdigit(*p); ++p); for (num = p; isdecdigit(*p); ++p);
/* check for no number */ /* check for no number */
if (num == p) if (num == p)
@ -98,21 +96,23 @@ odoffset(int argc, char ***argvp)
base = 10; base = 10;
} }
skip = strtol(num, &end, base ? base : 8); bb_dump_skip = strtol(num, &end, base ? base : 8);
/* if end isn't the same as p, we got a non-octal digit */ /* if end isn't the same as p, we got a non-octal digit */
if (end != p) if (end != p)
skip = 0; bb_dump_skip = 0;
else { else {
if (*p) { if (*p) {
if (*p == 'b') if (*p == 'b') {
skip *= 512; bb_dump_skip *= 512;
else if (*p == 'B') ++p;
skip *= 1024; } else if (*p == 'B') {
++p; bb_dump_skip *= 1024;
++p;
}
} }
if (*p) if (*p)
skip = 0; bb_dump_skip = 0;
else { else {
++*argvp; ++*argvp;
/* /*
@ -121,117 +121,76 @@ odoffset(int argc, char ***argvp)
* but it's easy. * but it's easy.
*/ */
#define TYPE_OFFSET 7 #define TYPE_OFFSET 7
if (base == 16) { {
fshead->nextfu->fmt[TYPE_OFFSET] = 'x'; char x_or_d;
fshead->nextfs->nextfu->fmt[TYPE_OFFSET] = 'x'; if (base == 16) {
} else if (base == 10) { x_or_d = 'x';
fshead->nextfu->fmt[TYPE_OFFSET] = 'd'; goto DO_X_OR_D;
fshead->nextfs->nextfu->fmt[TYPE_OFFSET] = 'd'; }
if (base == 10) {
x_or_d = 'd';
DO_X_OR_D:
bb_dump_fshead->nextfu->fmt[TYPE_OFFSET]
= bb_dump_fshead->nextfs->nextfu->fmt[TYPE_OFFSET]
= x_or_d;
}
} }
} }
} }
} }
static void odprecede(void) static const char * const add_strings[] = {
{ "16/1 \"%3_u \" \"\\n\"", /* a */
static int first = 1; "8/2 \" %06o \" \"\\n\"", /* B, o */
"16/1 \"%03o \" \"\\n\"", /* b */
"16/1 \"%3_c \" \"\\n\"", /* c */
"8/2 \" %05u \" \"\\n\"", /* d */
"4/4 \" %010u \" \"\\n\"", /* D */
"2/8 \" %21.14e \" \"\\n\"", /* e (undocumented in od), F */
"4/4 \" %14.7e \" \"\\n\"", /* f */
"4/4 \" %08x \" \"\\n\"", /* H, X */
"8/2 \" %04x \" \"\\n\"", /* h, x */
"4/4 \" %11d \" \"\\n\"", /* I, L, l */
"8/2 \" %6d \" \"\\n\"", /* i */
"4/4 \" %011o \" \"\\n\"", /* O */
};
if (first) { static const signed char od_opts[] = "aBbcDdeFfHhIiLlOovXx";
first = 0;
add("\"%07.7_Ao\n\""); static const signed char od_o2si[] = {
add("\"%07.7_ao \""); 0, 1, 2, 3, 5,
} else 4, 6, 6, 7, 8,
add("\" \""); 9, 0xa, 0xb, 0xa, 0xa,
} 0xb, 1, -1, 8, 9,
};
int od_main(int argc, char **argv) int od_main(int argc, char **argv)
{ {
int ch; int ch;
extern enum _vflag vflag; bb_dump_vflag = FIRST;
vflag = FIRST; bb_dump_length = -1;
length = -1; int first = 1;
signed char *p;
while ((ch = getopt(argc, argv, "aBbcDdeFfHhIiLlOoPpswvXx")) != EOF) while ((ch = getopt(argc, argv, od_opts)) > 0) {
switch (ch) { if (((p = strchr(od_opts, ch)) != NULL) && (*p >= 0)) {
case 'a': if (first) {
odprecede(); first = 0;
add("16/1 \"%3_u \" \"\\n\""); bb_dump_add("\"%07.7_Ao\n\"");
break; bb_dump_add("\"%07.7_ao \"");
case 'B': } else {
case 'o': bb_dump_add("\" \"");
odprecede();
add("8/2 \" %06o \" \"\\n\"");
break;
case 'b':
odprecede();
add("16/1 \"%03o \" \"\\n\"");
break;
case 'c':
odprecede();
add("16/1 \"%3_c \" \"\\n\"");
break;
case 'd':
odprecede();
add("8/2 \" %05u \" \"\\n\"");
break;
case 'D':
odprecede();
add("4/4 \" %010u \" \"\\n\"");
break;
case 'e': /* undocumented in od */
case 'F':
odprecede();
add("2/8 \" %21.14e \" \"\\n\"");
break;
case 'f':
odprecede();
add("4/4 \" %14.7e \" \"\\n\"");
break;
case 'H':
case 'X':
odprecede();
add("4/4 \" %08x \" \"\\n\"");
break;
case 'h':
case 'x':
odprecede();
add("8/2 \" %04x \" \"\\n\"");
break;
case 'I':
case 'L':
case 'l':
odprecede();
add("4/4 \" %11d \" \"\\n\"");
break;
case 'i':
odprecede();
add("8/2 \" %6d \" \"\\n\"");
break;
case 'O':
odprecede();
add("4/4 \" %011o \" \"\\n\"");
break;
case 'v':
vflag = ALL;
break;
case 'P':
case 'p':
case 's':
case 'w':
case '?':
default:
error_msg("od: od(1) has been deprecated for hexdump(1).\n");
if (ch != '?') {
error_msg("od: hexdump(1) compatibility doesn't support the -%c option%s\n",
ch, ch == 's' ? "; see strings(1)." : ".");
} }
show_usage(); bb_dump_add(add_strings[od_o2si[(int)(p-od_opts)]]);
} else if (ch == 'v') {
bb_dump_vflag = ALL;
} else { /* P, p, s, w, or other unhandled */
bb_show_usage();
} }
}
if (!fshead) { if (!bb_dump_fshead) {
add("\"%07.7_Ao\n\""); bb_dump_add("\"%07.7_Ao\n\"");
add("\"%07.7_ao \" 8/2 \"%06o \" \"\\n\""); bb_dump_add("\"%07.7_ao \" 8/2 \"%06o \" \"\\n\"");
} }
argc -= optind; argc -= optind;
@ -239,7 +198,7 @@ int od_main(int argc, char **argv)
odoffset(argc, &argv); odoffset(argc, &argv);
return(dump(argv)); return(bb_dump_dump(argv));
} }
/*- /*-

View File

@ -124,7 +124,7 @@ int printf_main(int argc, char **argv)
exit_status = 0; exit_status = 0;
if (argc <= 1 || **(argv + 1) == '-') { if (argc <= 1 || **(argv + 1) == '-') {
show_usage(); bb_show_usage();
} }
format = argv[1]; format = argv[1];

View File

@ -20,24 +20,18 @@
* *
*/ */
/* getopt not needed */
#include <stdio.h> #include <stdio.h>
#include <dirent.h>
#include <errno.h>
#include <unistd.h>
#include <stdlib.h> #include <stdlib.h>
#include "busybox.h" #include "busybox.h"
extern int pwd_main(int argc, char **argv) extern int pwd_main(int argc, char **argv)
{ {
static char *buf; char *buf;
buf = xgetcwd(buf); if ((buf = xgetcwd(NULL)) != NULL) {
if (buf != NULL) {
puts(buf); puts(buf);
return EXIT_SUCCESS; bb_fflush_stdout_and_exit(EXIT_SUCCESS);
} }
return EXIT_FAILURE; return EXIT_FAILURE;
} }

View File

@ -14,17 +14,26 @@
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/ */
/* BB_AUDIT SUSv3 N/A -- Apparently a busybox extension. */
/* Mar 16, 2003 Manuel Novoa III (mjn3@codepoet.org)
*
* Now does proper error checking on output and returns a failure exit code
* if one or more paths can not be resolved.
*/
#include <limits.h> #include <limits.h>
#include <stdlib.h> #include <stdlib.h>
#include "busybox.h" #include "busybox.h"
int realpath_main(int argc, char **argv) int realpath_main(int argc, char **argv)
{ {
int retval = EXIT_SUCCESS;
RESERVE_CONFIG_BUFFER(resolved_path, PATH_MAX); RESERVE_CONFIG_BUFFER(resolved_path, PATH_MAX);
if (--argc == 0) { if (--argc == 0) {
show_usage(); bb_show_usage();
} }
do { do {
@ -32,11 +41,14 @@ int realpath_main(int argc, char **argv)
if (realpath(*argv, resolved_path) != NULL) { if (realpath(*argv, resolved_path) != NULL) {
puts(resolved_path); puts(resolved_path);
} else { } else {
perror_msg("%s", *argv); retval = EXIT_FAILURE;
bb_perror_msg("%s", *argv);
} }
} while (--argc); } while (--argc);
#ifdef CONFIG_FEATURE_CLEAN_UP
RELEASE_CONFIG_BUFFER(resolved_path); RELEASE_CONFIG_BUFFER(resolved_path);
#endif
return(EXIT_SUCCESS); bb_fflush_stdout_and_exit(retval);
} }

View File

@ -2,7 +2,6 @@
/* /*
* Mini rm implementation for busybox * Mini rm implementation for busybox
* *
*
* Copyright (C) 2001 Matt Kraai <kraai@alumni.carnegiemellon.edu> * Copyright (C) 2001 Matt Kraai <kraai@alumni.carnegiemellon.edu>
* *
* *
@ -22,55 +21,51 @@
* *
*/ */
#include <stdio.h> /* BB_AUDIT SUSv3 compliant */
#include <time.h> /* http://www.opengroup.org/onlinepubs/007904975/utilities/rm.html */
#include <utime.h>
#include <dirent.h> /* Mar 16, 2003 Manuel Novoa III (mjn3@codepoet.org)
#include <errno.h> *
* Size reduction.
*/
#include <unistd.h> #include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <getopt.h>
#include "busybox.h" #include "busybox.h"
extern int rm_main(int argc, char **argv) extern int rm_main(int argc, char **argv)
{ {
int status = 0; int status = 0;
int opt;
int flags = 0; int flags = 0;
int i; int opt;
while ((opt = getopt(argc, argv, "fiRr")) != -1) { while ((opt = getopt(argc, argv, "fiRr")) > 0) {
switch (opt) { if ((opt == 'r') || (opt == 'R')) {
case 'f':
flags &= ~FILEUTILS_INTERACTIVE;
flags |= FILEUTILS_FORCE;
break;
case 'i':
flags &= ~FILEUTILS_FORCE;
flags |= FILEUTILS_INTERACTIVE;
break;
case 'R':
case 'r':
flags |= FILEUTILS_RECUR; flags |= FILEUTILS_RECUR;
break; } else {
flags &= ~(FILEUTILS_INTERACTIVE | FILEUTILS_FORCE);
if (opt == 'i') {
flags |= FILEUTILS_INTERACTIVE;
} else if (opt == 'f') {
flags |= FILEUTILS_FORCE;
} else {
bb_show_usage();
}
} }
} }
if (!(flags & FILEUTILS_FORCE) && optind == argc) if (*(argv += optind) != NULL) {
show_usage(); do {
const char *base = bb_get_last_path_component(*argv);
for (i = optind; i < argc; i++) { if ((base[0] == '.') && (!base[1] || ((base[1] == '.') && !base[2]))) {
char *base = get_last_path_component(argv[i]); bb_error_msg("cannot remove `.' or `..'");
} else if (remove_file(*argv, flags) >= 0) {
if (strcmp(base, ".") == 0 || strcmp(base, "..") == 0) { continue;
error_msg("cannot remove `.' or `..'"); }
status = 1;
continue;
}
if (remove_file(argv[i], flags) < 0)
status = 1; status = 1;
} while (*++argv);
} else if (!(flags & FILEUTILS_FORCE)) {
bb_show_usage();
} }
return status; return status;

View File

@ -1,9 +1,8 @@
/* vi: set sw=4 ts=4: */ /* vi: set sw=4 ts=4: */
/* /*
* Mini rmdir implementation for busybox * rmdir implementation for busybox
* *
* Copyright (C) 1999,2000 by Lineo, inc. and Erik Andersen * Copyright (C) 2003 Manuel Novoa III <mjn3@codepoet.org>
* Copyright (C) 1999,2000,2001 by Erik Andersen <andersee@debian.org>
* *
* This program is free software; you can redistribute it and/or modify * This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
@ -21,76 +20,54 @@
* *
*/ */
#include <getopt.h> /* BB_AUDIT SUSv3 compliant */
#include <unistd.h> /* http://www.opengroup.org/onlinepubs/007904975/utilities/rmdir.html */
#include <stdlib.h>
#include <stdlib.h>
#include <unistd.h>
#include <libgen.h>
#include "busybox.h" #include "busybox.h"
extern int rmdir_main(int argc, char **argv)
/* Return true if a path is composed of multiple components. */
static int
multiple_components_p (const char *path)
{
const char *s = path;
while (s[0] != '\0' && s[0] != '/')
s++;
while (s[0] == '/')
s++;
return (s[0] != '\0');
}
/* Remove a directory. Returns 0 if successful, -1 on error. */
static int
remove_directory (char *path, int flags)
{
if (!(flags & FILEUTILS_RECUR)) {
if (rmdir (path) < 0) {
perror_msg ("unable to remove `%s'", path);
return -1;
}
} else {
if (remove_directory (path, 0) < 0)
return -1;
if (multiple_components_p (path))
if (remove_directory (dirname (path), flags) < 0)
return -1;
}
return 0;
}
extern int
rmdir_main (int argc, char **argv)
{ {
int status = EXIT_SUCCESS; int status = EXIT_SUCCESS;
int flags = 0; int flags;
int i, opt; int do_dot;
char *path;
while ((opt = getopt (argc, argv, "p")) != -1) flags = bb_getopt_ulflags(argc, argv, "p");
switch (opt) {
case 'p':
flags |= FILEUTILS_RECUR;
break;
default: argv += optind;
show_usage ();
}
if (optind == argc) if (!*argv) {
show_usage(); bb_show_usage();
}
for (i = optind; i < argc; i++) do {
if (remove_directory (argv[i], flags) < 0) path = *argv;
status = EXIT_FAILURE;
/* Record if the first char was a '.' so we can use dirname later. */
do_dot = (*path == '.');
do {
if (rmdir(path) < 0) {
bb_perror_msg("`%s'", path); /* Match gnu rmdir msg. */
status = EXIT_FAILURE;
} else if (flags) {
/* Note: path was not empty or null since rmdir succeeded. */
path = dirname(path);
/* Path is now just the parent component. Note that dirname
* returns "." if there are no parents. We must distinguish
* this from the case of the original path starting with '.'.
*/
if (do_dot || (*path != '.') || path[1]) {
continue;
}
}
break;
} while (1);
} while (*++argv);
return status; return status;
} }

View File

@ -187,7 +187,7 @@ extern int authenticate(const int argc, char **argv, void (*hash_ptr)(FILE *stre
break; break;
#endif #endif
default: default:
show_usage(); bb_show_usage();
} }
} }
@ -204,7 +204,7 @@ extern int authenticate(const int argc, char **argv, void (*hash_ptr)(FILE *stre
hash_ptr(stdin, hashval); hash_ptr(stdin, hashval);
print_hash(hash_length, hashval, NULL); print_hash(hash_length, hashval, NULL);
} else { } else {
FILE *stream = xfopen(argv[i], "r"); FILE *stream = bb_xfopen(argv[i], "r");
hash_ptr(stream, hashval); hash_ptr(stream, hashval);
fclose(stream); fclose(stream);
print_hash(hash_length, hashval, argv[i]); print_hash(hash_length, hashval, argv[i]);

View File

@ -1,8 +1,8 @@
/* vi: set sw=4 ts=4: */ /* vi: set sw=4 ts=4: */
/* /*
* Mini sleep implementation for busybox * sleep implementation for busybox
* *
* Copyright (C) 1995, 1996 by Bruce Perens <bruce@pixar.com>. * Copyright (C) 2003 Manuel Novoa III <mjn3@codepoet.org>
* *
* This program is free software; you can redistribute it and/or modify * This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
@ -20,18 +20,67 @@
* *
*/ */
#include <stdio.h> /* BB_AUDIT SUSv3 compliant */
#include <unistd.h> /* BB_AUDIT GNU issues -- fancy version matches except args must be ints. */
/* http://www.opengroup.org/onlinepubs/007904975/utilities/sleep.html */
/* Mar 16, 2003 Manuel Novoa III (mjn3@codepoet.org)
*
* Rewritten to do proper arg and error checking.
* Also, added a 'fancy' configuration to accept multiple args with
* time suffixes for seconds, minutes, hours, and days.
*/
#include <stdlib.h> #include <stdlib.h>
#include <limits.h>
#include <unistd.h>
#include "busybox.h" #include "busybox.h"
#ifdef CONFIG_FEATURE_FANCY_SLEEP
static const struct suffix_mult sleep_suffixes[] = {
{ "s", 1 },
{ "m", 60 },
{ "h", 60*60 },
{ "d", 24*60*60 },
{ NULL, 0 }
};
#endif
extern int sleep_main(int argc, char **argv) extern int sleep_main(int argc, char **argv)
{ {
if ((argc < 2) || (**(argv + 1) == '-')) { unsigned int duration;
show_usage();
#ifdef CONFIG_FEATURE_FANCY_SLEEP
if (argc < 2) {
bb_show_usage();
}
++argv;
duration = 0;
do {
duration += bb_xgetularg_bnd_sfx(*argv, 10,
0, UINT_MAX-duration,
sleep_suffixes);
} while (*++argv);
#else /* CONFIG_FEATURE_FANCY_SLEEP */
if (argc != 2) {
bb_show_usage();
}
#if UINT_MAX == ULONG_MAX
duration = bb_xgetularg10(argv[1]);
#else
duration = bb_xgetularg10_bnd(argv[1], 0, UINT_MAX);
#endif
#endif /* CONFIG_FEATURE_FANCY_SLEEP */
if (sleep(duration)) {
bb_perror_nomsg_and_die();
} }
if (sleep(atoi(*(++argv))) != 0)
perror_msg_and_die("sleep");
return EXIT_SUCCESS; return EXIT_SUCCESS;
} }

View File

@ -2,7 +2,6 @@
/* /*
* Mini sort implementation for busybox * Mini sort implementation for busybox
* *
*
* Copyright (C) 2000 by Matt Kraai <kraai@alumni.carnegiemellon.edu> * Copyright (C) 2000 by Matt Kraai <kraai@alumni.carnegiemellon.edu>
* *
* This program is free software; you can redistribute it and/or modify * This program is free software; you can redistribute it and/or modify
@ -21,10 +20,20 @@
* *
*/ */
#include <getopt.h> /* BB_AUDIT SUSv3 _NOT_ compliant -- a number of options are not supported. */
#include <string.h> /* http://www.opengroup.org/onlinepubs/007904975/utilities/sort.html */
/* Mar 16, 2003 Manuel Novoa III (mjn3@codepoet.org)
*
* Now does proper error checking on i/o. Plus some space savings.
*/
#include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "busybox.h" #include "busybox.h"
#include "libcoreutils/coreutils.h"
static int compare_ascii(const void *x, const void *y) static int compare_ascii(const void *x, const void *y)
{ {
@ -41,66 +50,51 @@ int sort_main(int argc, char **argv)
{ {
FILE *fp; FILE *fp;
char *line, **lines = NULL; char *line, **lines = NULL;
int i, opt, nlines = 0; int i, nlines = 0, inc;
int (*compare)(const void *, const void *) = compare_ascii; int (*compare)(const void *, const void *) = compare_ascii;
#ifdef CONFIG_FEATURE_SORT_REVERSE
int reverse = FALSE;
#endif
#ifdef CONFIG_FEATURE_SORT_UNIQUE
int unique = FALSE;
#endif
while ((opt = getopt(argc, argv, "nru")) != -1) { int flags;
switch (opt) {
case 'n': bb_default_error_retval = 2;
compare = compare_numeric;
break; flags = bb_getopt_ulflags(argc, argv, "nru");
#ifdef CONFIG_FEATURE_SORT_REVERSE if (flags & 1) {
case 'r': compare = compare_numeric;
reverse = TRUE;
break;
#endif
#ifdef CONFIG_FEATURE_SORT_UNIQUE
case 'u':
unique = TRUE;
break;
#endif
default:
show_usage();
}
} }
/* read the input */ argv += optind;
for (i = optind; i == optind || i < argc; i++) { if (!*argv) {
if (argv[i] == NULL) *--argv = "-";
fp = stdin; }
else
fp = xfopen(argv[i], "r");
while ((line = get_line_from_file(fp)) != NULL) { do {
fp = xgetoptfile_sort_uniq(argv, "r");
while ((line = bb_get_chomped_line_from_file(fp)) != NULL) {
lines = xrealloc(lines, sizeof(char *) * (nlines + 1)); lines = xrealloc(lines, sizeof(char *) * (nlines + 1));
chomp(line);
lines[nlines++] = line; lines[nlines++] = line;
} }
} bb_xferror(fp, *argv);
bb_fclose_nonstdin(fp);
} while (*++argv);
/* sort it */ /* sort it */
qsort(lines, nlines, sizeof(char *), compare); qsort(lines, nlines, sizeof(char *), compare);
/* print it */ /* print it */
#ifdef CONFIG_FEATURE_SORT_REVERSE i = 0;
if (reverse) { --nlines;
for (i = --nlines; 0 <= i; i--) if ((inc = 1 - (flags & 2)) < 0) { /* reverse */
#ifdef CONFIG_FEATURE_SORT_UNIQUE i = nlines;
if((!unique) || (i == nlines) || (strcmp(lines[i + 1], lines[i]))) }
#endif flags &= 4;
puts(lines[i]);
} else while (nlines >= 0) {
#endif if (!flags || !nlines || strcmp(lines[i+inc], lines[i])) {
for (i = 0; i < nlines; i++) puts(lines[i]);
#ifdef CONFIG_FEATURE_SORT_UNIQUE }
if((!unique) || (!i) || (strcmp(lines[i - 1], lines[i]))) i += inc;
#endif --nlines;
puts(lines[i]); }
return EXIT_SUCCESS;
bb_fflush_stdout_and_exit(EXIT_SUCCESS);
} }

View File

@ -30,9 +30,9 @@
//#define TEST //#define TEST
#include <stddef.h>
#include <termios.h> #include <termios.h>
#include <sys/ioctl.h> #include <sys/ioctl.h>
#include <getopt.h>
#include <sys/param.h> #include <sys/param.h>
#include <unistd.h> #include <unistd.h>
@ -155,13 +155,10 @@ enum speed_setting {
input_speed, output_speed, both_speeds input_speed, output_speed, both_speeds
}; };
/* What to output and how. */
enum output_type {
changed, all, recoverable /* Default, -a, -g. */
};
/* Which member(s) of `struct termios' a mode uses. */ /* Which member(s) of `struct termios' a mode uses. */
enum mode_type { enum mode_type {
/* Do NOT change the order or values, as mode_type_flag()
* depends on them. */
control, input, output, local, combination control, input, output, local, combination
}; };
@ -199,156 +196,159 @@ static const char stty_dec [] = "dec";
/* Each mode. */ /* Each mode. */
struct mode_info { struct mode_info {
const char *name; /* Name given on command line. */ const char *name; /* Name given on command line. */
enum mode_type type; /* Which structure element to change. */ /* enum mode_type type; */
char type; /* Which structure element to change. */
char flags; /* Setting and display options. */ char flags; /* Setting and display options. */
unsigned short mask; /* Other bits to turn off for this mode. */
unsigned long bits; /* Bits to set for this mode. */ unsigned long bits; /* Bits to set for this mode. */
unsigned long mask; /* Other bits to turn off for this mode. */
}; };
#define MI_ENTRY(N,T,F,B,M) { N, T, F, M, B }
static const struct mode_info mode_info[] = { static const struct mode_info mode_info[] = {
{"parenb", control, REV, PARENB, 0 }, MI_ENTRY("parenb", control, REV, PARENB, 0 ),
{"parodd", control, REV, PARODD, 0 }, MI_ENTRY("parodd", control, REV, PARODD, 0 ),
{"cs5", control, 0, CS5, CSIZE}, MI_ENTRY("cs5", control, 0, CS5, CSIZE),
{"cs6", control, 0, CS6, CSIZE}, MI_ENTRY("cs6", control, 0, CS6, CSIZE),
{"cs7", control, 0, CS7, CSIZE}, MI_ENTRY("cs7", control, 0, CS7, CSIZE),
{"cs8", control, 0, CS8, CSIZE}, MI_ENTRY("cs8", control, 0, CS8, CSIZE),
{"hupcl", control, REV, HUPCL, 0 }, MI_ENTRY("hupcl", control, REV, HUPCL, 0 ),
{"hup", control, REV | OMIT, HUPCL, 0 }, MI_ENTRY("hup", control, REV | OMIT, HUPCL, 0 ),
{"cstopb", control, REV, CSTOPB, 0 }, MI_ENTRY("cstopb", control, REV, CSTOPB, 0 ),
{"cread", control, SANE_SET | REV, CREAD, 0 }, MI_ENTRY("cread", control, SANE_SET | REV, CREAD, 0 ),
{"clocal", control, REV, CLOCAL, 0 }, MI_ENTRY("clocal", control, REV, CLOCAL, 0 ),
#ifdef CRTSCTS #ifdef CRTSCTS
{"crtscts", control, REV, CRTSCTS, 0 }, MI_ENTRY("crtscts", control, REV, CRTSCTS, 0 ),
#endif #endif
{"ignbrk", input, SANE_UNSET | REV, IGNBRK, 0 }, MI_ENTRY("ignbrk", input, SANE_UNSET | REV, IGNBRK, 0 ),
{"brkint", input, SANE_SET | REV, BRKINT, 0 }, MI_ENTRY("brkint", input, SANE_SET | REV, BRKINT, 0 ),
{"ignpar", input, REV, IGNPAR, 0 }, MI_ENTRY("ignpar", input, REV, IGNPAR, 0 ),
{"parmrk", input, REV, PARMRK, 0 }, MI_ENTRY("parmrk", input, REV, PARMRK, 0 ),
{"inpck", input, REV, INPCK, 0 }, MI_ENTRY("inpck", input, REV, INPCK, 0 ),
{"istrip", input, REV, ISTRIP, 0 }, MI_ENTRY("istrip", input, REV, ISTRIP, 0 ),
{"inlcr", input, SANE_UNSET | REV, INLCR, 0 }, MI_ENTRY("inlcr", input, SANE_UNSET | REV, INLCR, 0 ),
{"igncr", input, SANE_UNSET | REV, IGNCR, 0 }, MI_ENTRY("igncr", input, SANE_UNSET | REV, IGNCR, 0 ),
{"icrnl", input, SANE_SET | REV, ICRNL, 0 }, MI_ENTRY("icrnl", input, SANE_SET | REV, ICRNL, 0 ),
{"ixon", input, REV, IXON, 0 }, MI_ENTRY("ixon", input, REV, IXON, 0 ),
{"ixoff", input, SANE_UNSET | REV, IXOFF, 0 }, MI_ENTRY("ixoff", input, SANE_UNSET | REV, IXOFF, 0 ),
{"tandem", input, REV | OMIT, IXOFF, 0 }, MI_ENTRY("tandem", input, REV | OMIT, IXOFF, 0 ),
#ifdef IUCLC #ifdef IUCLC
{"iuclc", input, SANE_UNSET | REV, IUCLC, 0 }, MI_ENTRY("iuclc", input, SANE_UNSET | REV, IUCLC, 0 ),
#endif #endif
#ifdef IXANY #ifdef IXANY
{"ixany", input, SANE_UNSET | REV, IXANY, 0 }, MI_ENTRY("ixany", input, SANE_UNSET | REV, IXANY, 0 ),
#endif #endif
#ifdef IMAXBEL #ifdef IMAXBEL
{"imaxbel", input, SANE_SET | REV, IMAXBEL, 0 }, MI_ENTRY("imaxbel", input, SANE_SET | REV, IMAXBEL, 0 ),
#endif #endif
{"opost", output, SANE_SET | REV, OPOST, 0 }, MI_ENTRY("opost", output, SANE_SET | REV, OPOST, 0 ),
#ifdef OLCUC #ifdef OLCUC
{"olcuc", output, SANE_UNSET | REV, OLCUC, 0 }, MI_ENTRY("olcuc", output, SANE_UNSET | REV, OLCUC, 0 ),
#endif #endif
#ifdef OCRNL #ifdef OCRNL
{"ocrnl", output, SANE_UNSET | REV, OCRNL, 0 }, MI_ENTRY("ocrnl", output, SANE_UNSET | REV, OCRNL, 0 ),
#endif #endif
#ifdef ONLCR #ifdef ONLCR
{"onlcr", output, SANE_SET | REV, ONLCR, 0 }, MI_ENTRY("onlcr", output, SANE_SET | REV, ONLCR, 0 ),
#endif #endif
#ifdef ONOCR #ifdef ONOCR
{"onocr", output, SANE_UNSET | REV, ONOCR, 0 }, MI_ENTRY("onocr", output, SANE_UNSET | REV, ONOCR, 0 ),
#endif #endif
#ifdef ONLRET #ifdef ONLRET
{"onlret", output, SANE_UNSET | REV, ONLRET, 0 }, MI_ENTRY("onlret", output, SANE_UNSET | REV, ONLRET, 0 ),
#endif #endif
#ifdef OFILL #ifdef OFILL
{"ofill", output, SANE_UNSET | REV, OFILL, 0 }, MI_ENTRY("ofill", output, SANE_UNSET | REV, OFILL, 0 ),
#endif #endif
#ifdef OFDEL #ifdef OFDEL
{"ofdel", output, SANE_UNSET | REV, OFDEL, 0 }, MI_ENTRY("ofdel", output, SANE_UNSET | REV, OFDEL, 0 ),
#endif #endif
#ifdef NLDLY #ifdef NLDLY
{"nl1", output, SANE_UNSET, NL1, NLDLY}, MI_ENTRY("nl1", output, SANE_UNSET, NL1, NLDLY),
{"nl0", output, SANE_SET, NL0, NLDLY}, MI_ENTRY("nl0", output, SANE_SET, NL0, NLDLY),
#endif #endif
#ifdef CRDLY #ifdef CRDLY
{"cr3", output, SANE_UNSET, CR3, CRDLY}, MI_ENTRY("cr3", output, SANE_UNSET, CR3, CRDLY),
{"cr2", output, SANE_UNSET, CR2, CRDLY}, MI_ENTRY("cr2", output, SANE_UNSET, CR2, CRDLY),
{"cr1", output, SANE_UNSET, CR1, CRDLY}, MI_ENTRY("cr1", output, SANE_UNSET, CR1, CRDLY),
{"cr0", output, SANE_SET, CR0, CRDLY}, MI_ENTRY("cr0", output, SANE_SET, CR0, CRDLY),
#endif #endif
#ifdef TABDLY #ifdef TABDLY
{"tab3", output, SANE_UNSET, TAB3, TABDLY}, MI_ENTRY("tab3", output, SANE_UNSET, TAB3, TABDLY),
{"tab2", output, SANE_UNSET, TAB2, TABDLY}, MI_ENTRY("tab2", output, SANE_UNSET, TAB2, TABDLY),
{"tab1", output, SANE_UNSET, TAB1, TABDLY}, MI_ENTRY("tab1", output, SANE_UNSET, TAB1, TABDLY),
{"tab0", output, SANE_SET, TAB0, TABDLY}, MI_ENTRY("tab0", output, SANE_SET, TAB0, TABDLY),
#else #else
# ifdef OXTABS # ifdef OXTABS
{"tab3", output, SANE_UNSET, OXTABS, 0 }, MI_ENTRY("tab3", output, SANE_UNSET, OXTABS, 0 ),
# endif # endif
#endif #endif
#ifdef BSDLY #ifdef BSDLY
{"bs1", output, SANE_UNSET, BS1, BSDLY}, MI_ENTRY("bs1", output, SANE_UNSET, BS1, BSDLY),
{"bs0", output, SANE_SET, BS0, BSDLY}, MI_ENTRY("bs0", output, SANE_SET, BS0, BSDLY),
#endif #endif
#ifdef VTDLY #ifdef VTDLY
{"vt1", output, SANE_UNSET, VT1, VTDLY}, MI_ENTRY("vt1", output, SANE_UNSET, VT1, VTDLY),
{"vt0", output, SANE_SET, VT0, VTDLY}, MI_ENTRY("vt0", output, SANE_SET, VT0, VTDLY),
#endif #endif
#ifdef FFDLY #ifdef FFDLY
{"ff1", output, SANE_UNSET, FF1, FFDLY}, MI_ENTRY("ff1", output, SANE_UNSET, FF1, FFDLY),
{"ff0", output, SANE_SET, FF0, FFDLY}, MI_ENTRY("ff0", output, SANE_SET, FF0, FFDLY),
#endif #endif
{"isig", local, SANE_SET | REV, ISIG, 0 }, MI_ENTRY("isig", local, SANE_SET | REV, ISIG, 0 ),
{"icanon", local, SANE_SET | REV, ICANON, 0 }, MI_ENTRY("icanon", local, SANE_SET | REV, ICANON, 0 ),
#ifdef IEXTEN #ifdef IEXTEN
{"iexten", local, SANE_SET | REV, IEXTEN, 0 }, MI_ENTRY("iexten", local, SANE_SET | REV, IEXTEN, 0 ),
#endif #endif
{"echo", local, SANE_SET | REV, ECHO, 0 }, MI_ENTRY("echo", local, SANE_SET | REV, ECHO, 0 ),
{"echoe", local, SANE_SET | REV, ECHOE, 0 }, MI_ENTRY("echoe", local, SANE_SET | REV, ECHOE, 0 ),
{"crterase", local, REV | OMIT, ECHOE, 0 }, MI_ENTRY("crterase", local, REV | OMIT, ECHOE, 0 ),
{"echok", local, SANE_SET | REV, ECHOK, 0 }, MI_ENTRY("echok", local, SANE_SET | REV, ECHOK, 0 ),
{"echonl", local, SANE_UNSET | REV, ECHONL, 0 }, MI_ENTRY("echonl", local, SANE_UNSET | REV, ECHONL, 0 ),
{"noflsh", local, SANE_UNSET | REV, NOFLSH, 0 }, MI_ENTRY("noflsh", local, SANE_UNSET | REV, NOFLSH, 0 ),
#ifdef XCASE #ifdef XCASE
{"xcase", local, SANE_UNSET | REV, XCASE, 0 }, MI_ENTRY("xcase", local, SANE_UNSET | REV, XCASE, 0 ),
#endif #endif
#ifdef TOSTOP #ifdef TOSTOP
{"tostop", local, SANE_UNSET | REV, TOSTOP, 0 }, MI_ENTRY("tostop", local, SANE_UNSET | REV, TOSTOP, 0 ),
#endif #endif
#ifdef ECHOPRT #ifdef ECHOPRT
{"echoprt", local, SANE_UNSET | REV, ECHOPRT, 0 }, MI_ENTRY("echoprt", local, SANE_UNSET | REV, ECHOPRT, 0 ),
{"prterase", local, REV | OMIT, ECHOPRT, 0 }, MI_ENTRY("prterase", local, REV | OMIT, ECHOPRT, 0 ),
#endif #endif
#ifdef ECHOCTL #ifdef ECHOCTL
{"echoctl", local, SANE_SET | REV, ECHOCTL, 0 }, MI_ENTRY("echoctl", local, SANE_SET | REV, ECHOCTL, 0 ),
{"ctlecho", local, REV | OMIT, ECHOCTL, 0 }, MI_ENTRY("ctlecho", local, REV | OMIT, ECHOCTL, 0 ),
#endif #endif
#ifdef ECHOKE #ifdef ECHOKE
{"echoke", local, SANE_SET | REV, ECHOKE, 0 }, MI_ENTRY("echoke", local, SANE_SET | REV, ECHOKE, 0 ),
{"crtkill", local, REV | OMIT, ECHOKE, 0 }, MI_ENTRY("crtkill", local, REV | OMIT, ECHOKE, 0 ),
#endif #endif
{evenp, combination, REV | OMIT, 0, 0 }, MI_ENTRY(evenp, combination, REV | OMIT, 0, 0 ),
{parity, combination, REV | OMIT, 0, 0 }, MI_ENTRY(parity, combination, REV | OMIT, 0, 0 ),
{stty_oddp, combination, REV | OMIT, 0, 0 }, MI_ENTRY(stty_oddp, combination, REV | OMIT, 0, 0 ),
{stty_nl, combination, REV | OMIT, 0, 0 }, MI_ENTRY(stty_nl, combination, REV | OMIT, 0, 0 ),
{stty_ek, combination, OMIT, 0, 0 }, MI_ENTRY(stty_ek, combination, OMIT, 0, 0 ),
{stty_sane, combination, OMIT, 0, 0 }, MI_ENTRY(stty_sane, combination, OMIT, 0, 0 ),
{cooked, combination, REV | OMIT, 0, 0 }, MI_ENTRY(cooked, combination, REV | OMIT, 0, 0 ),
{raw, combination, REV | OMIT, 0, 0 }, MI_ENTRY(raw, combination, REV | OMIT, 0, 0 ),
{stty_pass8, combination, REV | OMIT, 0, 0 }, MI_ENTRY(stty_pass8, combination, REV | OMIT, 0, 0 ),
{litout, combination, REV | OMIT, 0, 0 }, MI_ENTRY(litout, combination, REV | OMIT, 0, 0 ),
{cbreak, combination, REV | OMIT, 0, 0 }, MI_ENTRY(cbreak, combination, REV | OMIT, 0, 0 ),
#ifdef IXANY #ifdef IXANY
{decctlq, combination, REV | OMIT, 0, 0 }, MI_ENTRY(decctlq, combination, REV | OMIT, 0, 0 ),
#endif #endif
#if defined (TABDLY) || defined (OXTABS) #if defined (TABDLY) || defined (OXTABS)
{stty_tabs, combination, REV | OMIT, 0, 0 }, MI_ENTRY(stty_tabs, combination, REV | OMIT, 0, 0 ),
#endif #endif
#if defined(XCASE) && defined(IUCLC) && defined(OLCUC) #if defined(XCASE) && defined(IUCLC) && defined(OLCUC)
{stty_lcase, combination, REV | OMIT, 0, 0 }, MI_ENTRY(stty_lcase, combination, REV | OMIT, 0, 0 ),
{stty_LCASE, combination, REV | OMIT, 0, 0 }, MI_ENTRY(stty_LCASE, combination, REV | OMIT, 0, 0 ),
#endif #endif
{stty_crt, combination, OMIT, 0, 0 }, MI_ENTRY(stty_crt, combination, OMIT, 0, 0 ),
{stty_dec, combination, OMIT, 0, 0 }, MI_ENTRY(stty_dec, combination, OMIT, 0, 0 ),
}; };
static const int NUM_mode_info = static const int NUM_mode_info =
@ -359,7 +359,7 @@ static const int NUM_mode_info =
struct control_info { struct control_info {
const char *name; /* Name given on command line. */ const char *name; /* Name given on command line. */
unsigned char saneval; /* Value to set for `stty sane'. */ unsigned char saneval; /* Value to set for `stty sane'. */
int offset; /* Offset in c_cc. */ unsigned char offset; /* Offset in c_cc. */
}; };
/* Control characters. */ /* Control characters. */
@ -408,7 +408,6 @@ static const int NUM_control_info =
static const char * visible(unsigned int ch); static const char * visible(unsigned int ch);
static unsigned long baud_to_value(speed_t speed);
static int recover_mode(char *arg, struct termios *mode); static int recover_mode(char *arg, struct termios *mode);
static int screen_columns(void); static int screen_columns(void);
static int set_mode(const struct mode_info *info, static int set_mode(const struct mode_info *info,
@ -416,12 +415,11 @@ static int set_mode(const struct mode_info *info,
static speed_t string_to_baud(const char *arg); static speed_t string_to_baud(const char *arg);
static tcflag_t* mode_type_flag(enum mode_type type, struct termios *mode); static tcflag_t* mode_type_flag(enum mode_type type, struct termios *mode);
static void display_all(struct termios *mode, int fd, static void display_all(struct termios *mode, int fd,
const char *device_name); const char *device_name);
static void display_changed(struct termios *mode); static void display_changed(struct termios *mode, int fd,
static void display_recoverable(struct termios *mode); const char *device_name);
static void display_settings(enum output_type output_type, static void display_recoverable(struct termios *mode, int fd,
struct termios *mode, int fd, const char *device_name);
const char *device_name);
static void display_speed(struct termios *mode, int fancy); static void display_speed(struct termios *mode, int fancy);
static void display_window_size(int fancy, int fd, static void display_window_size(int fancy, int fd,
const char *device_name); const char *device_name);
@ -479,7 +477,7 @@ extern int main(int argc, char **argv)
#endif #endif
{ {
struct termios mode; struct termios mode;
enum output_type output_type; void (*output_func)(struct termios *, int, const char *);
int optc; int optc;
int require_set_attr; int require_set_attr;
int speed_was_set; int speed_was_set;
@ -491,7 +489,7 @@ extern int main(int argc, char **argv)
int fd; int fd;
const char *device_name; const char *device_name;
output_type = changed; output_func = display_changed;
verbose_output = 0; verbose_output = 0;
recoverable_output = 0; recoverable_output = 0;
@ -502,17 +500,17 @@ extern int main(int argc, char **argv)
switch (optc) { switch (optc) {
case 'a': case 'a':
verbose_output = 1; verbose_output = 1;
output_type = all; output_func = display_all;
break; break;
case 'g': case 'g':
recoverable_output = 1; recoverable_output = 1;
output_type = recoverable; output_func = display_recoverable;
break; break;
case 'F': case 'F':
if (file_name) if (file_name)
error_msg_and_die("only one device may be specified"); bb_error_msg_and_die("only one device may be specified");
file_name = optarg; file_name = optarg;
break; break;
@ -529,12 +527,12 @@ extern int main(int argc, char **argv)
noargs = 0; noargs = 0;
/* Specifying both -a and -g gets an error. */ /* Specifying both -a and -g gets an error. */
if (verbose_output && recoverable_output) if (verbose_output & recoverable_output)
error_msg_and_die ("verbose and stty-readable output styles are mutually exclusive"); bb_error_msg_and_die ("verbose and stty-readable output styles are mutually exclusive");
/* Specifying any other arguments with -a or -g gets an error. */ /* Specifying any other arguments with -a or -g gets an error. */
if (!noargs && (verbose_output || recoverable_output)) if (~noargs & (verbose_output | recoverable_output))
error_msg_and_die ("modes may not be set when specifying an output style"); bb_error_msg_and_die ("modes may not be set when specifying an output style");
/* FIXME: it'd be better not to open the file until we've verified /* FIXME: it'd be better not to open the file until we've verified
that all arguments are valid. Otherwise, we could end up doing that all arguments are valid. Otherwise, we could end up doing
@ -547,26 +545,26 @@ extern int main(int argc, char **argv)
device_name = file_name; device_name = file_name;
fd = open(device_name, O_RDONLY | O_NONBLOCK); fd = open(device_name, O_RDONLY | O_NONBLOCK);
if (fd < 0) if (fd < 0)
perror_msg_and_die("%s", device_name); bb_perror_msg_and_die("%s", device_name);
if ((fdflags = fcntl(fd, F_GETFL)) == -1 if ((fdflags = fcntl(fd, F_GETFL)) == -1
|| fcntl(fd, F_SETFL, fdflags & ~O_NONBLOCK) < 0) || fcntl(fd, F_SETFL, fdflags & ~O_NONBLOCK) < 0)
perror_msg_and_die("%s: couldn't reset non-blocking mode", bb_perror_msg_and_die("%s: couldn't reset non-blocking mode",
device_name); device_name);
} else { } else {
fd = 0; fd = 0;
device_name = "standard input"; device_name = bb_msg_standard_input;
} }
/* Initialize to all zeroes so there is no risk memcmp will report a /* Initialize to all zeroes so there is no risk memcmp will report a
spurious difference in an uninitialized portion of the structure. */ spurious difference in an uninitialized portion of the structure. */
memset(&mode, 0, sizeof(mode)); memset(&mode, 0, sizeof(mode));
if (tcgetattr(fd, &mode)) if (tcgetattr(fd, &mode))
perror_msg_and_die("%s", device_name); bb_perror_msg_and_die("%s", device_name);
if (verbose_output || recoverable_output || noargs) { if (verbose_output | recoverable_output | noargs) {
max_col = screen_columns(); max_col = screen_columns();
current_col = 0; current_col = 0;
display_settings(output_type, &mode, fd, device_name); output_func(&mode, fd, device_name);
return EXIT_SUCCESS; return EXIT_SUCCESS;
} }
@ -610,13 +608,13 @@ extern int main(int argc, char **argv)
} }
if (match_found == 0 && reversed) if (match_found == 0 && reversed)
error_msg_and_die("invalid argument `%s'", --argv[k]); bb_error_msg_and_die("invalid argument `%s'", --argv[k]);
if (match_found == 0) if (match_found == 0)
for (i = 0; i < NUM_control_info; ++i) for (i = 0; i < NUM_control_info; ++i)
if (STREQ(argv[k], control_info[i].name)) { if (STREQ(argv[k], control_info[i].name)) {
if (k == argc - 1) if (k == argc - 1)
error_msg_and_die("missing argument to `%s'", argv[k]); bb_error_msg_and_die("missing argument to `%s'", argv[k]);
match_found = 1; match_found = 1;
++k; ++k;
set_control_char(&control_info[i], argv[k], &mode); set_control_char(&control_info[i], argv[k], &mode);
@ -627,14 +625,14 @@ extern int main(int argc, char **argv)
if (match_found == 0) { if (match_found == 0) {
if (STREQ(argv[k], "ispeed")) { if (STREQ(argv[k], "ispeed")) {
if (k == argc - 1) if (k == argc - 1)
error_msg_and_die("missing argument to `%s'", argv[k]); bb_error_msg_and_die("missing argument to `%s'", argv[k]);
++k; ++k;
set_speed(input_speed, argv[k], &mode); set_speed(input_speed, argv[k], &mode);
speed_was_set = 1; speed_was_set = 1;
require_set_attr = 1; require_set_attr = 1;
} else if (STREQ(argv[k], "ospeed")) { } else if (STREQ(argv[k], "ospeed")) {
if (k == argc - 1) if (k == argc - 1)
error_msg_and_die("missing argument to `%s'", argv[k]); bb_error_msg_and_die("missing argument to `%s'", argv[k]);
++k; ++k;
set_speed(output_speed, argv[k], &mode); set_speed(output_speed, argv[k], &mode);
speed_was_set = 1; speed_was_set = 1;
@ -643,16 +641,16 @@ extern int main(int argc, char **argv)
#ifdef TIOCGWINSZ #ifdef TIOCGWINSZ
else if (STREQ(argv[k], "rows")) { else if (STREQ(argv[k], "rows")) {
if (k == argc - 1) if (k == argc - 1)
error_msg_and_die("missing argument to `%s'", argv[k]); bb_error_msg_and_die("missing argument to `%s'", argv[k]);
++k; ++k;
set_window_size((int) parse_number(argv[k], stty_suffixes), set_window_size((int) bb_xparse_number(argv[k], stty_suffixes),
-1, fd, device_name); -1, fd, device_name);
} else if (STREQ(argv[k], "cols") || STREQ(argv[k], "columns")) { } else if (STREQ(argv[k], "cols") || STREQ(argv[k], "columns")) {
if (k == argc - 1) if (k == argc - 1)
error_msg_and_die("missing argument to `%s'", argv[k]); bb_error_msg_and_die("missing argument to `%s'", argv[k]);
++k; ++k;
set_window_size(-1, set_window_size(-1,
(int) parse_number(argv[k], stty_suffixes), (int) bb_xparse_number(argv[k], stty_suffixes),
fd, device_name); fd, device_name);
} else if (STREQ(argv[k], "size")) { } else if (STREQ(argv[k], "size")) {
max_col = screen_columns(); max_col = screen_columns();
@ -663,9 +661,9 @@ extern int main(int argc, char **argv)
#ifdef HAVE_C_LINE #ifdef HAVE_C_LINE
else if (STREQ(argv[k], "line")) { else if (STREQ(argv[k], "line")) {
if (k == argc - 1) if (k == argc - 1)
error_msg_and_die("missing argument to `%s'", argv[k]); bb_error_msg_and_die("missing argument to `%s'", argv[k]);
++k; ++k;
mode.c_line = parse_number(argv[k], stty_suffixes); mode.c_line = bb_xparse_number(argv[k], stty_suffixes);
require_set_attr = 1; require_set_attr = 1;
} }
#endif #endif
@ -679,7 +677,7 @@ extern int main(int argc, char **argv)
speed_was_set = 1; speed_was_set = 1;
require_set_attr = 1; require_set_attr = 1;
} else } else
error_msg_and_die("invalid argument `%s'", argv[k]); bb_error_msg_and_die("invalid argument `%s'", argv[k]);
} }
} }
@ -687,7 +685,7 @@ extern int main(int argc, char **argv)
struct termios new_mode; struct termios new_mode;
if (tcsetattr(fd, TCSADRAIN, &mode)) if (tcsetattr(fd, TCSADRAIN, &mode))
perror_msg_and_die("%s", device_name); bb_perror_msg_and_die("%s", device_name);
/* POSIX (according to Zlotnick's book) tcsetattr returns zero if /* POSIX (according to Zlotnick's book) tcsetattr returns zero if
it performs *any* of the requested operations. This means it it performs *any* of the requested operations. This means it
@ -700,7 +698,7 @@ extern int main(int argc, char **argv)
spurious difference in an uninitialized portion of the structure. */ spurious difference in an uninitialized portion of the structure. */
memset(&new_mode, 0, sizeof(new_mode)); memset(&new_mode, 0, sizeof(new_mode));
if (tcgetattr(fd, &new_mode)) if (tcgetattr(fd, &new_mode))
perror_msg_and_die("%s", device_name); bb_perror_msg_and_die("%s", device_name);
/* Normally, one shouldn't use memcmp to compare structures that /* Normally, one shouldn't use memcmp to compare structures that
may have `holes' containing uninitialized data, but we have been may have `holes' containing uninitialized data, but we have been
@ -723,7 +721,7 @@ extern int main(int argc, char **argv)
new_mode.c_cflag &= (~CIBAUD); new_mode.c_cflag &= (~CIBAUD);
if (speed_was_set || memcmp(&mode, &new_mode, sizeof(mode)) != 0) if (speed_was_set || memcmp(&mode, &new_mode, sizeof(mode)) != 0)
#endif #endif
error_msg_and_die ("%s: unable to perform all requested operations", bb_error_msg_and_die ("%s: unable to perform all requested operations",
device_name); device_name);
} }
} }
@ -896,9 +894,9 @@ set_mode(const struct mode_info *info, int reversed, struct termios *mode)
#endif #endif
} }
} else if (reversed) } else if (reversed)
*bitsp = *bitsp & ~info->mask & ~info->bits; *bitsp = *bitsp & ~((unsigned long)info->mask) & ~info->bits;
else else
*bitsp = (*bitsp & ~info->mask) | info->bits; *bitsp = (*bitsp & ~((unsigned long)info->mask)) | info->bits;
return 1; return 1;
} }
@ -910,7 +908,7 @@ set_control_char(const struct control_info *info, const char *arg,
unsigned char value; unsigned char value;
if (info->name == stty_min || info->name == stty_time) if (info->name == stty_min || info->name == stty_time)
value = parse_number(arg, stty_suffixes); value = bb_xparse_number(arg, stty_suffixes);
else if (arg[0] == '\0' || arg[1] == '\0') else if (arg[0] == '\0' || arg[1] == '\0')
value = arg[0]; value = arg[0];
else if (STREQ(arg, "^-") || STREQ(arg, "undef")) else if (STREQ(arg, "^-") || STREQ(arg, "undef"))
@ -921,7 +919,7 @@ set_control_char(const struct control_info *info, const char *arg,
else else
value = arg[1] & ~0140; /* Non-letters get weird results. */ value = arg[1] & ~0140; /* Non-letters get weird results. */
} else } else
value = parse_number(arg, stty_suffixes); value = bb_xparse_number(arg, stty_suffixes);
mode->c_cc[info->offset] = value; mode->c_cc[info->offset] = value;
} }
@ -931,10 +929,13 @@ set_speed(enum speed_setting type, const char *arg, struct termios *mode)
speed_t baud; speed_t baud;
baud = string_to_baud(arg); baud = string_to_baud(arg);
if (type == input_speed || type == both_speeds)
if (type != output_speed) { /* either input or both */
cfsetispeed(mode, baud); cfsetispeed(mode, baud);
if (type == output_speed || type == both_speeds) }
if (type != input_speed) { /* either output or both */
cfsetospeed(mode, baud); cfsetospeed(mode, baud);
}
} }
#ifdef TIOCGWINSZ #ifdef TIOCGWINSZ
@ -953,7 +954,7 @@ set_window_size(int rows, int cols, int fd, const char *device_name)
if (get_win_size(fd, &win)) { if (get_win_size(fd, &win)) {
if (errno != EINVAL) if (errno != EINVAL)
perror_msg_and_die("%s", device_name); bb_perror_msg_and_die("%s", device_name);
memset(&win, 0, sizeof(win)); memset(&win, 0, sizeof(win));
} }
@ -975,32 +976,28 @@ set_window_size(int rows, int cols, int fd, const char *device_name)
ttysz.ts_lines = win.ws_row; ttysz.ts_lines = win.ws_row;
ttysz.ts_cols = win.ws_col; ttysz.ts_cols = win.ws_col;
win.ws_row = 1; win.ws_row = win.ws_col = 1;
win.ws_col = 1;
if (ioctl(fd, TIOCSWINSZ, (char *) &win)) if ((ioctl(fd, TIOCSWINSZ, (char *) &win) != 0)
perror_msg_and_die("%s", device_name); || (ioctl(fd, TIOCSSIZE, (char *) &ttysz) != 0)) {
bb_perror_msg_and_die("%s", device_name);
if (ioctl(fd, TIOCSSIZE, (char *) &ttysz))
perror_msg_and_die("%s", device_name);
return; return;
} }
# endif # endif
if (ioctl(fd, TIOCSWINSZ, (char *) &win)) if (ioctl(fd, TIOCSWINSZ, (char *) &win))
perror_msg_and_die("%s", device_name); bb_perror_msg_and_die("%s", device_name);
} }
static void display_window_size(int fancy, int fd, const char *device_name) static void display_window_size(int fancy, int fd, const char *device_name)
{ {
const char *fmt_str = "%s" "\0" "%s: no size information for this device";
struct winsize win; struct winsize win;
if (get_win_size(fd, &win)) { if (get_win_size(fd, &win)) {
if (errno != EINVAL) if ((errno != EINVAL) || ((fmt_str += 2), !fancy)) {
perror_msg_and_die("%s", device_name); bb_perror_msg_and_die(fmt_str, device_name);
if (!fancy) }
perror_msg_and_die("%s: no size information for this device",
device_name);
} else { } else {
wrapf(fancy ? "rows %d; columns %d;" : "%d %d\n", wrapf(fancy ? "rows %d; columns %d;" : "%d %d\n",
win.ws_row, win.ws_col); win.ws_row, win.ws_col);
@ -1012,6 +1009,9 @@ static void display_window_size(int fancy, int fd, const char *device_name)
static int screen_columns(void) static int screen_columns(void)
{ {
int columns;
const char *s;
#ifdef TIOCGWINSZ #ifdef TIOCGWINSZ
struct winsize win; struct winsize win;
@ -1025,51 +1025,29 @@ static int screen_columns(void)
return win.ws_col; return win.ws_col;
#endif #endif
if (getenv("COLUMNS")) columns = 80;
return atoi(getenv("COLUMNS")); if ((s = getenv("COLUMNS"))) {
return 80; columns = atoi(s);
}
return columns;
} }
static tcflag_t *mode_type_flag(enum mode_type type, struct termios *mode) static tcflag_t *mode_type_flag(enum mode_type type, struct termios *mode)
{ {
switch (type) { static const unsigned char tcflag_offsets[] = {
case control: offsetof(struct termios, c_cflag), /* control */
return &mode->c_cflag; offsetof(struct termios, c_iflag), /* input */
offsetof(struct termios, c_oflag), /* output */
offsetof(struct termios, c_lflag) /* local */
};
case input: if (((unsigned int) type) <= local) {
return &mode->c_iflag; return (tcflag_t *)(((char *) mode) + tcflag_offsets[(int)type]);
case output:
return &mode->c_oflag;
case local:
return &mode->c_lflag;
default: /* combination: */
return NULL;
} }
return NULL;
} }
static void static void display_changed(struct termios *mode, int fd, const char *device_name)
display_settings(enum output_type output_type, struct termios *mode,
int fd, const char *device_name)
{
switch (output_type) {
case changed:
display_changed(mode);
break;
case all:
display_all(mode, fd, device_name);
break;
case recoverable:
display_recoverable(mode);
break;
}
}
static void display_changed(struct termios *mode)
{ {
int i; int i;
int empty_line; int empty_line;
@ -1206,18 +1184,25 @@ display_all(struct termios *mode, int fd, const char *device_name)
static void display_speed(struct termios *mode, int fancy) static void display_speed(struct termios *mode, int fancy)
{ {
if (cfgetispeed(mode) == 0 || cfgetispeed(mode) == cfgetospeed(mode)) unsigned long ispeed, ospeed;
wrapf(fancy ? "speed %lu baud;" : "%lu\n", const char *fmt_str =
baud_to_value(cfgetospeed(mode))); "%lu %lu\n\0" "ispeed %lu baud; ospeed %lu baud;\0"
else "%lu\n\0" "\0\0\0\0" "speed %lu baud;";
wrapf(fancy ? "ispeed %lu baud; ospeed %lu baud;" : "%lu %lu\n",
baud_to_value(cfgetispeed(mode)), ospeed = ispeed = cfgetispeed(mode);
baud_to_value(cfgetospeed(mode))); if (ispeed == 0 || ispeed == (ospeed = cfgetospeed(mode))) {
ispeed = ospeed; /* in case ispeed was 0 */
fmt_str += 43;
}
if (fancy) {
fmt_str += 9;
}
wrapf(fmt_str, bb_baud_to_value(ispeed), bb_baud_to_value(ospeed));
if (!fancy) if (!fancy)
current_col = 0; current_col = 0;
} }
static void display_recoverable(struct termios *mode) static void display_recoverable(struct termios *mode, int fd, const char *device_name)
{ {
int i; int i;
@ -1259,62 +1244,9 @@ static int recover_mode(char *arg, struct termios *mode)
return 1; return 1;
} }
struct speed_map {
speed_t speed; /* Internal form. */
unsigned long value; /* Numeric value. */
};
static const struct speed_map speeds[] = {
{B0, 0},
{B50, 50},
{B75, 75},
{B110, 110},
{B134, 134},
{B150, 150},
{B200, 200},
{B300, 300},
{B600, 600},
{B1200, 1200},
{B1800, 1800},
{B2400, 2400},
{B4800, 4800},
{B9600, 9600},
{B19200, 19200},
{B38400, 38400},
#ifdef B57600
{B57600, 57600},
#endif
#ifdef B115200
{B115200, 115200},
#endif
#ifdef B230400
{B230400, 230400},
#endif
#ifdef B460800
{B460800, 460800},
#endif
};
static const int NUM_SPEEDS = (sizeof(speeds) / sizeof(struct speed_map));
static speed_t string_to_baud(const char *arg) static speed_t string_to_baud(const char *arg)
{ {
int i; return bb_value_to_baud(bb_xparse_number(arg, 0));
for (i = 0; i < NUM_SPEEDS; ++i)
if (parse_number(arg, 0) == speeds[i].value)
return speeds[i].speed;
return (speed_t) - 1;
}
static unsigned long baud_to_value(speed_t speed)
{
int i;
for (i = 0; i < NUM_SPEEDS; ++i)
if (speed == speeds[i].speed)
return speeds[i].value;
return 0;
} }
static void sane_mode(struct termios *mode) static void sane_mode(struct termios *mode)
@ -1333,10 +1265,12 @@ static void sane_mode(struct termios *mode)
for (i = 0; i < NUM_mode_info; ++i) { for (i = 0; i < NUM_mode_info; ++i) {
if (mode_info[i].flags & SANE_SET) { if (mode_info[i].flags & SANE_SET) {
bitsp = mode_type_flag(mode_info[i].type, mode); bitsp = mode_type_flag(mode_info[i].type, mode);
*bitsp = (*bitsp & ~mode_info[i].mask) | mode_info[i].bits; *bitsp = (*bitsp & ~((unsigned long)mode_info[i].mask))
| mode_info[i].bits;
} else if (mode_info[i].flags & SANE_UNSET) { } else if (mode_info[i].flags & SANE_UNSET) {
bitsp = mode_type_flag(mode_info[i].type, mode); bitsp = mode_type_flag(mode_info[i].type, mode);
*bitsp = *bitsp & ~mode_info[i].mask & ~mode_info[i].bits; *bitsp = *bitsp & ~((unsigned long)mode_info[i].mask)
& ~mode_info[i].bits;
} }
} }
} }
@ -1349,47 +1283,32 @@ static const char *visible(unsigned int ch)
static char buf[10]; static char buf[10];
char *bpout = buf; char *bpout = buf;
if (ch == _POSIX_VDISABLE) if (ch == _POSIX_VDISABLE) {
return "<undef>"; return "<undef>";
}
if (ch >= 32) { if (ch >= 128) {
if (ch < 127) ch -= 128;
*bpout++ = ch; *bpout++ = 'M';
else if (ch == 127) { *bpout++ = '-';
*bpout++ = '^'; }
*bpout++ = '?';
} else { if (ch < 32) {
*bpout++ = 'M', *bpout++ = '-';
if (ch >= 128 + 32) {
if (ch < 128 + 127)
*bpout++ = ch - 128;
else {
*bpout++ = '^';
*bpout++ = '?';
}
} else {
*bpout++ = '^';
*bpout++ = ch - 128 + 64;
}
}
} else {
*bpout++ = '^'; *bpout++ = '^';
*bpout++ = ch + 64; *bpout++ = ch + 64;
} else if (ch < 127) {
*bpout++ = ch;
} else {
*bpout++ = '^';
*bpout++ = '?';
} }
*bpout = '\0'; *bpout = '\0';
return (const char *) buf; return (const char *) buf;
} }
#ifdef TEST #ifdef TEST
const char *applet_name = "stty"; const char *bb_applet_name = "stty";
#endif #endif
/*
Local Variables:
c-file-style: "linux"
c-basic-offset: 4
tab-width: 4
End:
*/

View File

@ -20,15 +20,17 @@
* *
*/ */
#include <stdio.h> /* BB_AUDIT SUSv3 N/A -- Matches GNU behavior. */
#include <stdlib.h> #include <stdlib.h>
#include <unistd.h> #include <unistd.h>
#include "busybox.h" #include "busybox.h"
extern int sync_main(int argc, char **argv) extern int sync_main(int argc, char **argv)
{ {
if (argc > 1 && **(argv + 1) == '-') bb_warn_ignoring_args(argc - 1);
show_usage();
sync(); sync();
return(EXIT_SUCCESS); return(EXIT_SUCCESS);
} }

View File

@ -2,7 +2,6 @@
/* /*
* Mini tail implementation for busybox * Mini tail implementation for busybox
* *
*
* Copyright (C) 2001 by Matt Kraai <kraai@alumni.carnegiemellon.edu> * Copyright (C) 2001 by Matt Kraai <kraai@alumni.carnegiemellon.edu>
* *
* This program is free software; you can redistribute it and/or modify * This program is free software; you can redistribute it and/or modify
@ -21,14 +20,30 @@
* *
*/ */
/* BB_AUDIT SUSv3 compliant (need fancy for -c) */
/* BB_AUDIT GNU compatible -c, -q, and -v options in 'fancy' configuration. */
/* http://www.opengroup.org/onlinepubs/007904975/utilities/tail.html */
#include <fcntl.h> /* Mar 16, 2003 Manuel Novoa III (mjn3@codepoet.org)
#include <getopt.h> *
* Pretty much rewritten to fix numerous bugs and reduce realloc() calls.
* Bugs fixed (although I may have forgotten one or two... it was pretty bad)
* 1) mixing printf/write without fflush()ing stdout
* 2) no check that any open files are present
* 3) optstring had -q taking an arg
* 4) no error checking on write in some cases, and a warning even then
* 5) q and s interaction bug
* 6) no check for lseek error
* 7) lseek attempted when count==0 even if arg was +0 (from top)
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h> #include <string.h>
#include <ctype.h> #include <ctype.h>
#include <stdlib.h>
#include <unistd.h> #include <unistd.h>
#include <sys/types.h> #include <fcntl.h>
#include <sys/stat.h>
#include "busybox.h" #include "busybox.h"
static const struct suffix_mult tail_suffixes[] = { static const struct suffix_mult tail_suffixes[] = {
@ -38,234 +53,287 @@ static const struct suffix_mult tail_suffixes[] = {
{ NULL, 0 } { NULL, 0 }
}; };
static const int BYTES = 0; static int status
static const int LINES = 1; #if EXIT_SUCCESS != 0
= EXIT_SUCCESS /* If it is 0 (paranoid check), let bss initialize it. */
#endif
;
static char *tailbuf; static void tail_xprint_header(const char *fmt, const char *filename)
static int taillen;
static int newline;
static void tailbuf_append(char *buf, int len)
{ {
tailbuf = xrealloc(tailbuf, taillen + len); /* If we get an output error, there is really no sense in continuing. */
memcpy(tailbuf + taillen, buf, len); if (dprintf(STDOUT_FILENO, fmt, filename) < 0) {
taillen += len; bb_perror_nomsg_and_die();
}
} }
static void tailbuf_trunc(void) /* len should probably be size_t */
static void tail_xbb_full_write(const char *buf, size_t len)
{ {
char *s; /* If we get a write error, there is really no sense in continuing. */
s = memchr(tailbuf, '\n', taillen); if (bb_full_write(STDOUT_FILENO, buf, len) < 0) {
memmove(tailbuf, s + 1, taillen - ((s + 1) - tailbuf)); bb_perror_nomsg_and_die();
taillen -= (s + 1) - tailbuf; }
newline = 0;
} }
static ssize_t tail_read(int fd, char *buf, size_t count)
{
ssize_t r;
if ((r = safe_read(fd, buf, count)) < 0) {
bb_perror_msg("read");
status = EXIT_FAILURE;
}
return r;
}
static const char tail_opts[] =
"fn:"
#ifdef CONFIG_FEATURE_FANCY_TAIL
"c:qs:v"
#endif
;
static const char header_fmt[] = "\n==> %s <==\n";
int tail_main(int argc, char **argv) int tail_main(int argc, char **argv)
{ {
int from_top = 0, units = LINES, count = 10, sleep_period = 1; long count = 10;
int show_headers = 0, hide_headers = 0, follow = 0; unsigned int sleep_period = 1;
int *fds, nfiles = 0, status = EXIT_SUCCESS, nread, nwrite, seen = 0; int from_top = 0;
char *s, *start, *end, buf[BUFSIZ]; int follow = 0;
int i, opt; int header_threshhold = 1;
#ifdef CONFIG_FEATURE_FANCY_TAIL
int count_bytes = 0;
#endif
if (argc >= 2) { char *tailbuf;
int line_num; size_t tailbufsize;
switch (argv[1][0]) { int taillen = 0;
case '+': int newline = 0;
from_top = 1;
/* FALLS THROUGH */ int *fds, nfiles, nread, nwrite, seen, i, opt;
case '-': char *s, *buf;
line_num = atoi(&argv[1][1]); const char *fmt;
if (line_num != 0) {
optind = 2; /* Allow legacy syntax of an initial numeric option without -n. */
count = line_num; if ((argv[1][0] == '+')
} || ((argv[1][0] == '-')
break; /* && (isdigit)(argv[1][1]) */
} && (((unsigned int)(argv[1][1] - '0')) <= 9))
) {
optind = 2;
optarg = argv[1];
goto GET_COUNT;
} }
#ifdef CONFIG_FEATURE_FANCY_TAIL while ((opt = getopt(argc, argv, tail_opts)) > 0) {
while ((opt = getopt(argc, argv, "c:fn:q:s:v")) > 0) {
#else
while ((opt = getopt(argc, argv, "fn:")) > 0) {
#endif
switch (opt) { switch (opt) {
case 'f': case 'f':
follow = 1; follow = 1;
break; break;
#ifdef CONFIG_FEATURE_FANCY_TAIL #ifdef CONFIG_FEATURE_FANCY_TAIL
case 'c': case 'c':
units = BYTES; count_bytes = 1;
/* FALLS THROUGH */ /* FALLS THROUGH */
#endif #endif
case 'n': case 'n':
count = parse_number(optarg, tail_suffixes); GET_COUNT:
if (count < 0) count = bb_xgetlarg10_sfx(optarg, tail_suffixes);
count = -count; /* Note: Leading whitespace is an error trapped above. */
if (optarg[0] == '+') if (*optarg == '+') {
from_top = 1; from_top = 1;
} else {
from_top = 0;
}
if (count < 0) {
count = -count;
}
break; break;
#ifdef CONFIG_FEATURE_FANCY_TAIL #ifdef CONFIG_FEATURE_FANCY_TAIL
case 'q': case 'q':
hide_headers = 1; header_threshhold = INT_MAX;
break; break;
case 's': case 's':
sleep_period = parse_number(optarg, 0); sleep_period =bb_xgetularg10_bnd(optarg, 0, UINT_MAX);
break; break;
case 'v': case 'v':
show_headers = 1; header_threshhold = 0;
break; break;
#endif #endif
default: default:
show_usage(); bb_show_usage();
} }
} }
/* open all the files */ /* open all the files */
fds = (int *)xmalloc(sizeof(int) * (argc - optind + 1)); fds = (int *)xmalloc(sizeof(int) * (argc - optind + 1));
if (argc == optind) {
fds[nfiles++] = STDIN_FILENO; argv += optind;
argv[optind] = "standard input"; nfiles = i = 0;
} else {
for (i = optind; i < argc; i++) { if ((argc -= optind) == 0) {
if (strcmp(argv[i], "-") == 0) { struct stat statbuf;
fds[nfiles++] = STDIN_FILENO;
argv[i] = "standard input"; if (!fstat(STDIN_FILENO, &statbuf) && S_ISFIFO(statbuf.st_mode)) {
} else if ((fds[nfiles++] = open(argv[i], O_RDONLY)) < 0) { follow = 0;
perror_msg("%s", argv[i]);
status = EXIT_FAILURE;
}
} }
/* --argv; */
*argv = (char *) bb_msg_standard_input;
goto DO_STDIN;
} }
do {
if ((argv[i][0] == '-') && !argv[i][1]) {
DO_STDIN:
fds[nfiles] = STDIN_FILENO;
} else if ((fds[nfiles] = open(argv[i], O_RDONLY)) < 0) {
bb_perror_msg("%s", argv[i]);
status = EXIT_FAILURE;
continue;
}
argv[nfiles] = argv[i];
++nfiles;
} while (++i < argc);
if (!nfiles) {
bb_error_msg_and_die("no files");
}
tailbufsize = BUFSIZ;
#ifdef CONFIG_FEATURE_FANCY_TAIL #ifdef CONFIG_FEATURE_FANCY_TAIL
/* tail the files */ /* tail the files */
if (!from_top && units == BYTES) if (from_top < count_bytes) { /* Each is 0 or 1, so true iff 0 < 1. */
tailbuf = xmalloc(count); /* Hence, !from_top && count_bytes */
if (tailbufsize < count) {
tailbufsize = count + BUFSIZ;
}
}
#endif #endif
buf = tailbuf = xmalloc(tailbufsize);
for (i = 0; i < nfiles; i++) { fmt = header_fmt + 1; /* Skip header leading newline on first output. */
if (fds[i] == -1) i = 0;
continue; do {
if (!count) { /* Be careful. It would be possible to optimize the count-bytes
lseek(fds[i], 0, SEEK_END); * case if the file is seekable. If you do though, remember that
* starting file position may not be the beginning of the file.
* Beware of backing up too far. See example in wc.c.
*/
if ((!(count|from_top)) && (lseek(fds[i], 0, SEEK_END) >= 0)) {
continue; continue;
} }
seen = 0;
if (show_headers || (!hide_headers && nfiles > 1)) if (nfiles > header_threshhold) {
printf("%s==> %s <==\n", i == 0 ? "" : "\n", argv[optind + i]); tail_xprint_header(fmt, argv[i]);
while ((nread = safe_read(fds[i], buf, sizeof(buf))) > 0) { fmt = header_fmt;
}
buf = tailbuf;
taillen = 0;
seen = 1;
while ((nread = tail_read(fds[i], buf, tailbufsize-taillen)) > 0) {
if (from_top) { if (from_top) {
nwrite = nread;
if (seen < count) {
#ifdef CONFIG_FEATURE_FANCY_TAIL #ifdef CONFIG_FEATURE_FANCY_TAIL
if (units == BYTES) { if (count_bytes) {
if (count - 1 <= seen) nwrite -= (count - seen);
nwrite = nread; seen = count;
else if (count - 1 <= seen + nread) } else
nwrite = nread + seen - (count - 1);
else
nwrite = 0;
seen += nread;
} else {
#else
{
#endif #endif
if (count - 1 <= seen) {
nwrite = nread; s = buf;
else { do {
nwrite = 0; --nwrite;
for (s = memchr(buf, '\n', nread); s != NULL; if ((*s++ == '\n') && (++seen == count)) {
s = memchr(s+1, '\n', nread - (s + 1 - buf))) {
if (count - 1 <= ++seen) {
nwrite = nread - (s + 1 - buf);
break; break;
} }
} while (nwrite);
}
}
tail_xbb_full_write(buf + nread - nwrite, nwrite);
} else if (count) {
#ifdef CONFIG_FEATURE_FANCY_TAIL
if (count_bytes) {
taillen += nread;
if (taillen > count) {
memmove(tailbuf, tailbuf + taillen - count, count);
taillen = count;
}
} else
#endif
{
int k = nread;
int nbuf = 0;
while (k) {
--k;
if (buf[k] == '\n') {
++nbuf;
} }
} }
}
if (full_write(STDOUT_FILENO, buf + nread - nwrite, if (newline + nbuf < count) {
nwrite) < 0) { newline += nbuf;
perror_msg("write"); taillen += nread;
status = EXIT_FAILURE;
break;
}
} else {
#ifdef CONFIG_FEATURE_FANCY_TAIL
if (units == BYTES) {
if (nread < count) {
memmove(tailbuf, tailbuf + nread, count - nread);
memcpy(tailbuf + count - nread, buf, nread);
} else { } else {
memcpy(tailbuf, buf + nread - count, count); int extra = 0;
if (buf[nread-1] != '\n') {
extra = 1;
}
k = newline + nbuf + extra - count;
s = tailbuf;
while (k) {
if (*s == '\n') {
--k;
}
++s;
}
taillen += nread - (s - tailbuf);
memmove(tailbuf, s, taillen);
newline = count - extra;
} }
seen += nread; if (tailbufsize < taillen + BUFSIZ) {
} else { tailbufsize = taillen + BUFSIZ;
#else tailbuf = xrealloc(tailbuf, tailbufsize);
{
#endif
for (start = buf, end = memchr(buf, '\n', nread);
end != NULL; start = end+1,
end = memchr(start, '\n', nread - (start - buf))) {
if (newline && count <= seen)
tailbuf_trunc();
tailbuf_append(start, end - start + 1);
seen++;
newline = 1;
} }
if (newline && count <= seen && nread - (start - buf) > 0)
tailbuf_trunc();
tailbuf_append(start, nread - (start - buf));
} }
buf = tailbuf + taillen;
} }
} }
if (nread < 0) { if (!from_top) {
perror_msg("read"); tail_xbb_full_write(tailbuf, taillen);
status = EXIT_FAILURE;
}
#ifdef CONFIG_FEATURE_FANCY_TAIL
if (!from_top && units == BYTES) {
if (count < seen)
seen = count;
if (full_write(STDOUT_FILENO, tailbuf + count - seen, seen) < 0) {
perror_msg("write");
status = EXIT_FAILURE;
}
}
#endif
if (!from_top && units == LINES) {
if (full_write(STDOUT_FILENO, tailbuf, taillen) < 0) {
perror_msg("write");
status = EXIT_FAILURE;
}
} }
taillen = 0; taillen = 0;
} } while (++i < nfiles);
buf = xrealloc(tailbuf, BUFSIZ);
fmt = NULL;
while (follow) { while (follow) {
sleep(sleep_period); sleep(sleep_period);
i = 0;
for (i = 0; i < nfiles; i++) { do {
if (fds[i] == -1) if (nfiles > header_threshhold) {
continue; fmt = header_fmt;
if ((nread = safe_read(fds[i], buf, sizeof(buf))) > 0) {
if (show_headers || (!hide_headers && nfiles > 1))
printf("\n==> %s <==\n", argv[optind + i]);
do {
full_write(STDOUT_FILENO, buf, nread);
} while ((nread = safe_read(fds[i], buf, sizeof(buf))) > 0);
} }
while ((nread = tail_read(fds[i], buf, sizeof(buf))) > 0) {
if (nread < 0) { if (fmt) {
perror_msg("read"); tail_xprint_header(fmt, argv[i]);
status = EXIT_FAILURE; fmt = NULL;
}
tail_xbb_full_write(buf, nread);
} }
} } while (++i < nfiles);
} }
return status; return status;

View File

@ -1,8 +1,8 @@
/* vi: set sw=4 ts=4: */ /* vi: set sw=4 ts=4: */
/* /*
* Mini tee implementation for busybox * tee implementation for busybox
* *
* Copyright (C) 2000,2001 by Matt Kraai <kraai@alumni.carnegiemellon.edu> * Copyright (C) 2003 Manuel Novoa III <mjn3@codepoet.org>
* *
* This program is free software; you can redistribute it and/or modify * This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
@ -20,47 +20,96 @@
* *
*/ */
#include "busybox.h" /* BB_AUDIT SUSv3 compliant */
#include <getopt.h> /* http://www.opengroup.org/onlinepubs/007904975/utilities/tee.html */
#include <stdio.h> #include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <unistd.h>
#include "busybox.h"
int int tee_main(int argc, char **argv)
tee_main(int argc, char **argv)
{ {
char *mode = "w"; const char *mode = "w\0a";
int c, i, status = 0, nfiles = 0;
FILE **files; FILE **files;
FILE **p;
char **filenames;
int flags;
int retval = EXIT_SUCCESS;
#ifdef CONFIG_FEATURE_TEE_USE_BLOCK_IO
size_t c;
RESERVE_CONFIG_BUFFER(buf, BUFSIZ);
#else
int c;
#endif
while ((c = getopt(argc, argv, "a")) != EOF) { flags = bb_getopt_ulflags(argc, argv, "ia"); /* 'a' must be 2nd */
switch (c) {
case 'a': mode += (flags & 2); /* Since 'a' is the 2nd option... */
mode = "a";
break; if (flags & 1) {
default: signal(SIGINT, SIG_IGN); /* TODO - switch to sigaction.*/
show_usage(); }
/* gnu tee ignores SIGPIPE in case one of the output files is a pipe
* that doesn't consume all its input. Good idea... */
signal(SIGPIPE, SIG_IGN); /* TODO - switch to sigaction.*/
/* Allocate an array of FILE *'s, with one extra for a sentinal. */
p = files = (FILE **)xmalloc(sizeof(FILE *) * (argc - optind + 2));
*p = stdout;
argv += optind - 1;
filenames = argv - 1;
*filenames = (char *) bb_msg_standard_input; /* for later */
goto GOT_NEW_FILE;
do {
if ((*p = bb_wfopen(*argv, mode)) == NULL) {
retval = EXIT_FAILURE;
continue;
}
filenames[(int)(p - files)] = *argv;
GOT_NEW_FILE:
setbuf(*p, NULL); /* tee must not buffer output. */
++p;
} while (*++argv);
*p = NULL; /* Store the sentinal value. */
#ifdef CONFIG_FEATURE_TEE_USE_BLOCK_IO
while ((c = fread(buf, 1, BUFSIZ, stdin)) != 0) {
for (p=files ; *p ; p++) {
fwrite(buf, 1, c, *p);
} }
} }
files = (FILE **)xmalloc(sizeof(FILE *) * (argc - optind + 1)); #ifdef CONFIG_FEATURE_CLEAN_UP
files[nfiles++] = stdout; RELEASE_CONFIG_BUFFER(buf);
while (optind < argc) { #endif
if ((files[nfiles++] = wfopen(argv[optind++], mode)) == NULL) {
nfiles--; #else
status = 1; while ((c = getchar()) != EOF) {
for (p=files ; *p ; p++) {
putc(c, *p);
} }
} }
#endif
while ((c = getchar()) != EOF) /* Now we need to check for i/o errors on stdin and the various
for (i = 0; i < nfiles; i++) * output files. Since we know that the first entry in the output
putc(c, files[i]); * file table is stdout, we can save one "if ferror" test by
* setting the first entry to stdin and checking stdout error
* status with bb_fflush_stdout_and_exit()... although fflush()ing
* is unnecessary here. */
return status; p = files;
*p = stdin;
do { /* Now check for (input and) output errors. */
/* Checking ferror should be sufficient, but we may want to fclose.
* If we do, remember not to close stdin! */
bb_xferror(*p, filenames[(int)(p - files)]);
} while (*++p);
bb_fflush_stdout_and_exit(retval);
} }
/*
Local Variables:
c-file-style: "linux"
c-basic-offset: 4
tab-width: 4
End:
*/

View File

@ -180,9 +180,9 @@ extern int test_main(int argc, char **argv)
{ {
int res; int res;
if (strcmp(applet_name, "[") == 0) { if (strcmp(bb_applet_name, "[") == 0) {
if (strcmp(argv[--argc], "]")) if (strcmp(argv[--argc], "]"))
error_msg_and_die("missing ]"); bb_error_msg_and_die("missing ]");
argv[argc] = NULL; argv[argc] = NULL;
} }
/* Implement special cases from POSIX.2, section 4.62.4 */ /* Implement special cases from POSIX.2, section 4.62.4 */
@ -226,9 +226,9 @@ extern int test_main(int argc, char **argv)
static void syntax(const char *op, const char *msg) static void syntax(const char *op, const char *msg)
{ {
if (op && *op) { if (op && *op) {
error_msg_and_die("%s: %s", op, msg); bb_error_msg_and_die("%s: %s", op, msg);
} else { } else {
error_msg_and_die("%s", msg); bb_error_msg_and_die("%s", msg);
} }
} }
@ -450,13 +450,13 @@ static int getn(const char *s)
r = strtol(s, &p, 10); r = strtol(s, &p, 10);
if (errno != 0) if (errno != 0)
error_msg_and_die("%s: out of range", s); bb_error_msg_and_die("%s: out of range", s);
while (isspace(*p)) while (isspace(*p))
p++; p++;
if (*p) if (*p)
error_msg_and_die("%s: bad number", s); bb_error_msg_and_die("%s: bad number", s);
return (int) r; return (int) r;
} }

View File

@ -21,6 +21,16 @@
* *
*/ */
/* BB_AUDIT SUSv3 _NOT_ compliant -- options -a, -m, -r, -t not supported. */
/* http://www.opengroup.org/onlinepubs/007904975/utilities/touch.html */
/* Mar 16, 2003 Manuel Novoa III (mjn3@codepoet.org)
*
* Previous version called open() and then utime(). While this will be
* be necessary to implement -r and -t, it currently only makes things bigger.
* Also, exiting on a failure was a bug. All args should be processed.
*/
#include <stdio.h> #include <stdio.h>
#include <sys/types.h> #include <sys/types.h>
#include <fcntl.h> #include <fcntl.h>
@ -33,44 +43,35 @@
extern int touch_main(int argc, char **argv) extern int touch_main(int argc, char **argv)
{ {
int fd; int fd;
int create = TRUE; int flags;
int status = EXIT_SUCCESS;
/* Parse options */ flags = bb_getopt_ulflags(argc, argv, "c");
while (--argc > 0 && **(++argv) == '-') {
while (*(++(*argv))) { argv += optind;
switch (**argv) {
case 'c': if (!*argv) {
create = FALSE; bb_show_usage();
break;
default:
show_usage();
}
}
} }
if (argc < 1) { do {
show_usage();
}
while (argc > 0) {
fd = open(*argv, create ? O_RDWR | O_CREAT : O_RDWR,
S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH);
if (fd < 0) {
if (! create && errno == ENOENT) {
argc--;
argv++;
continue;
} else {
perror_msg_and_die("%s", *argv);
}
}
close(fd);
if (utime(*argv, NULL)) { if (utime(*argv, NULL)) {
perror_msg_and_die("%s", *argv); if (errno == ENOENT) { /* no such file*/
if (flags & 1) { /* Creation is disabled, so ignore. */
continue;
}
/* Try to create the file. */
fd = open(*argv, O_RDWR | O_CREAT,
S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH
);
if ((fd >= 0) && !close(fd)) {
continue;
}
}
status = EXIT_FAILURE;
bb_perror_msg("%s", *argv);
} }
argc--; } while (*++argv);
argv++;
}
return EXIT_SUCCESS; return status;
} }

View File

@ -54,7 +54,7 @@ static void convert(void)
if (in_index == read_chars) { if (in_index == read_chars) {
if ((read_chars = read(0, (char *) pinput, BUFSIZ)) <= 0) { if ((read_chars = read(0, (char *) pinput, BUFSIZ)) <= 0) {
if (write(1, (char *) poutput, out_index) != out_index) if (write(1, (char *) poutput, out_index) != out_index)
error_msg("%s", write_error); bb_error_msg(bb_msg_write_error);
exit(0); exit(0);
} }
in_index = 0; in_index = 0;
@ -68,7 +68,7 @@ static void convert(void)
poutput[out_index++] = last = coded; poutput[out_index++] = last = coded;
if (out_index == BUFSIZ) { if (out_index == BUFSIZ) {
if (write(1, (char *) poutput, out_index) != out_index) if (write(1, (char *) poutput, out_index) != out_index)
error_msg_and_die("%s", write_error); bb_error_msg_and_die(bb_msg_write_error);
out_index = 0; out_index = 0;
} }
} }
@ -102,7 +102,7 @@ static unsigned int expand(const char *arg, register unsigned char *buffer)
while (*arg) { while (*arg) {
if (*arg == '\\') { if (*arg == '\\') {
arg++; arg++;
*buffer++ = process_escape_sequence(&arg); *buffer++ = bb_process_escape_sequence(&arg);
} else if (*(arg+1) == '-') { } else if (*(arg+1) == '-') {
ac = *(arg+2); ac = *(arg+2);
if(ac == 0) { if(ac == 0) {
@ -181,7 +181,7 @@ extern int tr_main(int argc, char **argv)
sq_fl = TRUE; sq_fl = TRUE;
break; break;
default: default:
show_usage(); bb_show_usage();
} }
} }
idx++; idx++;
@ -197,7 +197,7 @@ extern int tr_main(int argc, char **argv)
input_length = complement(input, input_length); input_length = complement(input, input_length);
if (argv[idx] != NULL) { if (argv[idx] != NULL) {
if (*argv[idx] == '\0') if (*argv[idx] == '\0')
error_msg_and_die("STRING2 cannot be empty"); bb_error_msg_and_die("STRING2 cannot be empty");
output_length = expand(argv[idx], output); output_length = expand(argv[idx], output);
map(input, input_length, output, output_length); map(input, input_length, output, output_length);
} }

View File

@ -21,7 +21,8 @@
* *
*/ */
/* getopt not needed */ /* BB_AUDIT SUSv3 compliant */
/* http://www.opengroup.org/onlinepubs/007904975/utilities/true.html */
#include <stdlib.h> #include <stdlib.h>
#include "busybox.h" #include "busybox.h"

View File

@ -1,8 +1,8 @@
/* vi: set sw=4 ts=4: */ /* vi: set sw=4 ts=4: */
/* /*
* Mini tty implementation for busybox * tty implementation for busybox
* *
* Copyright (C) 2000 Edward Betts <edward@debian.org>. * Copyright (C) 2003 Manuel Novoa III <mjn3@codepoet.org>
* *
* This program is free software; you can redistribute it and/or modify * This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
@ -20,25 +20,39 @@
* *
*/ */
/* BB_AUDIT SUSv3 compliant */
/* http://www.opengroup.org/onlinepubs/007904975/utilities/tty.html */
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <unistd.h> #include <unistd.h>
#include <sys/types.h>
#include "busybox.h" #include "busybox.h"
extern int tty_main(int argc, char **argv) extern int tty_main(int argc, char **argv)
{ {
char *tty; const char *s;
int silent; /* Note: No longer relevant in SUSv3. */
int retval;
if (argc > 1) { bb_default_error_retval = 2; /* SUSv3 requires > 1 for error. */
if (argv[1][0] != '-' || argv[1][1] != 's')
show_usage(); silent = bb_getopt_ulflags(argc, argv, "s");
} else {
tty = ttyname(0); /* gnu tty outputs a warning that it is ignoring all args. */
if (tty) bb_warn_ignoring_args(argc - optind);
puts(tty);
else retval = 0;
puts("not a tty");
if ((s = ttyname(0)) == NULL) {
/* According to SUSv3, ttyname can on fail with EBADF or ENOTTY.
* We know the file descriptor is good, so failure means not a tty. */
s = "not a tty";
retval = 1;
} }
return(isatty(0) ? EXIT_SUCCESS : EXIT_FAILURE);
if (!silent) {
puts(s);
}
bb_fflush_stdout_and_exit(retval);
} }

View File

@ -16,6 +16,9 @@
along with this program; if not, write to the Free Software Foundation, along with this program; if not, write to the Free Software Foundation,
Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */
/* BB_AUDIT SUSv3 compliant */
/* http://www.opengroup.org/onlinepubs/007904975/utilities/uname.html */
/* Option Example /* Option Example
-s, --sysname SunOS -s, --sysname SunOS
@ -33,13 +36,18 @@
/* Further size reductions by Glenn McGrath and Manuel Novoa III. */ /* Further size reductions by Glenn McGrath and Manuel Novoa III. */
/* Mar 16, 2003 Manuel Novoa III (mjn3@codepoet.org)
*
* Now does proper error checking on i/o. Plus some further space savings.
*/
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <stddef.h> #include <stddef.h>
#include <string.h> #include <string.h>
#include <unistd.h>
#include <sys/types.h> #include <sys/types.h>
#include <sys/utsname.h> #include <sys/utsname.h>
#include <getopt.h>
#include "busybox.h" #include "busybox.h"
typedef struct { typedef struct {
@ -48,7 +56,6 @@ typedef struct {
} uname_info_t; } uname_info_t;
static const char options[] = "snrvmpa"; static const char options[] = "snrvmpa";
static const char flags[] = "\x01\x02\x04\x08\x10\x20\x3f";
static const unsigned short int utsname_offset[] = { static const unsigned short int utsname_offset[] = {
offsetof(uname_info_t,name.sysname), offsetof(uname_info_t,name.sysname),
offsetof(uname_info_t,name.nodename), offsetof(uname_info_t,name.nodename),
@ -61,29 +68,28 @@ static const unsigned short int utsname_offset[] = {
int uname_main(int argc, char **argv) int uname_main(int argc, char **argv)
{ {
uname_info_t uname_info; uname_info_t uname_info;
#if defined(__sparc__) && defined(__linux__) #if defined(__sparc__) && defined(__linux__)
char *fake_sparc = getenv("FAKE_SPARC"); char *fake_sparc = getenv("FAKE_SPARC");
#endif #endif
const unsigned short int *delta; const unsigned short int *delta;
int opt; char toprint;
char toprint = 0;
while ((opt = getopt(argc, argv, options)) != -1) { toprint = bb_getopt_ulflags(argc, argv, options);
const char *p = strchr(options,opt);
if (p == NULL) { if (argc != optind) {
show_usage(); bb_show_usage();
} }
toprint |= flags[(int)(p-options)];
if (toprint & (1 << 6)) {
toprint = 0x3f;
} }
if (toprint == 0) { if (toprint == 0) {
toprint = flags[0]; /* sysname */ toprint = 1; /* sysname */
} }
if (uname(&uname_info.name) == -1) { if (uname(&uname_info.name) == -1) {
error_msg_and_die("cannot get system name"); bb_error_msg_and_die("cannot get system name");
} }
#if defined(__sparc__) && defined(__linux__) #if defined(__sparc__) && defined(__linux__)
@ -99,7 +105,7 @@ int uname_main(int argc, char **argv)
delta=utsname_offset; delta=utsname_offset;
do { do {
if (toprint & 1) { if (toprint & 1) {
printf(((char *)(&uname_info)) + *delta); bb_printf(((char *)(&uname_info)) + *delta);
if (toprint > 1) { if (toprint > 1) {
putchar(' '); putchar(' ');
} }
@ -108,5 +114,5 @@ int uname_main(int argc, char **argv)
} while (toprint >>= 1); } while (toprint >>= 1);
putchar('\n'); putchar('\n');
return EXIT_SUCCESS; bb_fflush_stdout_and_exit(EXIT_SUCCESS);
} }

View File

@ -1,10 +1,8 @@
/* vi: set sw=4 ts=4: */ /* vi: set sw=4 ts=4: */
/* /*
* Mini uniq implementation for busybox * uniq implementation for busybox
* *
* Copyright (C) 1999 by Lineo, inc. and John Beppu * Copyright (C) 2003 Manuel Novoa III <mjn3@codepoet.org>
* Copyright (C) 1999,2000,2001 by John Beppu <beppu@codepoet.org>
* Rewritten by Matt Kraai <kraai@alumni.carnegiemellon.edu>
* *
* This program is free software; you can redistribute it and/or modify * This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
@ -22,67 +20,93 @@
* *
*/ */
/* BB_AUDIT SUSv3 compliant */
/* http://www.opengroup.org/onlinepubs/007904975/utilities/uniq.html */
#include <stdio.h> #include <stdio.h>
#include <string.h>
#include <getopt.h>
#include <errno.h>
#include <stdlib.h> #include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <unistd.h>
#include "busybox.h" #include "busybox.h"
#include "libcoreutils/coreutils.h"
static int print_count; static const char uniq_opts[] = "f:s:cdu\0\7\3\5\1\2\4";
static int print_uniq = 1;
static int print_duplicates = 1;
static void print_line(char *line, int count, FILE *fp)
{
if ((print_duplicates && count > 1) || (print_uniq && count == 1)) {
if (print_count)
fprintf(fp, "%7d\t%s", count, line);
else
fputs(line, fp);
}
}
int uniq_main(int argc, char **argv) int uniq_main(int argc, char **argv)
{ {
FILE *in = stdin, *out = stdout; FILE *in, *out;
char *lastline = NULL, *input; /* Note: Ignore the warning about dups and e0 possibly being uninitialized.
int opt, count = 0; * They will be initialized on the fist pass of the loop (since s0 is NULL). */
unsigned long dups, skip_fields, skip_chars, i;
const char *s0, *e0, *s1, *e1, *input_filename;
int opt;
int uniq_flags = 6; /* -u */
/* parse argv[] */ skip_fields = skip_chars = 0;
while ((opt = getopt(argc, argv, "cdu")) > 0) {
switch (opt) { while ((opt = getopt(argc, argv, uniq_opts)) > 0) {
case 'c': if (opt == 'f') {
print_count = 1; skip_fields = bb_xgetularg10(optarg);
break; } else if (opt == 's') {
case 'd': skip_chars = bb_xgetularg10(optarg);
print_duplicates = 1; } else if ((s0 = strchr(uniq_opts, opt)) != NULL) {
print_uniq = 0; uniq_flags &= s0[4];
break; uniq_flags |= s0[7];
case 'u': } else {
print_duplicates = 0; bb_show_usage();
print_uniq = 1;
break;
} }
} }
if (argv[optind] != NULL) { input_filename = *(argv += optind);
in = xfopen(argv[optind], "r");
if (argv[optind+1] != NULL) in = xgetoptfile_sort_uniq(argv, "r");
out = xfopen(argv[optind+1], "w"); if (*argv) {
++argv;
}
out = xgetoptfile_sort_uniq(argv, "w");
if (*argv && argv[1]) {
bb_show_usage();
} }
while ((input = get_line_from_file(in)) != NULL) { s0 = NULL;
if (lastline == NULL || strcmp(input, lastline) != 0) {
print_line(lastline, count, out); /* gnu uniq ignores newlines */
free(lastline); while ((s1 = bb_get_chomped_line_from_file(in)) != NULL) {
lastline = input; e1 = s1;
count = 0; for (i=skip_fields ; i ; i--) {
e1 = bb_skip_whitespace(e1);
while (*e1 && !isspace(*e1)) {
++e1;
}
}
for (i = skip_chars ; *e1 && i ; i--) {
++e1;
}
if (s0) {
if (strcmp(e0, e1) == 0) {
++dups; /* Note: Testing for overflow seems excessive. */
continue;
}
DO_LAST:
if ((dups && (uniq_flags & 2)) || (!dups && (uniq_flags & 4))) {
bb_fprintf(out, "\0%7d\t" + (uniq_flags & 1), dups + 1);
bb_fprintf(out, "%s\n", s0);
}
free((void *)s0);
} }
count++;
}
print_line(lastline, count, out);
free(lastline);
return EXIT_SUCCESS; s0 = s1;
e0 = e1;
dups = 0;
}
if (s0) {
e1 = NULL;
goto DO_LAST;
}
bb_xferror(in, input_filename);
bb_fflush_stdout_and_exit(EXIT_SUCCESS);
} }

Some files were not shown because too many files have changed in this diff Show More