Compare commits

..
1 Commits
Author SHA1 Message Date
Mike Frysinger f23b96cebf tag busybox-1.2.1 2006-08-24 03:06:55 +00:00
783 changed files with 52459 additions and 67336 deletions

No files matched your search

+1 -1
View File
@@ -113,7 +113,7 @@ Manuel Novoa III <mjn3@codepoet.org>
Vladimir Oleynik <dzo@simtreas.ru>
cmdedit; bb_mkdep, xargs(current), httpd(current);
ports: ash, crond, fdisk (initial, unmaintained now), inetd, stty, traceroute,
ports: ash, crond, fdisk (initial, unmaintained now), inetd, stty, traceroute,
top;
locale, various fixes
and irreconcilable critic of everything not perfect.
+61 -83
View File
@@ -13,7 +13,7 @@ menu "Busybox Settings"
menu "General Configuration"
config NITPICK
config CONFIG_NITPICK
bool "See lots more (probably unnecessary) configuration options."
default n
help
@@ -29,18 +29,10 @@ config NITPICK
You have been warned.
config DESKTOP
bool "Enable options for full-blown desktop systems"
default n
help
Enable options and features which are not essential.
Select this only if you plan to use busybox on full-blown
desktop machine with common Linux distro, not on an embedded box.
choice
prompt "Buffer allocation policy"
default FEATURE_BUFFERS_USE_MALLOC
depends on NITPICK
default CONFIG_FEATURE_BUFFERS_USE_MALLOC
depends on CONFIG_NITPICK
help
There are 3 ways BusyBox can handle buffer allocations:
- Use malloc. This costs code size for the call to xmalloc.
@@ -51,18 +43,18 @@ choice
behavior was the only one available for BusyBox versions 0.48 and
earlier.
config FEATURE_BUFFERS_USE_MALLOC
config CONFIG_FEATURE_BUFFERS_USE_MALLOC
bool "Allocate with Malloc"
config FEATURE_BUFFERS_GO_ON_STACK
config CONFIG_FEATURE_BUFFERS_GO_ON_STACK
bool "Allocate on the Stack"
config FEATURE_BUFFERS_GO_IN_BSS
config CONFIG_FEATURE_BUFFERS_GO_IN_BSS
bool "Allocate in the .bss section"
endchoice
config SHOW_USAGE
config CONFIG_SHOW_USAGE
bool "Show terse applet usage messages"
default y
help
@@ -71,20 +63,20 @@ config SHOW_USAGE
messages if you say no here.
This will save you up to 7k.
config FEATURE_VERBOSE_USAGE
config CONFIG_FEATURE_VERBOSE_USAGE
bool "Show verbose applet usage messages"
default n
select SHOW_USAGE
select CONFIG_SHOW_USAGE
help
All BusyBox applets will show more verbose help messages when
busybox is invoked with --help. This will add a lot of text to the
busybox binary. In the default configuration, this will add about
13k, but it can add much more depending on your configuration.
config FEATURE_COMPRESS_USAGE
config CONFIG_FEATURE_COMPRESS_USAGE
bool "Store applet usage messages in compressed form"
default y
depends on SHOW_USAGE
depends on CONFIG_SHOW_USAGE && CONFIG_NITPICK
help
Store usage messages in compressed form, uncompress them on-the-fly
when <applet> --help is called.
@@ -95,7 +87,7 @@ config FEATURE_COMPRESS_USAGE
and have very little memory, this might not be a win. Otherwise,
you probably want this.
config FEATURE_INSTALLER
config CONFIG_FEATURE_INSTALLER
bool "Support --install [-s] to install applet links at runtime"
default n
help
@@ -104,21 +96,23 @@ config FEATURE_INSTALLER
applets that are compiled into busybox. This feature requires the
/proc filesystem.
config LOCALE_SUPPORT
config CONFIG_LOCALE_SUPPORT
bool "Enable locale support (system needs locale for this to work)"
default n
help
Enable this if your system has locale support and you would like
busybox to support locale settings.
config GETOPT_LONG
bool "Enable support for --long-options"
config CONFIG_GETOPT_LONG
bool
default y
help
Enable this if you want busybox applets to use the gnu --long-option
style, in addition to single character -a -b -c style options.
# bool "Enable support for --long-options"
# default n
# help
# Enable this if you want busybox applets to use the gnu --long-option
# style, in addition to single character -a -b -c style options.
config FEATURE_DEVPTS
config CONFIG_FEATURE_DEVPTS
bool "Use the devpts filesystem for Unix98 PTYs"
default y
help
@@ -128,10 +122,10 @@ config FEATURE_DEVPTS
/dev/ttyp<number> will be used. To use this option, you should have
devpts mounted.
config FEATURE_CLEAN_UP
config CONFIG_FEATURE_CLEAN_UP
bool "Clean up all memory before exiting (usually not needed)"
default n
depends on NITPICK
depends on CONFIG_NITPICK
help
As a size optimization, busybox normally exits without explicitly
freeing dynamically allocated memory or closing files. This saves
@@ -141,7 +135,7 @@ config FEATURE_CLEAN_UP
Don't enable this unless you have a really good reason to clean
things up manually.
config FEATURE_SUID
config CONFIG_FEATURE_SUID
bool "Support for SUID/SGID handling"
default n
help
@@ -156,17 +150,10 @@ config FEATURE_SUID
are login, passwd, su, ping, traceroute, crontab, dnsd, ipcrm, ipcs,
and vlock.
config FEATURE_SYSLOG
bool "Support for syslog"
default n
help
This option is auto-selected when you select any applet which may
send its output to syslog. You do not need to select it manually.
config FEATURE_SUID_CONFIG
config CONFIG_FEATURE_SUID_CONFIG
bool "Runtime SUID/SGID configuration via /etc/busybox.conf"
default n if FEATURE_SUID
depends on FEATURE_SUID
default n if CONFIG_FEATURE_SUID
depends on CONFIG_FEATURE_SUID
help
Allow the SUID / SGID state of an applet to be determined at runtime
by checking /etc/busybox.conf. (This is sort of a poor man's sudo.)
@@ -195,23 +182,15 @@ config FEATURE_SUID_CONFIG
Robert 'sandman' Griebl has more information here:
<url: http://www.softforge.de/bb/suid.html >.
config FEATURE_SUID_CONFIG_QUIET
config CONFIG_FEATURE_SUID_CONFIG_QUIET
bool "Suppress warning message if /etc/busybox.conf is not readable"
default y
depends on FEATURE_SUID_CONFIG
depends on CONFIG_FEATURE_SUID_CONFIG
help
/etc/busybox.conf should be readable by the user needing the SUID, check
this option to avoid users to be notified about missing permissions.
config FEATURE_HAVE_RPC
bool "RPC support"
default y
help
Select this if you have rpc support.
This automatically turns off all configuration options that rely
on RPC.
config SELINUX
config CONFIG_SELINUX
bool "Support NSA Security Enhanced Linux"
default n
help
@@ -231,7 +210,7 @@ config SELINUX
Most people will leave this set to 'N'.
config BUSYBOX_EXEC_PATH
config CONFIG_BUSYBOX_EXEC_PATH
string "Path to BusyBox executable"
default "/proc/self/exe"
help
@@ -245,7 +224,7 @@ endmenu
menu 'Build Options'
config STATIC
config CONFIG_STATIC
bool "Build BusyBox as a static binary (no shared libs)"
default n
help
@@ -259,7 +238,7 @@ config STATIC
Most people will leave this set to 'N'.
config BUILD_LIBBUSYBOX
config CONFIG_BUILD_LIBBUSYBOX
bool "Build shared libbusybox"
default n
help
@@ -271,10 +250,10 @@ config BUILD_LIBBUSYBOX
binary serves no purpose (and increases the size). You should
almost certainly say "no" to this right now.
config FEATURE_FULL_LIBBUSYBOX
config CONFIG_FEATURE_FULL_LIBBUSYBOX
bool "Feature-complete libbusybox"
default n if !FEATURE_SHARED_BUSYBOX
depends on BUILD_LIBBUSYBOX
default n if !CONFIG_FEATURE_SHARED_BUSYBOX
depends on CONFIG_BUILD_LIBBUSYBOX
help
Build a libbusybox with the complete feature-set, disregarding
the actually selected config.
@@ -290,15 +269,15 @@ config FEATURE_FULL_LIBBUSYBOX
Say 'N' if in doubt.
config FEATURE_SHARED_BUSYBOX
config CONFIG_FEATURE_SHARED_BUSYBOX
bool "Use shared libbusybox for busybox"
default y if BUILD_LIBBUSYBOX
depends on !STATIC && BUILD_LIBBUSYBOX
default y if CONFIG_BUILD_LIBBUSYBOX
depends on !CONFIG_STATIC && CONFIG_BUILD_LIBBUSYBOX
help
Use libbusybox.so also for busybox itself.
You need to have a working dynamic linker to use this variant.
config LFS
config CONFIG_LFS
bool "Build with Large File Support (for accessing files > 2 GB)"
default n
select FDISK_SUPPORT_LARGE_DISKS
@@ -310,7 +289,7 @@ config LFS
cp, mount, tar, and many others. If you want to access files larger
than 2 Gigabytes, enable this option. Otherwise, leave it set to 'N'.
config BUILD_AT_ONCE
config CONFIG_BUILD_AT_ONCE
bool "Compile all sources at once"
default n
help
@@ -333,7 +312,7 @@ endmenu
menu 'Debugging Options'
config DEBUG
config CONFIG_DEBUG
bool "Build BusyBox with extra Debugging symbols"
default n
help
@@ -344,10 +323,10 @@ config DEBUG
Most people should answer N.
config DEBUG_PESSIMIZE
config CONFIG_DEBUG_PESSIMIZE
bool "Disable compiler optimizations."
default n
depends on DEBUG
depends on CONFIG_DEBUG
help
The compiler's optimization of source code can eliminate and reorder
code, resulting in an executable that's hard to understand when
@@ -357,8 +336,8 @@ config DEBUG_PESSIMIZE
choice
prompt "Additional debugging library"
default NO_DEBUG_LIB
depends on DEBUG
default CONFIG_NO_DEBUG_LIB
depends on CONFIG_DEBUG
help
Using an additional debugging library will make BusyBox become
considerable larger and will cause it to run more slowly. You
@@ -386,31 +365,31 @@ choice
you are hunting a hard to find memory problem.
config NO_DEBUG_LIB
config CONFIG_NO_DEBUG_LIB
bool "None"
config DMALLOC
config CONFIG_DMALLOC
bool "Dmalloc"
config EFENCE
config CONFIG_EFENCE
bool "Electric-fence"
endchoice
config INCLUDE_SUSv2
bool "Enable obsolete features removed before SUSv3?"
config CONFIG_DEBUG_YANK_SUSv2
bool "Disable obsolete features removed before SUSv3?"
default y
help
This option will enable backwards compatibility with SuSv2,
This option will disable backwards compatibility with SuSv2,
specifically, old-style numeric options ('command -1 <file>')
will be supported in head, tail, and fold. (Note: should
affect renice too.)
will not be supported in head, tail, and fold. (Note: should
yank from renice too.)
endmenu
menu 'Installation Options'
config INSTALL_NO_USR
config CONFIG_INSTALL_NO_USR
bool "Don't use /usr"
default n
help
@@ -419,29 +398,29 @@ config INSTALL_NO_USR
choice
prompt "Applets links"
default INSTALL_APPLET_SYMLINKS
default CONFIG_INSTALL_APPLET_SYMLINKS
help
Choose how you install applets links.
config INSTALL_APPLET_SYMLINKS
config CONFIG_INSTALL_APPLET_SYMLINKS
bool "as soft-links"
help
Install applets as soft-links to the busybox binary. This needs some
free inodes on the filesystem, but might help with filesystem
generators that can't cope with hard-links.
config INSTALL_APPLET_HARDLINKS
config CONFIG_INSTALL_APPLET_HARDLINKS
bool "as hard-links"
help
Install applets as hard-links to the busybox binary. This might count
on a filesystem with few inodes.
config INSTALL_APPLET_DONT
config CONFIG_INSTALL_APPLET_DONT
bool
prompt "not installed"
depends on FEATURE_INSTALLER || FEATURE_SH_STANDALONE_SHELL
depends on CONFIG_FEATURE_INSTALLER || CONFIG_FEATURE_SH_STANDALONE_SHELL
help
Do not install applet links. Useful when using the -install feature
Do not install applets links. Usefull when using the -install feature
or a standalone shell for rescue pruposes.
endchoice
@@ -476,4 +455,3 @@ source networking/Config.in
source procps/Config.in
source shell/Config.in
source sysklogd/Config.in
source runit/Config.in
+2 -4
View File
@@ -32,10 +32,8 @@ any built-in busybox applets directly, without looking for external
programs by that name. Supplying an empty command path (as above) means
the only commands busybox can find are the built-in ones.
Note that the standalone shell requires CONFIG_BUSYBOX_EXEC_PATH
to be set appropriately, depending on whether or not /proc/self/exe is
available or not. If you do not have /proc, then point that config option
to the location of your busybox binary, usually /bin/busybox.
(Note that the standalone shell currently requires /proc/self/exe to
launch new applets.)
Configuring Busybox:
====================
-8
View File
@@ -1,11 +1,3 @@
--- A note on GPL versions
BusyBox is distributed under version 2 of the General Public License (included
in its entirety, below). Version 2 is the only version of this license which
this version of BusyBox (or modified versions derived from this one) may be
distributed under.
------------------------------------------------------------------------
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
+472 -1227
View File
File diff suppressed because it is too large. Load diff
-145
View File
@@ -1,145 +0,0 @@
# ==========================================================================
# Build system
# ==========================================================================
%.bflt: %_unstripped
$(CROSS_COMPILE)elf2flt $(ELF2FLTFLAGS) $< -o $@
busybox.links: $(srctree)/applets/busybox.mkll $(objtree)/include/autoconf.h $(srctree)/include/applets.h
$(Q)-$(SHELL) $^ >$@
.PHONY: install
ifeq ($(CONFIG_INSTALL_APPLET_SYMLINKS),y)
INSTALL_OPTS:= --symlinks
endif
ifeq ($(CONFIG_INSTALL_APPLET_HARDLINKS),y)
INSTALL_OPTS:= --hardlinks
endif
install: $(srctree)/applets/install.sh busybox busybox.links
$(Q)DO_INSTALL_LIBS="$(strip $(LIBBUSYBOX_SONAME) $(DO_INSTALL_LIBS))" \
$(SHELL) $< $(CONFIG_PREFIX) $(INSTALL_OPTS)
ifeq ($(strip $(CONFIG_FEATURE_SUID)),y)
@echo
@echo
@echo --------------------------------------------------
@echo You will probably need to make your busybox binary
@echo setuid root to ensure all configured applets will
@echo work properly.
@echo --------------------------------------------------
@echo
endif
uninstall: busybox.links
rm -f $(CONFIG_PREFIX)/bin/busybox
for i in `cat busybox.links` ; do rm -f $(CONFIG_PREFIX)$$i; done
ifneq ($(strip $(DO_INSTALL_LIBS)),n)
for i in $(LIBBUSYBOX_SONAME) $(DO_INSTALL_LIBS); do \
rm -f $(CONFIG_PREFIX)$$i; \
done
endif
check test: busybox busybox.links
bindir=$(objtree) srcdir=$(srctree)/testsuite SED="$(SED)" \
$(SHELL) $(srctree)/testsuite/runtest $(if $(KBUILD_VERBOSE:0=),-v)
.PHONY: release
release: distclean
cd ..; \
rm -r -f busybox-$(VERSION).$(PATCHLEVEL).$(SUBLEVEL)$(EXTRAVERSION); \
cp -a busybox busybox-$(VERSION).$(PATCHLEVEL).$(SUBLEVEL)$(EXTRAVERSION) && { \
find busybox-$(VERSION).$(PATCHLEVEL).$(SUBLEVEL)$(EXTRAVERSION)/ -type d \
-name .svn \
-print \
-exec rm -r -f {} \; ; \
find busybox-$(VERSION).$(PATCHLEVEL).$(SUBLEVEL)$(EXTRAVERSION)/ -type f \
-name .\#* \
-print \
-exec rm -f {} \; ; \
tar -czf busybox-$(VERSION).$(PATCHLEVEL).$(SUBLEVEL)$(EXTRAVERSION).tar.gz \
busybox-$(VERSION).$(PATCHLEVEL).$(SUBLEVEL)$(EXTRAVERSION)/ ; }
.PHONY: checkhelp
checkhelp:
$(Q)$(srctree)/scripts/checkhelp.awk \
$(patsubst %,$(srctree)/%,$(wildcard $(patsubst %,%/Config.in,$(busybox-dirs) ./)))
.PHONY: sizes
sizes: busybox_unstripped
$(NM) --size-sort $(<)
.PHONY: bloatcheck
bloatcheck: busybox_old busybox_unstripped
@$(srctree)/scripts/bloat-o-meter busybox_old busybox_unstripped
.PHONY: baseline
baseline: busybox_unstripped
@mv busybox_unstripped busybox_old
.PHONY: objsizes
objsizes: busybox_unstripped
$(srctree)/scripts/objsizes
.PHONY: bigdata
bigdata: busybox_unstripped
nm --size-sort busybox_unstripped | grep -vi ' [tr] ' | tail -20
# Documentation Targets
.PHONY: doc
doc: docs/busybox.pod docs/BusyBox.txt docs/BusyBox.1 docs/BusyBox.html
docs/busybox.pod: $(srctree)/docs/busybox_header.pod \
$(srctree)/include/usage.h \
$(srctree)/docs/busybox_footer.pod \
$(srctree)/docs/autodocifier.pl
$(disp_doc)
$(Q)-mkdir -p docs
$(Q)-( cat $(srctree)/docs/busybox_header.pod ; \
$(srctree)/docs/autodocifier.pl $(srctree)/include/usage.h ; \
cat $(srctree)/docs/busybox_footer.pod ; ) > docs/busybox.pod
docs/BusyBox.txt: docs/busybox.pod
$(disp_doc)
$(Q)-mkdir -p docs
$(Q)-pod2text $< > $@
docs/BusyBox.1: docs/busybox.pod
$(disp_doc)
$(Q)-mkdir -p docs
$(Q)-pod2man --center=BusyBox --release="version $(VERSION)" \
$< > $@
docs/BusyBox.html: docs/busybox.net/BusyBox.html
$(disp_doc)
$(Q)-mkdir -p docs
$(Q)-rm -f docs/BusyBox.html
$(Q)-cp docs/busybox.net/BusyBox.html docs/BusyBox.html
docs/busybox.net/BusyBox.html: docs/busybox.pod
$(Q)-mkdir -p docs/busybox.net
$(Q)-pod2html --noindex $< > \
docs/busybox.net/BusyBox.html
$(Q)-rm -f pod2htm*
# documentation, cross-reference
# Modern distributions already ship synopsis packages (e.g. debian)
# If you have an old distribution go to http://synopsis.fresco.org/
syn_tgt = $(wildcard $(patsubst %,%/*.c,$(busybox-alldirs)))
syn = $(patsubst %.c, %.syn, $(syn_tgt))
comma:= ,
brace_open:= (
brace_close:= )
SYN_CPPFLAGS := $(strip $(CPPFLAGS) $(EXTRA_CPPFLAGS))
SYN_CPPFLAGS := $(subst $(brace_open),\$(brace_open),$(SYN_CPPFLAGS))
SYN_CPPFLAGS := $(subst $(brace_close),\$(brace_close),$(SYN_CPPFLAGS))
#SYN_CPPFLAGS := $(subst ",\",$(SYN_CPPFLAGS))
#")
#SYN_CPPFLAGS := [$(patsubst %,'%'$(comma),$(SYN_CPPFLAGS))'']
%.syn: %.c
synopsis -p C -l Comments.SSDFilter,Comments.Previous -Wp,preprocess=True,cppflags="'$(SYN_CPPFLAGS)'" -o $@ $<
.PHONY: html
html: $(syn)
synopsis -f HTML -Wf,title="'BusyBox Documentation'" -o $@ $^
-31
View File
@@ -1,31 +0,0 @@
# ==========================================================================
# Build system
# ==========================================================================
BB_VER = $(VERSION).$(PATCHLEVEL).$(SUBLEVEL)$(EXTRAVERSION)
# -std=gnu99 needed for [U]LLONG_MAX on some systems
CPPFLAGS += \
-std=gnu99 \
-Iinclude -Ilibbb \
$(if $(KBUILD_SRC),-Iinclude2 -I$(srctree)/include) -I$(srctree)/libbb \
-include include/autoconf.h \
-D_GNU_SOURCE -DNDEBUG \
$(if $(CONFIG_LFS),-D_LARGEFILE_SOURCE -D_LARGEFILE64_SOURCE -D_FILE_OFFSET_BITS=64) \
-D"BB_VER=KBUILD_STR($(BB_VER))" -DBB_BT=AUTOCONF_TIMESTAMP
CFLAGS += \
-Wall -Wstrict-prototypes -Wshadow -Werror -Wundef \
-funsigned-char -fno-builtin-strlen -finline-limit=0 -static-libgcc \
-Os -falign-functions=1 -falign-jumps=1 -falign-loops=1 \
-fomit-frame-pointer -ffunction-sections -fdata-sections
ifeq ($(CONFIG_DEBUG),y)
CFLAGS += -g
endif
ifeq ($(CONFIG_STATIC),y)
LDFLAGS += -static
endif
#LDFLAGS += -nostdlib
-42
View File
@@ -1,42 +0,0 @@
# ==========================================================================
# Build system
# ==========================================================================
help:
@echo 'Cleaning:'
@echo ' clean - delete temporary files created by build'
@echo ' distclean - delete all non-source files (including .config)'
@echo
@echo 'Build:'
@echo ' all - Executable and documentation'
@echo ' busybox - the swiss-army executable'
@echo ' doc - docs/BusyBox.{txt,html,1}'
@echo ' html - create html-based cross-reference'
@echo
@echo 'Configuration:'
@echo ' allnoconfig - disable all symbols in .config'
@echo ' allyesconfig - enable all symbols in .config (see defconfig)'
@echo ' allbareconfig - enable all applets without any sub-features'
@echo ' config - text based configurator (of last resort)'
@echo ' defconfig - set .config to largest generic configuration'
@echo ' menuconfig - interactive curses-based configurator'
@echo ' oldconfig - resolve any unresolved symbols in .config'
@echo ' hosttools - build sed for the host.'
@echo ' You can use these commands if the commands on the host'
@echo ' is unusable. Afterwards use it like:'
@echo ' make SED="$(objtree)/sed"'
@echo
@echo 'Installation:'
@echo ' install - install busybox into $(PREFIX)'
@echo ' uninstall'
@echo
@echo 'Development:'
@echo ' baseline - create busybox_old for bloatcheck.'
@echo ' bloatcheck - show size difference between old and new versions'
@echo ' check - run the test suite for all applets'
@echo ' checkhelp - check for missing help-entries in Config.in'
@echo ' randconfig - generate a random configuration'
@echo ' release - create a distribution tarball'
@echo ' sizes - show size of all enabled busybox symbols'
@echo ' objsizes - show size of each .o object built'
@echo
+2 -2
View File
@@ -194,5 +194,5 @@ Supported hardware:
Please feed suggestions, bug reports, insults, and bribes back to the busybox
maintainer:
Denis Vlasenko
<vda.linux@googlemail.com>
Rob Landley
<rob@landley.net>
+427
View File
@@ -0,0 +1,427 @@
# Rules.make for busybox
#
# Copyright (C) 1999-2005 by Erik Andersen <andersen@codepoet.org>
#
# Licensed under GPLv2, see the file LICENSE in this tarball for details.
#
# Pull in the user's busybox configuration
ifeq ($(filter $(noconfig_targets),$(MAKECMDGOALS)),)
-include $(top_builddir)/.config
endif
#--------------------------------------------------------
PROG := busybox
MAJOR_VERSION :=1
MINOR_VERSION :=2
SUBLEVEL_VERSION:=1
EXTRAVERSION :=
VERSION :=$(MAJOR_VERSION).$(MINOR_VERSION).$(SUBLEVEL_VERSION)$(EXTRAVERSION)
BUILDTIME := $(shell TZ=UTC date -u "+%Y.%m.%d-%H:%M%z")
#--------------------------------------------------------
# With a modern GNU make(1) (highly recommended, that's what all the
# developers use), all of the following configuration values can be
# overridden at the command line. For example:
# make CROSS=powerpc-linux- top_srcdir="$HOME/busybox" PREFIX=/mnt/app
#--------------------------------------------------------
# If you are running a cross compiler, you will want to set 'CROSS'
# to something more interesting... Target architecture is determined
# by asking the CC compiler what arch it compiles things for, so unless
# your compiler is broken, you should not need to specify TARGET_ARCH
CROSS =$(strip $(subst ",, $(strip $(CROSS_COMPILER_PREFIX))))
# be gentle to vi coloring.. "))
CC = $(CROSS)gcc
AR = $(CROSS)ar
AS = $(CROSS)as
LD = $(CROSS)ld
NM = $(CROSS)nm
STRIP = $(CROSS)strip
ELF2FLT = $(CROSS)elf2flt
CPP = $(CC) -E
SED ?= sed
BZIP2 ?= bzip2
# What OS are you compiling busybox for? This allows you to include
# OS specific things, syscall overrides, etc.
TARGET_OS=linux
# Ensure consistent sort order, 'gcc -print-search-dirs' behavior, etc.
LC_ALL:= C
# This must bind late because srcdir is reset for every source subdirectory.
INCS:=-I$(top_builddir)/include -I$(top_srcdir)/include
CFLAGS=$(INCS) -I$(srcdir) -D_GNU_SOURCE
CFLAGS+=$(CHECKED_CFLAGS)
ARFLAGS=cru
# gcc centric. Perhaps fiddle with findstring gcc,$(CC) for the rest
# get the CC MAJOR/MINOR version
CC_MAJOR:=$(shell printf "%02d" $(shell echo __GNUC__ | $(CC) -E -xc - | tail -n 1))
CC_MINOR:=$(shell printf "%02d" $(shell echo __GNUC_MINOR__ | $(CC) -E -xc - | tail -n 1))
#--------------------------------------------------------
export VERSION BUILDTIME HOSTCC HOSTCFLAGS CROSS CC AR AS LD NM STRIP CPP
ifeq ($(strip $(TARGET_ARCH)),)
TARGET_ARCH:=$(shell $(CC) -dumpmachine | $(SED) -e s'/-.*//' \
-e 's/i.86/i386/' \
-e 's/sparc.*/sparc/' \
-e 's/arm.*/arm/g' \
-e 's/m68k.*/m68k/' \
-e 's/ppc/powerpc/g' \
-e 's/v850.*/v850/g' \
-e 's/sh[234]/sh/' \
-e 's/mips-.*/mips/' \
-e 's/mipsel-.*/mipsel/' \
-e 's/cris.*/cris/' \
)
endif
# A nifty macro to make testing gcc features easier, but note that everything
# that uses this _must_ use := or it will be re-evaluated everytime it is
# referenced.
ifeq ($(strip $(BUILD_VERBOSE)),2)
VERBOSE_CHECK_CC=echo CC=\"$(1)\" check_cc $(2) >&2;
endif
check_cc=$(shell \
$(VERBOSE_CHECK_CC) \
if [ "x$(1)" != "x" ] && [ "x$(2)" != "x" ]; then \
echo "int i;" > ./conftest.c; \
if $(1) $(2) -c -o conftest.o conftest.c > /dev/null 2>&1; \
then echo "$(2)"; else echo "$(3)"; fi ; \
rm -f conftest.c conftest.o; \
fi)
ifneq ($(filter $(nocheck_targets),$(MAKECMDGOALS)),)
check_cc:=
endif
# A not very robust macro to check for available ld flags
ifeq ($(strip $(BUILD_VERBOSE)),2)
VERBOSE_CHECK_LD=echo LD=\"$(1)\" check_ld $(2) >&2;
endif
check_ld=$(shell \
$(VERBOSE_CHECK_LD) \
if [ "x$(1)" != "x" ] && [ "x$(2)" != "x" ]; then \
$(1) -o /dev/null -b binary /dev/null > /dev/null 2>&1 && \
echo "-Wl,$(2)" ; \
fi)
ifneq ($(filter $(nocheck_targets),$(MAKECMDGOALS)),)
check_ld:=
endif
# A not very robust macro to check for available strip flags
ifeq ($(strip $(BUILD_VERBOSE)),2)
VERBOSE_CHECK_STRIP=echo STRIPCMD=\"$(1)\" check_strip $(2) >&2;
endif
check_strip=$(shell \
$(VERBOSE_CHECK_STRIP) \
if [ "x$(1)" != "x" ] && [ "x$(2)" != "x" ]; then \
echo "int i;" > ./conftest.c ; \
$(CC) -c -o conftest.o conftest.c > /dev/null 2>&1 ; \
$(1) $(2) conftest.o > /dev/null 2>&1 && \
echo "$(1) $(2)" || echo "$(3)"; \
rm -f conftest.c conftest.o > /dev/null 2>&1 ; \
fi)
ifneq ($(filter $(nocheck_targets),$(MAKECMDGOALS)),)
check_strip:=
endif
# Select the compiler needed to build binaries for your development system
HOSTCC = gcc
HOSTCFLAGS:=$(call check_cc,$(HOSTCC),-Wall,)
HOSTCFLAGS+=$(call check_cc,$(HOSTCC),-Wstrict-prototypes,)
HOSTCFLAGS+=$(call check_cc,$(HOSTCC),-O2,)
HOSTCFLAGS+=$(call check_cc,$(HOSTCC),-fomit-frame-pointer,)
LD_WHOLE_ARCHIVE:=$(shell echo "int i;" > conftest.c ; \
$(CC) -c -o conftest.o conftest.c ; \
echo "int main(void){return 0;}" > conftest_main.c ; \
$(CC) -c -o conftest_main.o conftest_main.c ; \
$(AR) $(ARFLAGS) conftest.a conftest.o ; \
$(CC) -Wl,--whole-archive conftest.a -Wl,--no-whole-archive \
conftest_main.o -o conftest > /dev/null 2>&1 \
&& echo "-Wl,--whole-archive" ; \
rm conftest_main.o conftest_main.c conftest.o conftest.c \
conftest.a conftest > /dev/null 2>&1 ; )
ifneq ($(findstring whole-archive,$(LD_WHOLE_ARCHIVE)),)
LD_NO_WHOLE_ARCHIVE:= -Wl,--no-whole-archive
endif
LD_START_GROUP:=$(shell echo "int bar(void){return 0;}" > conftest.c ; \
$(CC) -c -o conftest.o conftest.c ; \
echo "int main(void){return bar();}" > conftest_main.c ; \
$(CC) -c -o conftest_main.o conftest_main.c ; \
$(AR) $(ARFLAGS) conftest.a conftest.o ; \
$(CC) -Wl,--start-group conftest.a conftest_main.o -Wl,--end-group \
-o conftest > /dev/null 2>&1 && echo "-Wl,--start-group" ; \
rm conftest_main.o conftest_main.c conftest.o conftest.c \
conftest.a conftest > /dev/null 2>&1 ; )
ifneq ($(findstring start-group,$(LD_START_GROUP)),)
LD_END_GROUP:= -Wl,--end-group
endif
CHECKED_LDFLAGS := $(call check_ld,$(LD),--warn-common,)
# Pin CHECKED_CFLAGS with := so it's only evaluated once.
CHECKED_CFLAGS:=$(call check_cc,$(CC),-Wall,)
CHECKED_CFLAGS+=$(call check_cc,$(CC),-Wstrict-prototypes,)
CHECKED_CFLAGS+=$(call check_cc,$(CC),-Wshadow,)
CHECKED_CFLAGS+=$(call check_cc,$(CC),-funsigned-char,)
CHECKED_CFLAGS+=$(call check_cc,$(CC),-mmax-stack-frame=256,)
CHECKED_CFLAGS+=$(call check_cc,$(CC),-fno-builtin-strlen)
# Preemptively pin this too.
PROG_CFLAGS:=
#--------------------------------------------------------
# Arch specific compiler optimization stuff should go here.
# Unless you want to override the defaults, do not set anything
# for OPTIMIZATION...
# use '-Os' optimization if available, else use -O2
OPTIMIZATION:=$(call check_cc,$(CC),-Os,-O2)
ifeq ($(CONFIG_BUILD_AT_ONCE),y)
# gcc 2.95 exits with 0 for "unrecognized option"
ifeq ($(strip $(shell [ $(CC_MAJOR) -ge 3 ] ; echo $$?)),0)
CFLAGS_COMBINE:=$(call check_cc,$(CC),--combine,)
endif
OPTIMIZATION+=$(call check_cc,$(CC),-funit-at-a-time,)
OPTIMIZATION+=$(call check_cc,$(CC),-fgcse-after-reload,)
ifneq ($(CONFIG_BUILD_LIBBUSYBOX),y)
# http://gcc.gnu.org/bugzilla/show_bug.cgi?id=25795
# This prevents us from using -fwhole-program when we build the lib
PROG_CFLAGS+=$(call check_cc,$(CC),-fwhole-program,)
endif # CONFIG_BUILD_LIBBUSYBOX
endif # CONFIG_BUILD_AT_ONCE
LIB_LDFLAGS:=$(call check_ld,$(LD),--enable-new-dtags,)
#LIB_LDFLAGS+=$(call check_ld,$(LD),--reduce-memory-overheads,)
#LIB_LDFLAGS+=$(call check_ld,$(LD),--as-needed,)
#LIB_LDFLAGS+=$(call check_ld,$(LD),--warn-shared-textrel,)
# Some nice architecture specific optimizations
ifeq ($(strip $(TARGET_ARCH)),arm)
OPTIMIZATION+=-fstrict-aliasing
endif
ifeq ($(strip $(TARGET_ARCH)),i386)
OPTIMIZATION+=$(call check_cc,$(CC),-march=i386,)
# gcc-4.0 and older seem to benefit from these
#ifneq ($(strip $(shell [ $(CC_MAJOR) -ge 4 -a $(CC_MINOR) -ge 1 ] ; echo $$?)),0)
OPTIMIZATION+=$(call check_cc,$(CC),-mpreferred-stack-boundary=2,)
OPTIMIZATION+=$(call check_cc,$(CC),-falign-functions=1 -falign-jumps=1 -falign-loops=1,\
-malign-functions=0 -malign-jumps=0 -malign-loops=0)
#endif # gcc-4.0 and older
# gcc-4.1 and beyond seem to benefit from these
ifeq ($(strip $(shell [ $(CC_MAJOR) -ge 4 -a $(CC_MINOR) -ge 1 ] ; echo $$?)),0)
# turn off flags which hurt -Os
OPTIMIZATION+=$(call check_cc,$(CC),-fno-tree-loop-optimize,)
OPTIMIZATION+=$(call check_cc,$(CC),-fno-tree-dominator-opts,)
OPTIMIZATION+=$(call check_cc,$(CC),-fno-strength-reduce,)
OPTIMIZATION+=$(call check_cc,$(CC),-fno-branch-count-reg,)
endif # gcc-4.1 and beyond
endif
OPTIMIZATION+=$(call check_cc,$(CC),-fomit-frame-pointer,)
OPTIMIZATION+=$(call check_cc,$(CC),-ffunction-sections -fdata-sections,)
#
#--------------------------------------------------------
# If you're going to do a lot of builds with a non-vanilla configuration,
# it makes sense to adjust parameters above, so you can type "make"
# by itself, instead of following it by the same half-dozen overrides
# every time. The stuff below, on the other hand, is probably less
# prone to casual user adjustment.
#
ifeq ($(strip $(CONFIG_LFS)),y)
# For large file summit support
CFLAGS+=-D_LARGEFILE_SOURCE -D_LARGEFILE64_SOURCE -D_FILE_OFFSET_BITS=64
endif
ifeq ($(strip $(CONFIG_DMALLOC)),y)
# For testing mem leaks with dmalloc
CFLAGS+=-DDMALLOC
LIBRARIES:=-ldmalloc
else
ifeq ($(strip $(CONFIG_EFENCE)),y)
LIBRARIES:=-lefence
endif
endif
# Debugging info
ifeq ($(strip $(CONFIG_DEBUG)),y)
CFLAGS +=-g
else
CFLAGS +=-DNDEBUG
CHECKED_LDFLAGS += $(call check_ld,$(LD),--sort-common,)
CHECKED_LDFLAGS += $(call check_ld,--gc-sections,)
endif
ifneq ($(strip $(CONFIG_DEBUG_PESSIMIZE)),y)
CFLAGS += $(OPTIMIZATION)
endif
# warn a bit more verbosely for non-release versions
ifneq ($(EXTRAVERSION),)
CHECKED_CFLAGS+=$(call check_cc,$(CC),-Wstrict-prototypes,)
CHECKED_CFLAGS+=$(call check_cc,$(CC),-Wmissing-prototypes,)
CHECKED_CFLAGS+=$(call check_cc,$(CC),-Wmissing-declarations,)
CHECKED_CFLAGS+=$(call check_cc,$(CC),-Wunused,)
CHECKED_CFLAGS+=$(call check_cc,$(CC),-Winit-self,)
CHECKED_CFLAGS+=$(call check_cc,$(CC),-Wshadow,)
CHECKED_CFLAGS+=$(call check_cc,$(CC),-Wcast-align,)
endif
STRIPCMD:=$(call check_strip,$(STRIP),-s --remove-section=.note --remove-section=.comment,$(STRIP))
ifeq ($(strip $(CONFIG_STATIC)),y)
PROG_CFLAGS += $(call check_cc,$(CC),-static,)
endif
CFLAGS_SHARED := $(call check_cc,$(CC),-shared,)
LIB_CFLAGS+=$(CFLAGS_SHARED)
ifeq ($(strip $(CONFIG_BUILD_LIBBUSYBOX)),y)
CFLAGS_PIC:= $(call check_cc,$(CC),-fPIC,)
LIB_CFLAGS+=$(CFLAGS_PIC)
endif
ifeq ($(strip $(CONFIG_SELINUX)),y)
LIBRARIES += -lselinux
endif
ifeq ($(strip $(PREFIX)),)
PREFIX:=`pwd`/_install
endif
ifneq ($(strip $(CONFIG_GETOPT_LONG)),y)
CFLAGS += -D__need_getopt
endif
# Additional complications due to support for pristine source dir.
# Include files in the build directory should take precedence over
# the copy in top_srcdir, both during the compilation phase and the
# shell script that finds the list of object files.
# Work in progress by <ldoolitt@recycle.lbl.gov>.
OBJECTS:=$(APPLET_SOURCES:.c=.o) busybox.o usage.o applets.o
CFLAGS += $(CHECKED_CFLAGS) $(CROSS_CFLAGS)
LDFLAGS += $(CHECKED_LDFLAGS)
ifdef BB_INIT_SCRIPT
CFLAGS += -DINIT_SCRIPT='"$(BB_INIT_SCRIPT)"'
endif
# Put user-supplied flags at the end, where they
# have a chance of winning.
-include $(top_builddir)/.config.mak
#------------------------------------------------------------
# Installation options
ifeq ($(strip $(CONFIG_INSTALL_APPLET_HARDLINKS)),y)
INSTALL_OPTS=--hardlinks
endif
ifeq ($(strip $(CONFIG_INSTALL_APPLET_SYMLINKS)),y)
INSTALL_OPTS=--symlinks
endif
ifeq ($(strip $(CONFIG_INSTALL_APPLET_DONT)),y)
INSTALL_OPTS=
endif
#------------------------------------------------------------
# Make the output nice and tight
MAKEFLAGS += --no-print-directory
export MAKE_IS_SILENT=n
ifneq ($(findstring s,$(MAKEFLAGS)),)
export MAKE_IS_SILENT=y
SECHO := @-false
DISP := sil
Q := @
else
ifneq ($(BUILD_VERBOSE),)
SECHO := @-false
DISP := ver
Q :=
else
SECHO := @echo
DISP := pur
Q := @
endif
endif
show_objs = $(subst $(top_builddir)/,,$(subst ../,,$@))
pur_disp_compile.c = echo " "CC $(show_objs)
pur_disp_compile.h = echo " "HOSTCC $(show_objs)
pur_disp_strip = echo " "STRIP $(show_objs)
pur_disp_link = echo " "LINK $(show_objs)
pur_disp_link.h = echo " "HOSTLINK $(show_objs)
pur_disp_ar = echo " "AR $(ARFLAGS) $(show_objs)
pur_disp_elf2flt = echo " "ELF2FLT $(ELF2FLTFLAGS) $(show_objs)
sil_disp_compile.c = true
sil_disp_compile.h = true
sil_disp_strip = true
sil_disp_link = true
sil_disp_link.h = true
sil_disp_ar = true
sil_disp_elf2flt = true
ver_disp_compile.c = echo $(cmd_compile.c)
ver_disp_compile.h = echo $(cmd_compile.h)
ver_disp_strip = echo $(cmd_strip)
ver_disp_link = echo $(cmd_link)
ver_disp_link.h = echo $(cmd_link.h)
ver_disp_ar = echo $(cmd_ar)
ver_disp_elf2flt = echo $(cmd_elf2flt)
disp_compile.c = $($(DISP)_disp_compile.c)
disp_compile.h = $($(DISP)_disp_compile.h)
disp_strip = $($(DISP)_disp_strip)
disp_link = $($(DISP)_disp_link)
disp_link.h = $($(DISP)_disp_link.h)
disp_ar = $($(DISP)_disp_ar)
disp_gen = $(SECHO) " "GEN $@ ; true
disp_doc = $(SECHO) " "DOC $(subst docs/,,$@) ; true
disp_elf2flt = $($(DISP)_disp_elf2flt)
cmd_compile.c = $(CC) $(CFLAGS) $(EXTRA_CFLAGS) -c -o $@ $<
cmd_compile.h = $(HOSTCC) $(HOSTCFLAGS) $(INCS) -c -o $@ $<
cmd_strip = $(STRIPCMD) $@
cmd_link = $(CC) $(CFLAGS) $(EXTRA_CFLAGS) $(LDFLAGS) \
$(PROG_CFLAGS) $(PROG_LDFLAGS) $(CFLAGS_COMBINE) \
-o $@ $(LD_START_GROUP) \
$(APPLETS_DEFINE) $(APPLET_SRC) \
$(BUSYBOX_DEFINE) $(BUSYBOX_SRC) $(libraries-y) \
$(LDBUSYBOX) $(LIBRARIES) \
$(LD_END_GROUP)
cmd_link.so = $(CC) $(CFLAGS) $(EXTRA_CFLAGS) $(LDFLAGS) \
$(LIB_CFLAGS) $(CFLAGS_COMBINE) $(LIB_LDFLAGS) \
-o $(@) $(LD_START_GROUP) $(LD_WHOLE_ARCHIVE) \
$(LIBRARY_DEFINE) $(^) \
$(LD_NO_WHOLE_ARCHIVE) $(LD_END_GROUP)
cmd_link.h = $(HOSTCC) $(HOSTCFLAGS) $(INCS) $< -o $@
cmd_ar = $(AR) $(ARFLAGS) $@ $^
cmd_elf2flt = $(ELF2FLT) $(ELF2FLTFLAGS) $< -o $@
compile.c = @$(disp_compile.c) ; $(cmd_compile.c)
compile.h = @$(disp_compile.h) ; $(cmd_compile.h)
do_strip = @$(disp_strip) ; $(cmd_strip)
do_link = @$(disp_link) ; $(cmd_link)
do_link.so = @$(disp_link) ; $(cmd_link.so)
do_link.h = @$(disp_link.h) ; $(cmd_link.h)
do_ar = @$(disp_ar) ; $(cmd_ar)
do_elf2flt = @$(disp_elf2flt) ; $(cmd_elf2flt)
uppercase = $(shell echo $1 | $(SED) -e "y/abcdefghijklmnopqrstuvwxyz/ABCDEFGHIJKLMNOPQRSTUVWXYZ/")
%.a:
@if test -z "$($(call uppercase,$*)_DIR)" ; then \
echo "Invalid target $@" ; \
exit 1 ; \
fi
$(Q)$(MAKE) $($(call uppercase,$*)_DIR)$@
.PHONY: dummy
+17 -22
View File
@@ -33,7 +33,7 @@ Rob Landley <rob@landley.net>:
depmod
busybox lacks a way to update module deps when running from firmware without the
use of the depmod.pl (perl is to bloated for most embedded setups) and or orig
modutils. The orig depmod is rather pointless to have to add to a firmware image
modutils. The orig depmod is rather pointless to have to add to a firmware image
in when we already have a insmod/rmmod and friends.
Unify base64 handling.
There's base64 encoding and decoding going on in:
@@ -117,20 +117,13 @@ Rob Landley <rob@landley.net>:
This one's open to everybody, but I'll wind up doing it...
Bernhard Fischer <busybox@busybox.net> suggests to look at these:
Bernhard Fischer <rep.nop@anon.at>:
Makefile stuff:
make -j is broken, -j1 is forced atm
New debug options:
-Wlarger-than-127
Cleanup any big users
-Wunused-parameter
Facilitate applet PROTOTYPES to provide means for having applets that
do a) not take any arguments b) need only one of argc or argv c) need
both argc and argv. All of these three options should go for the most
feature complete denominator.
Collate BUFSIZ IOBUF_SIZE MY_BUF_SIZE PIPE_PROGRESS_SIZE BUFSIZE PIPESIZE
make bb_common_bufsiz1 configurable, size wise.
make pipesize configurable, size wise.
Use bb_common_bufsiz1 throughout applets!
Add chrt applet. Please CC Bernhard if you suggest a patch.
Use bb_common_bufsiz1?
As yet unclaimed:
@@ -142,10 +135,10 @@ diff
Make sure we handle empty files properly:
From the patch man page:
you can remove a file by sending out a context diff that compares
the file to be deleted with an empty file dated the Epoch. The
file will be removed unless patch is conforming to POSIX and the
-E or --remove-empty-files option is not given.
   you can remove a file by sending out a context diff that compares
   the file to be deleted with an empty file dated the Epoch.  The
   file will be removed unless patch is conforming to POSIX and the
   -E or --remove-empty-files option is not given.
---
patch
Should have simple fuzz factor support to apply patches at an offset which
@@ -164,11 +157,9 @@ man
---
ar
Write support?
----
stty / catv
stty's visible() function and catv's guts are identical. Merge them into
an appropriate libbb function.
----
---
crond
turn FEATURE_DEBUG_OPT into ENABLE_FEATURE_CROND_DEBUG_OPT
Architectural issues:
@@ -264,7 +255,7 @@ FEATURE_CLEAN_UP
jumps out of the normal flow control and bypasses any cleanup code we
put at the end of our applets.
It's possible to add hooks to libbb functions like xmalloc() and xopen()
It's possible to add hooks to libbb functions like xmalloc() and bb_xopen()
to add their entries to a linked list, which could be traversed and
freed/closed automatically. (This would need to be able to free just the
entries after a checkpoint to be usable for a forkless standalone shell.
@@ -296,6 +287,9 @@ Minor stuff:
-> fprintf(stderr, "unalias: %s not found\n", *argptr);
---
possible code duplication ingroup() and is_a_group_member()
---
unify itoa: netstat.c, hush.c, lash.c, msh.c
Put one single, robust version into e.g. safe_strtol.c
---
Move __get_hz() to a better place and (re)use it in route.c, ash.c, msh.c
---
@@ -311,3 +305,4 @@ sigblock(), siggetmask(), sigsetmask(), sigmask() -> sigprocmask et al
---
vdprintf() -> similar sized functionality
---
-22
View File
@@ -1,22 +0,0 @@
# Makefile for busybox
#
# Copyright (C) 1999-2005 by Erik Andersen <andersen@codepoet.org>
#
# Licensed under the GPL v2, see the file LICENSE in this tarball.
obj-y:=
obj-y += applets.o
obj-y += busybox.o
# Generated file needs additional love
applets/applets.o: include/usage_compressed.h
hostprogs-y += usage
always := $(hostprogs-y)
HOSTCFLAGS_usage.o = -I$(srctree)/include
quiet_cmd_gen_usage_compressed = GEN include/usage_compressed.h
cmd_gen_usage_compressed = $(srctree)/applets/usage_compressed include/usage_compressed.h applets
include/usage_compressed.h: $(srctree)/include/usage.h applets/usage
$(call cmd,gen_usage_compressed)
+23
View File
@@ -0,0 +1,23 @@
# Makefile for busybox
#
# Copyright (C) 1999-2005 by Erik Andersen <andersen@codepoet.org>
#
# Licensed under the GPL v2, see the file LICENSE in this tarball.
ifndef top_srcdir
top_srcdir=..
endif
ifndef top_builddir
top_builddir=..
endif
srcdir=$(top_srcdir)/applets
APPLETS_DIR:=./
include $(top_srcdir)/Rules.mak
include $(top_builddir)/.config
include $(srcdir)/Makefile.in
all: $(libraries-y)
-include $(top_builddir).depend
clean:
rm -f *.o *.a $(AR_TARGET)
+26
View File
@@ -0,0 +1,26 @@
# Makefile for busybox
#
# Copyright (C) 1999-2005 by Erik Andersen <andersen@codepoet.org>
#
# Licensed under the GPL v2, see the file LICENSE in this tarball.
APPLETS_AR:=applets.a
ifndef $(APPLETS_DIR)
APPLETS_DIR:=$(top_builddir)/applets/
endif
srcdir=$(top_srcdir)/applets
APPLET_SRC:= $(patsubst %,$(srcdir)/%,applets.c busybox.c version.c)
APPLET_OBJ:= $(patsubst $(srcdir)/%.c,$(APPLETS_DIR)%.o, $(APPLET_SRC))
APPLET_SRC-y+=$(APPLET_SRC)
APPLET_SRC-a+=$(APPLET_SRC)
libraries-y+=$(APPLETS_DIR)$(APPLETS_AR)
$(APPLETS_DIR)$(APPLETS_AR): $(APPLET_OBJ)
$(do_ar)
$(APPLET_OBJ): $(top_builddir)/.config
$(APPLET_OBJ): $(APPLETS_DIR)%.o: $(srcdir)/%.c
$(compile.c)
+81 -95
View File
@@ -13,18 +13,10 @@
*/
#include "busybox.h"
#include <unistd.h>
#include <string.h>
#include <assert.h>
/* Apparently uclibc defines __GLIBC__ (compat trick?). Oh well. */
#if ENABLE_STATIC && defined(__GLIBC__) && !defined(__UCLIBC__)
#warning Static linking against glibc produces buggy executables
#warning (glibc does not cope well with ld --gc-sections).
#warning See sources.redhat.com/bugzilla/show_bug.cgi?id=3400
#warning Note that glibc is unsuitable for static linking anyway.
#warning If you still want to do it, remove -Wl,--gc-sections
#warning from top-level Makefile and remove this warning.
#endif
#if ENABLE_SHOW_USAGE && !ENABLE_FEATURE_COMPRESS_USAGE
static const char usage_messages[] =
#define MAKE_USAGE
@@ -44,45 +36,47 @@ static const char usage_messages[] =
static struct BB_applet *applet_using;
/* The -1 arises because of the {0,NULL,0,-1} entry above. */
const unsigned short NUM_APPLETS = (sizeof (applets) / sizeof (struct BB_applet) - 1);
const size_t NUM_APPLETS = (sizeof (applets) / sizeof (struct BB_applet) - 1);
#ifdef CONFIG_FEATURE_SUID_CONFIG
#include <ctype.h>
#include "pwd_.h"
#include "grp_.h"
#define CONFIG_FILE "/etc/busybox.conf"
/* applets [] is const, so we have to define this "override" structure */
static struct BB_suid_config
{
struct BB_applet *m_applet;
struct BB_applet *m_applet;
uid_t m_uid;
gid_t m_gid;
mode_t m_mode;
uid_t m_uid;
gid_t m_gid;
mode_t m_mode;
struct BB_suid_config *m_next;
struct BB_suid_config *m_next;
} *suid_config;
static int suid_cfg_readable;
/* check if u is member of group g */
static int ingroup(uid_t u, gid_t g)
static int ingroup (uid_t u, gid_t g)
{
struct group *grp = getgrgid(g);
struct group *grp = getgrgid (g);
if (grp) {
char **mem;
if (grp) {
char **mem;
for (mem = grp->gr_mem; *mem; mem++) {
struct passwd *pwd = getpwnam(*mem);
for (mem = grp->gr_mem; *mem; mem++) {
struct passwd *pwd = getpwnam (*mem);
if (pwd && (pwd->pw_uid == u))
return 1;
}
if (pwd && (pwd->pw_uid == u))
return 1;
}
return 0;
}
return 0;
}
/* This should probably be a libbb routine. In that case,
@@ -143,7 +137,7 @@ static void parse_config_file(void)
|| !S_ISREG(st.st_mode) /* Not a regular file? */
|| (st.st_uid != 0) /* Not owned by root? */
|| (st.st_mode & (S_IWGRP | S_IWOTH)) /* Writable by non-root? */
|| !(f = fopen(config_file, "r")) /* Cannot open? */
|| !(f = fopen(config_file, "r")) /* Can not open? */
) {
return;
}
@@ -272,8 +266,8 @@ static void parse_config_file(void)
sct->m_uid = strtoul(s, &e2, 10);
if (*e2 || (s == e2)) {
struct passwd *pwd = getpwnam(s);
if (!pwd) {
struct passwd *pwd;
if (!(pwd = getpwnam(s))) {
parse_error("user");
}
sct->m_uid = pwd->pw_uid;
@@ -320,70 +314,64 @@ static void parse_config_file(void)
}
#else
#define parse_config_file() ((void)0)
#define parse_config_file()
#endif /* CONFIG_FEATURE_SUID_CONFIG */
#ifdef CONFIG_FEATURE_SUID
static void check_suid(struct BB_applet *applet)
static void check_suid (struct BB_applet *applet)
{
uid_t ruid = getuid(); /* real [ug]id */
uid_t rgid = getgid();
uid_t ruid = getuid (); /* real [ug]id */
uid_t rgid = getgid ();
#ifdef CONFIG_FEATURE_SUID_CONFIG
if (suid_cfg_readable) {
struct BB_suid_config *sct;
if (suid_cfg_readable) {
struct BB_suid_config *sct;
for (sct = suid_config; sct; sct = sct->m_next) {
if (sct->m_applet == applet)
break;
}
if (sct) {
mode_t m = sct->m_mode;
for (sct = suid_config; sct; sct = sct->m_next) {
if (sct->m_applet == applet)
break;
}
if (sct) {
mode_t m = sct->m_mode;
if (sct->m_uid == ruid)
/* same uid */
m >>= 6;
else if ((sct->m_gid == rgid) || ingroup(ruid, sct->m_gid))
/* same group / in group */
m >>= 3;
if (sct->m_uid == ruid) /* same uid */
m >>= 6;
else if ((sct->m_gid == rgid) || ingroup (ruid, sct->m_gid)) /* same group / in group */
m >>= 3;
if (!(m & S_IXOTH)) /* is x bit not set ? */
bb_error_msg_and_die("you have no permission to run this applet!");
if (!(m & S_IXOTH)) /* is x bit not set ? */
bb_error_msg_and_die ("You have no permission to run this applet!");
if (sct->m_gid != 0) {
/* _both_ have to be set for sgid */
if ((sct->m_mode & (S_ISGID | S_IXGRP)) == (S_ISGID | S_IXGRP)) {
xsetgid(sct->m_gid);
} else xsetgid(rgid); /* no sgid -> drop */
}
if (sct->m_uid != 0) {
if (sct->m_mode & S_ISUID) xsetuid(sct->m_uid);
else xsetuid(ruid); /* no suid -> drop */
}
} else {
/* default: drop all privileges */
xsetgid(rgid);
xsetuid(ruid);
}
return;
if ((sct->m_mode & (S_ISGID | S_IXGRP)) == (S_ISGID | S_IXGRP)) { /* *both* have to be set for sgid */
xsetgid(sct->m_gid);
} else xsetgid(rgid); /* no sgid -> drop */
if (sct->m_mode & S_ISUID) xsetuid(sct->m_uid);
else xsetuid(ruid); /* no suid -> drop */
} else {
/* default: drop all privileges */
xsetgid(rgid);
xsetuid(ruid);
}
return;
} else {
#ifndef CONFIG_FEATURE_SUID_CONFIG_QUIET
static int onetime = 0;
static int onetime = 0;
if (!onetime) {
onetime = 1;
fprintf(stderr, "Using fallback suid method\n");
}
#endif
if (!onetime) {
onetime = 1;
fprintf (stderr, "Using fallback suid method\n");
}
#endif
}
#endif
if (applet->need_suid == _BB_SUID_ALWAYS) {
if (geteuid()) bb_error_msg_and_die("applet requires root privileges!");
} else if (applet->need_suid == _BB_SUID_NEVER) {
xsetgid(rgid); /* drop all privileges */
xsetuid(ruid);
}
if (applet->need_suid == _BB_SUID_ALWAYS) {
if (geteuid()) bb_error_msg_and_die("Applet requires root privileges!");
} else if (applet->need_suid == _BB_SUID_NEVER) {
xsetgid(rgid); /* drop all privileges */
xsetuid(ruid);
}
}
#else
#define check_suid(x)
@@ -391,7 +379,7 @@ static void check_suid(struct BB_applet *applet)
#ifdef CONFIG_FEATURE_COMPRESS_USAGE
#if ENABLE_FEATURE_COMPRESS_USAGE
#include "usage_compressed.h"
#include "unarchive.h"
@@ -438,7 +426,7 @@ static const char *unpack_usage_messages(void)
#define unpack_usage_messages() usage_messages
#endif /* ENABLE_FEATURE_COMPRESS_USAGE */
void bb_show_usage(void)
void bb_show_usage (void)
{
if (ENABLE_SHOW_USAGE) {
const char *format_string;
@@ -451,41 +439,39 @@ void bb_show_usage(void)
format_string = "%s\n\nUsage: %s %s\n\n";
if (*usage_string == '\b')
format_string = "%s\n\nNo help available.\n\n";
fprintf(stderr, format_string, bb_msg_full_version,
fprintf (stderr, format_string, bb_msg_full_version,
applet_using->name, usage_string);
}
exit(xfunc_error_retval);
exit (bb_default_error_retval);
}
static int applet_name_compare(const void *name, const void *vapplet)
{
const struct BB_applet *applet = vapplet;
const struct BB_applet *applet = vapplet;
return strcmp(name, applet->name);
return strcmp(name, applet->name);
}
extern const size_t NUM_APPLETS;
struct BB_applet *find_applet_by_name(const char *name)
{
return bsearch(name, applets, NUM_APPLETS, sizeof(struct BB_applet),
applet_name_compare);
return bsearch(name, applets, NUM_APPLETS, sizeof(struct BB_applet),
applet_name_compare);
}
void run_applet_by_name(const char *name, int argc, char **argv)
{
if (ENABLE_FEATURE_SUID_CONFIG)
parse_config_file();
if (ENABLE_FEATURE_SUID_CONFIG) parse_config_file();
if (!strncmp(name, "busybox", 7))
exit(busybox_main(argc, argv));
if (!strncmp(name, "busybox", 7)) busybox_main(argc, argv);
/* Do a binary search to find the applet entry given the name. */
applet_using = find_applet_by_name(name);
if (applet_using) {
applet_name = applet_using->name;
if (argc == 2 && !strcmp(argv[1], "--help"))
bb_show_usage();
if (ENABLE_FEATURE_SUID)
check_suid(applet_using);
exit(applet_using->main(argc, argv));
bb_applet_name = applet_using->name;
if(argc==2 && !strcmp(argv[1], "--help")) bb_show_usage();
if(ENABLE_FEATURE_SUID) check_suid(applet_using);
exit((*(applet_using->main))(argc, argv));
}
}
+53 -45
View File
@@ -2,11 +2,21 @@
/*
* BusyBox' main applet dispatcher.
*
* Licensed under GPLv2, see file LICENSE in this tarball for details.
* Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
*/
#include "busybox.h"
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <stdlib.h>
#if ENABLE_LOCALE_SUPPORT
#include <locale.h>
#else
#define setlocale(x,y)
#endif
const char *applet_name ATTRIBUTE_EXTERNALLY_VISIBLE;
const char *bb_applet_name ATTRIBUTE_EXTERNALLY_VISIBLE;
#ifdef CONFIG_FEATURE_INSTALLER
/*
@@ -14,8 +24,8 @@ const char *applet_name ATTRIBUTE_EXTERNALLY_VISIBLE;
* this should be consistent w/ the enum, busybox.h::Location,
* or else...
*/
static const char usr_bin [] = "/usr/bin";
static const char usr_sbin[] = "/usr/sbin";
static const char usr_bin [] ="/usr/bin";
static const char usr_sbin[] ="/usr/sbin";
static const char* const install_dir[] = {
&usr_bin [8], /* "", equivalent to "/" for concat_path_file() */
@@ -26,25 +36,25 @@ static const char* const install_dir[] = {
};
/* abstract link() */
typedef int (*link_func)(const char *, const char *);
typedef int (*__link_f)(const char *, const char *);
/* create (sym)links for each applet */
static void install_links(const char *busybox, int use_symbolic_links)
{
link_func lf = link;
__link_f Link = link;
char *fpc;
int i;
int rc;
if (use_symbolic_links)
lf = symlink;
Link = symlink;
for (i = 0; applets[i].name != NULL; i++) {
fpc = concat_path_file(
install_dir[applets[i].location],
applets[i].name);
rc = lf(busybox, fpc);
if (rc != 0 && errno != EEXIST) {
install_dir[applets[i].location], applets[i].name);
rc = Link(busybox, fpc);
if (rc!=0 && errno!=EEXIST) {
bb_perror_msg("%s", fpc);
}
free(fpc);
@@ -59,17 +69,16 @@ int main(int argc, char **argv)
{
const char *s;
applet_name = argv[0];
if (*applet_name == '-')
applet_name++;
while ((s = strchr(applet_name, '/')))
applet_name = s + 1;
bb_applet_name=argv[0];
if (*bb_applet_name == '-') bb_applet_name++;
for (s = bb_applet_name; *s ;)
if (*(s++) == '/') bb_applet_name = s;
/* Set locale for everybody except 'init' */
if (ENABLE_LOCALE_SUPPORT && getpid() != 1)
/* Set locale for everybody except `init' */
if(ENABLE_LOCALE_SUPPORT && getpid() != 1)
setlocale(LC_ALL, "");
run_applet_by_name(applet_name, argc, argv);
run_applet_by_name(bb_applet_name, argc, argv);
bb_error_msg_and_die("applet not found");
}
@@ -82,45 +91,44 @@ int busybox_main(int argc, char **argv)
*/
if (ENABLE_FEATURE_INSTALLER && argc > 1 && !strcmp(argv[1], "--install")) {
int use_symbolic_links = 0;
int rc = 0;
char *busybox;
/* to use symlinks, or not to use symlinks... */
if (argc > 2)
if (strcmp(argv[2], "-s") == 0)
if (argc > 2) {
if ((strcmp(argv[2], "-s") == 0)) {
use_symbolic_links = 1;
}
}
/* link */
// XXX: FIXME: this is broken. Why not just use argv[0] ?
busybox = xreadlink("/proc/self/exe");
if (!busybox)
return 1;
install_links(busybox, use_symbolic_links);
if (ENABLE_FEATURE_CLEAN_UP)
if (busybox) {
install_links(busybox, use_symbolic_links);
free(busybox);
return 0;
} else {
rc = 1;
}
return rc;
}
/* Deal with --help. (Also print help when called with no arguments) */
if (argc == 1 || !strcmp(argv[1], "--help") ) {
if (argc > 2) {
applet_name = argv[2];
run_applet_by_name(applet_name, 2, argv);
if (argc==1 || !strcmp(argv[1],"--help") ) {
if (argc>2) {
run_applet_by_name(bb_applet_name=argv[2], 2, argv);
} else {
const struct BB_applet *a;
int col, output_width;
output_width = 80 - sizeof("start-stop-daemon, ") - 8;
if (ENABLE_FEATURE_AUTOWIDTH) {
/* Obtain the terminal width. */
get_terminal_width_height(0, &output_width, NULL);
/* leading tab and room to wrap */
output_width -= sizeof("start-stop-daemon, ") + 8;
}
output_width -= 20;
} else output_width = 60;
printf("%s\n"
"Copyright (C) 1998-2006  Erik Andersen, Rob Landley, and others.\n"
"Licensed under GPLv2.  See source distribution for full notice.\n\n"
printf("%s\n\n"
"Usage: busybox [function] [arguments]...\n"
" or: [function] [arguments]...\n\n"
"\tBusyBox is a multi-call binary that combines many common Unix\n"
@@ -128,19 +136,19 @@ int busybox_main(int argc, char **argv)
"\tlink to busybox for each function they wish to use and BusyBox\n"
"\twill act like whatever it was invoked as!\n"
"\nCurrently defined functions:\n", bb_msg_full_version);
col = 0;
for (a = applets; a->name;) {
col += printf("%s%s", (col ? ", " : "\t"), a->name);
a++;
col=0;
for(a = applets; a->name;) {
col += printf("%s%s", (col ? ", " : "\t"), (a++)->name);
if (col > output_width && a->name) {
puts(",");
printf(",\n");
col = 0;
}
}
puts("\n");
return 0;
printf("\n\n");
exit(0);
}
} else run_applet_by_name(argv[1], argc - 1, argv + 1);
} else run_applet_by_name(argv[1], argc-1, argv+1);
bb_error_msg_and_die("applet not found");
}
+1 -1
View File
@@ -10,7 +10,7 @@
export LC_ALL=POSIX
export LC_CTYPE=POSIX
CONFIG_H=${1:-include/autoconf.h}
CONFIG_H=${1:-include/bb_config.h}
APPLETS_H=${2:-include/applets.h}
$HOSTCC -E -DMAKE_LINKS -include $CONFIG_H $APPLETS_H |
awk '/^[ \t]*LINK/{
-27
View File
@@ -1,27 +0,0 @@
/* Minimal wrapper to build an individual busybox applet.
*
* Copyright 2005 Rob Landley <rob@landley.net
*
* Licensed under GPL version 2, see file LICENSE in this tarball for details
*/
const char *applet_name;
#include <stdio.h>
#include <stdlib.h>
//Ok to remove? #include "bb_config.h"
#include "usage.h"
int main(int argc, char *argv[])
{
applet_name=argv[0];
return APPLET_main(argc,argv);
}
void bb_show_usage(void)
{
printf(APPLET_full_usage "\n");
exit(1);
}
+17
View File
@@ -0,0 +1,17 @@
/* vi: set sw=4 ts=4: */
/*
* Version stuff.
*
* Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
*/
#include "busybox.h"
#ifndef BB_EXTRA_VERSION
#define BANNER "BusyBox v" BB_VER " (" BB_BT ")"
#else
#define BANNER "BusyBox v" BB_VER " (" BB_EXTRA_VERSION ")"
#endif
const char BB_BANNER[]=BANNER;
const char * const bb_msg_full_version = BANNER " multi-call binary";
-5
View File
@@ -1,5 +0,0 @@
# ==========================================================================
# Build system
# ==========================================================================
CFLAGS += -march=i386 -mpreferred-stack-boundary=2
+53 -53
View File
@@ -5,7 +5,7 @@
menu "Archival Utilities"
config AR
config CONFIG_AR
bool "ar"
default n
help
@@ -28,17 +28,17 @@ config AR
Unless you have a specific application which requires ar, you should
probably say N here.
config FEATURE_AR_LONG_FILENAMES
config CONFIG_FEATURE_AR_LONG_FILENAMES
bool "Enable support for long filenames (not need for debs)"
default n
depends on AR
depends on CONFIG_AR
help
By default the ar format can only store the first 15 characters of the
filename, this option removes that limitation.
It supports the GNU ar long filename method which moves multiple long
filenames into a the data section of a new ar entry.
config BUNZIP2
config CONFIG_BUNZIP2
bool "bunzip2"
default n
help
@@ -54,7 +54,7 @@ config BUNZIP2
Unless you have a specific application which requires bunzip2, you
should probably say N here.
config CPIO
config CONFIG_CPIO
bool "cpio"
default n
help
@@ -68,7 +68,7 @@ config CPIO
Unless you have a specific application which requires cpio, you should
probably say N here.
config DPKG
config CONFIG_DPKG
bool "dpkg"
default n
help
@@ -77,7 +77,7 @@ config DPKG
This implementation of dpkg has a number of limitations, you should use the
official dpkg if possible.
config DPKG_DEB
config CONFIG_DPKG_DEB
bool "dpkg_deb"
default n
help
@@ -88,16 +88,16 @@ config DPKG_DEB
Unless you have a specific application which requires dpkg-deb, you should
probably say N here.
config FEATURE_DPKG_DEB_EXTRACT_ONLY
config CONFIG_FEATURE_DPKG_DEB_EXTRACT_ONLY
bool "extract only (-x)"
default n
depends on DPKG_DEB
depends on CONFIG_DPKG_DEB
help
This reduces dpkg-deb to the equivalent of "ar -p <deb> data.tar.gz | tar -zx".
However it saves space as none of the extra dpkg-deb, ar or tar options are
needed, they are linked to internally.
config GUNZIP
config CONFIG_GUNZIP
bool "gunzip"
default n
help
@@ -105,35 +105,35 @@ config GUNZIP
You can use the `-t' option to test the integrity of
an archive, without decompressing it.
config FEATURE_GUNZIP_UNCOMPRESS
config CONFIG_FEATURE_GUNZIP_UNCOMPRESS
bool "Uncompress support"
default n
depends on GUNZIP
depends on CONFIG_GUNZIP
help
Enable if you want gunzip to have the ability to decompress
archives created by the program compress (not much
used anymore).
config GZIP
config CONFIG_GZIP
bool "gzip"
default n
help
gzip is used to compress files.
It's probably the most widely used UNIX compression program.
config RPM2CPIO
config CONFIG_RPM2CPIO
bool "rpm2cpio"
default n
help
Converts an RPM file into a CPIO archive.
config RPM
config CONFIG_RPM
bool "rpm"
default n
help
Mini RPM applet - queries and extracts RPM packages.
Mini RPM applet - queries and extracts
config TAR
config CONFIG_TAR
bool "tar"
default n
help
@@ -141,86 +141,86 @@ config TAR
create compressed archives. It's probably the most widely used
UNIX archive program.
config FEATURE_TAR_CREATE
config CONFIG_FEATURE_TAR_CREATE
bool "Enable archive creation"
default y
depends on TAR
depends on CONFIG_TAR
help
If you enable this option you'll be able to create
tar archives using the `-c' option.
config FEATURE_TAR_BZIP2
config CONFIG_FEATURE_TAR_BZIP2
bool "Enable -j option to handle .tar.bz2 files"
default n
depends on TAR
depends on CONFIG_TAR
help
If you enable this option you'll be able to extract
archives compressed with bzip2.
config FEATURE_TAR_LZMA
config CONFIG_FEATURE_TAR_LZMA
bool "Enable -a option to handle .tar.lzma files"
default n
depends on TAR
depends on CONFIG_TAR
help
If you enable this option you'll be able to extract
archives compressed with lzma.
config FEATURE_TAR_FROM
config CONFIG_FEATURE_TAR_FROM
bool "Enable -X (exclude from) and -T (include from) options)"
default n
depends on TAR
depends on CONFIG_TAR
help
If you enable this option you'll be able to specify
a list of files to include or exclude from an archive.
config FEATURE_TAR_GZIP
config CONFIG_FEATURE_TAR_GZIP
bool "Enable -z option"
default y
depends on TAR
depends on CONFIG_TAR
help
If you enable this option tar will be able to call gzip,
when creating or extracting tar gziped archives.
config FEATURE_TAR_COMPRESS
config CONFIG_FEATURE_TAR_COMPRESS
bool "Enable -Z option"
default n
depends on TAR
depends on CONFIG_TAR
help
If you enable this option tar will be able to call uncompress,
when extracting .tar.Z archives.
config FEATURE_TAR_OLDGNU_COMPATIBILITY
config CONFIG_FEATURE_TAR_OLDGNU_COMPATIBILITY
bool "Enable support for old tar header format"
default N
depends on TAR
depends on CONFIG_TAR
help
This option is required to unpack archives created in
the old GNU format; help to kill this old format by
repacking your ancient archives with the new format.
config FEATURE_TAR_GNU_EXTENSIONS
config CONFIG_FEATURE_TAR_GNU_EXTENSIONS
bool "Enable support for some GNU tar extensions"
default y
depends on TAR
depends on CONFIG_TAR
help
With this option busybox supports GNU long filenames and
linknames.
config FEATURE_TAR_LONG_OPTIONS
config CONFIG_FEATURE_TAR_LONG_OPTIONS
bool "Enable long options"
default n
depends on TAR && GETOPT_LONG
depends on CONFIG_TAR && CONFIG_GETOPT_LONG
help
Enable use of long options, increases size by about 400 Bytes
config UNCOMPRESS
config CONFIG_UNCOMPRESS
bool "uncompress"
default n
help
uncompress is used to decompress archives created by compress.
Not much used anymore, replaced by gzip/gunzip.
config UNLZMA
config CONFIG_UNLZMA
bool "unlzma"
default n
help
@@ -235,15 +235,15 @@ config UNLZMA
Unless you have a specific application which requires unlzma, you
should probably say N here.
config FEATURE_LZMA_FAST
config CONFIG_FEATURE_LZMA_FAST
bool "Optimze unlzma for speed"
default n
depends on UNLZMA
depends on CONFIG_UNLZMA
help
This option reduces decompression time by about 33% at the cost of
a 2K bigger binary.
config UNZIP
config CONFIG_UNZIP
bool "unzip"
default n
help
@@ -254,31 +254,31 @@ config UNZIP
directory of your choice.
comment "Common options for cpio and tar"
depends on CPIO || TAR
depends on CONFIG_CPIO || CONFIG_TAR
config FEATURE_UNARCHIVE_TAPE
config CONFIG_FEATURE_UNARCHIVE_TAPE
bool "Enable tape drive support"
default n
depends on CPIO || TAR
depends on CONFIG_CPIO || CONFIG_TAR
help
I don't think this is needed anymore.
comment "Common options for dpkg and dpkg_deb"
depends on DPKG || DPKG_DEB
depends on CONFIG_DPKG || CONFIG_DPKG_DEB
config FEATURE_DEB_TAR_GZ
config CONFIG_FEATURE_DEB_TAR_GZ
bool "gzip debian packages (normal)"
default y if DPKG || DPKG_DEB
depends on DPKG || DPKG_DEB
default y if CONFIG_DPKG || CONFIG_DPKG_DEB
depends on CONFIG_DPKG || CONFIG_DPKG_DEB
help
This is the default compression method inside the debian ar file.
If you want compatibility with standard .deb's you should say yes here.
config FEATURE_DEB_TAR_BZ2
config CONFIG_FEATURE_DEB_TAR_BZ2
bool "bzip2 debian packages"
default n
depends on DPKG || DPKG_DEB
depends on CONFIG_DPKG || CONFIG_DPKG_DEB
help
This allows dpkg and dpkg-deb to extract deb's that are compressed internally
with bzip2 instead of gzip.
@@ -286,15 +286,15 @@ config FEATURE_DEB_TAR_BZ2
You only want this if you are creating your own custom debian packages that
use an internal control.tar.bz2 or data.tar.bz2.
config FEATURE_DEB_TAR_LZMA
config CONFIG_FEATURE_DEB_TAR_LZMA
bool "lzma debian packages"
default n
depends on DPKG || DPKG_DEB
depends on CONFIG_DPKG || CONFIG_DPKG_DEB
help
This allows dpkg and dpkg-deb to extract deb's that are compressed
internally with lzma instead of gzip.
internally with lzma instead of gzip.
You only want this if you are creating your own custom debian
packages that use an internal control.tar.lzma or data.tar.lzma.
packages that use an internal control.tar.lzma or data.tar.lzma.
endmenu
-22
View File
@@ -1,22 +0,0 @@
# Makefile for busybox
#
# Copyright (C) 1999-2005 by Erik Andersen <andersen@codepoet.org>
#
# Licensed under the GPL v2, see the file LICENSE in this tarball.
libs-y += libunarchive/
lib-y:=
lib-$(CONFIG_AR) += ar.o
lib-$(CONFIG_BUNZIP2) += bunzip2.o
lib-$(CONFIG_UNLZMA) += unlzma.o
lib-$(CONFIG_CPIO) += cpio.o
lib-$(CONFIG_DPKG) += dpkg.o
lib-$(CONFIG_DPKG_DEB) += dpkg_deb.o
lib-$(CONFIG_GUNZIP) += gunzip.o
lib-$(CONFIG_GZIP) += gzip.o
lib-$(CONFIG_RPM2CPIO) += rpm2cpio.o
lib-$(CONFIG_RPM) += rpm.o
lib-$(CONFIG_TAR) += tar.o
lib-$(CONFIG_UNCOMPRESS) += uncompress.o
lib-$(CONFIG_UNZIP) += unzip.o
+23
View File
@@ -0,0 +1,23 @@
# Makefile for busybox
#
# Copyright (C) 1999-2005 by Erik Andersen <andersen@codepoet.org>
#
# Licensed under the GPL v2, see the file LICENSE in this tarball.
ifndef top_srcdir
top_srcdir=..
endif
ifndef top_builddir
top_builddir=..
endif
ARCHIVAL_DIR:=./
srcdir=$(top_srcdir)/archival
include $(top_srcdir)/Rules.mak
include $(top_builddir)/.config
include $(srcdir)/Makefile.in
all: $(libraries-y)
-include $(top_builddir)/.depend
clean:
rm -f *.o *.a $(AR_TARGET)
+42
View File
@@ -0,0 +1,42 @@
# Makefile for busybox
#
# Copyright (C) 1999-2005 by Erik Andersen <andersen@codepoet.org>
#
# Licensed under the GPL v2, see the file LICENSE in this tarball.
ARCHIVAL_AR:=archival.a
ifndef $(ARCHIVAL_DIR)
ARCHIVAL_DIR:=$(top_builddir)/archival/
endif
srcdir=$(top_srcdir)/archival
ARCHIVAL-y:=
ARCHIVAL-$(CONFIG_APT_GET) +=
ARCHIVAL-$(CONFIG_AR) += ar.o
ARCHIVAL-$(CONFIG_BUNZIP2) += bunzip2.o
ARCHIVAL-$(CONFIG_UNLZMA) += unlzma.o
ARCHIVAL-$(CONFIG_CPIO) += cpio.o
ARCHIVAL-$(CONFIG_DPKG) += dpkg.o
ARCHIVAL-$(CONFIG_DPKG_DEB) += dpkg_deb.o
ARCHIVAL-$(CONFIG_GUNZIP) += gunzip.o
ARCHIVAL-$(CONFIG_GZIP) += gzip.o
ARCHIVAL-$(CONFIG_RPM2CPIO) += rpm2cpio.o
ARCHIVAL-$(CONFIG_RPM) += rpm.o
ARCHIVAL-$(CONFIG_TAR) += tar.o
ARCHIVAL-$(CONFIG_UNCOMPRESS) += uncompress.o
ARCHIVAL-$(CONFIG_UNZIP) += unzip.o
ifneq ($(strip $(ARCHIVAL-y)),)
libraries-y+=$(ARCHIVAL_DIR)$(ARCHIVAL_AR)
endif
ARCHIVAL_SRC-y:=$(patsubst %.o,$(srcdir)/%.c,$(ARCHIVAL-y))
ARCHIVAL_SRC-a:=$(wildcard $(srcdir)/*.c)
APPLET_SRC-y+=$(ARCHIVAL_SRC-y)
APPLET_SRC-a+=$(ARCHIVAL_SRC-a)
$(ARCHIVAL_DIR)$(ARCHIVAL_AR): $(patsubst %,$(ARCHIVAL_DIR)%, $(ARCHIVAL-y))
$(do_ar)
$(ARCHIVAL_DIR)%.o: $(srcdir)/%.c
$(compile.c)
+16 -9
View File
@@ -14,8 +14,16 @@
* http://www.unix-systems.org/single_unix_specification_v2/xcu/ar.html
*/
#include "busybox.h"
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <utime.h>
#include <unistd.h>
#include "unarchive.h"
#include "busybox.h"
static void header_verbose_list_ar(const file_header_t *file_header)
{
@@ -26,8 +34,7 @@ static void header_verbose_list_ar(const file_header_t *file_header)
mtime[16] = ' ';
memmove(&mtime[17], &mtime[20], 4);
mtime[21] = '\0';
printf("%s %d/%d%7d %s %s\n", &mode[1], file_header->uid, file_header->gid,
(int) file_header->size, &mtime[4], file_header->name);
printf("%s %d/%d%7d %s %s\n", &mode[1], file_header->uid, file_header->gid, (int) file_header->size, &mtime[4], file_header->name);
}
#define AR_CTX_PRINT 0x01
@@ -41,7 +48,7 @@ static void header_verbose_list_ar(const file_header_t *file_header)
int ar_main(int argc, char **argv)
{
archive_handle_t *archive_handle;
unsigned opt;
unsigned long opt;
static const char msg_unsupported_err[] =
"Archive %s not supported. Install binutils 'ar'.";
char magic[8];
@@ -49,8 +56,8 @@ int ar_main(int argc, char **argv)
archive_handle = init_handle();
/* Prepend '-' to the first argument if required */
opt_complementary = "--:p:t:x:-1:?:p--tx:t--px:x--pt";
opt = getopt32(argc, argv, "ptxovcr");
bb_opt_complementally = "--:p:t:x:-1:?:p--tx:t--px:x--pt";
opt = bb_getopt_ulflags(argc, argv, "ptxovcr");
if (opt & AR_CTX_PRINT) {
archive_handle->action_data = data_extract_to_stdout;
@@ -74,7 +81,7 @@ int ar_main(int argc, char **argv)
bb_error_msg_and_die(msg_unsupported_err, "insertion");
}
archive_handle->src_fd = xopen(argv[optind++], O_RDONLY);
archive_handle->src_fd = bb_xopen(argv[optind++], O_RDONLY);
while (optind < argc) {
archive_handle->filter = filter_accept_list;
@@ -83,11 +90,11 @@ int ar_main(int argc, char **argv)
xread(archive_handle->src_fd, magic, 7);
if (strncmp(magic, "!<arch>", 7) != 0) {
bb_error_msg_and_die("invalid ar magic");
bb_error_msg_and_die("Invalid ar magic");
}
archive_handle->offset += 7;
while (get_header_ar(archive_handle) == EXIT_SUCCESS) /* repeat */;
while (get_header_ar(archive_handle) == EXIT_SUCCESS);
return EXIT_SUCCESS;
}
+21 -20
View File
@@ -6,6 +6,12 @@
* Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
*/
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "busybox.h"
#include "unarchive.h"
@@ -14,51 +20,46 @@
int bunzip2_main(int argc, char **argv)
{
USE_DESKTOP(long long) int status;
char *filename;
unsigned opt;
int src_fd, dst_fd;
unsigned long opt;
int status, src_fd, dst_fd;
opt = getopt32(argc, argv, "cf");
opt = bb_getopt_ulflags(argc, argv, "cf");
/* Set input filename and number */
filename = argv[optind];
if (filename && NOT_LONE_DASH(filename)) {
if ((filename) && (filename[0] != '-') && (filename[1] != '\0')) {
/* Open input file */
src_fd = xopen(filename, O_RDONLY);
src_fd = bb_xopen(filename, O_RDONLY);
} else {
src_fd = STDIN_FILENO;
filename = 0;
}
/* if called as bzcat force the stdout flag */
if ((opt & BUNZIP2_OPT_STDOUT) || applet_name[2] == 'c')
if ((opt & BUNZIP2_OPT_STDOUT) || bb_applet_name[2] == 'c')
filename = 0;
/* Check that the input is sane. */
if (isatty(src_fd) && (opt & BUNZIP2_OPT_FORCE) == 0) {
bb_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 (filename) {
struct stat stat_buf;
/* extension = filename+strlen(filename)-4 is buggy:
* strlen may be less than 4 */
char *extension = strrchr(filename, '.');
if (!extension || strcmp(extension, ".bz2") != 0) {
bb_error_msg_and_die("invalid extension");
char *extension=filename+strlen(filename)-4;
if (strcmp(extension, ".bz2") != 0) {
bb_error_msg_and_die("Invalid extension");
}
xstat(filename, &stat_buf);
*extension = '\0';
dst_fd = xopen3(filename, O_WRONLY | O_CREAT | O_TRUNC,
stat_buf.st_mode);
*extension=0;
dst_fd = bb_xopen3(filename, O_WRONLY | O_CREAT, stat_buf.st_mode);
} else dst_fd = STDOUT_FILENO;
status = uncompressStream(src_fd, dst_fd);
if (filename) {
if (status >= 0) filename[strlen(filename)] = '.';
if(filename) {
if (!status) filename[strlen(filename)]='.';
if (unlink(filename) < 0) {
bb_error_msg_and_die("cannot remove %s", filename);
bb_error_msg_and_die("Couldn't remove %s", filename);
}
}
+5 -5
View File
@@ -30,15 +30,15 @@ int cpio_main(int argc, char **argv)
{
archive_handle_t *archive_handle;
char *cpio_filename = NULL;
unsigned opt;
unsigned long opt;
/* Initialise */
archive_handle = init_handle();
archive_handle->src_fd = STDIN_FILENO;
archive_handle->seek = seek_by_read;
archive_handle->seek = seek_by_char;
archive_handle->flags = ARCHIVE_EXTRACT_NEWER | ARCHIVE_PRESERVE_DATE;
opt = getopt32(argc, argv, "ituvF:dm", &cpio_filename);
opt = bb_getopt_ulflags(argc, argv, "ituvF:dm", &cpio_filename);
/* One of either extract or test options must be given */
if ((opt & (CPIO_OPT_TEST | CPIO_OPT_EXTRACT)) == 0) {
@@ -67,7 +67,7 @@ int cpio_main(int argc, char **argv)
}
}
if (cpio_filename) { /* CPIO_OPT_FILE */
archive_handle->src_fd = xopen(cpio_filename, O_RDONLY);
archive_handle->src_fd = bb_xopen(cpio_filename, O_RDONLY);
archive_handle->seek = seek_by_jump;
}
if (opt & CPIO_OPT_CREATE_LEADING_DIR) {
@@ -82,5 +82,5 @@ int cpio_main(int argc, char **argv)
while (get_header_cpio(archive_handle) == EXIT_SUCCESS);
return EXIT_SUCCESS;
return(EXIT_SUCCESS);
}
+399 -442
View File
File diff suppressed because it is too large. Load diff
+13 -8
View File
@@ -4,8 +4,13 @@
*
* Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
*/
#include "busybox.h"
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "unarchive.h"
#include "busybox.h"
#define DPKG_DEB_OPT_CONTENTS 1
#define DPKG_DEB_OPT_CONTROL 2
@@ -18,7 +23,7 @@ int dpkg_deb_main(int argc, char **argv)
archive_handle_t *ar_archive;
archive_handle_t *tar_archive;
llist_t *control_tar_llist = NULL;
unsigned opt;
unsigned long opt;
char *extract_dir = NULL;
short argcount = 1;
@@ -40,8 +45,8 @@ int dpkg_deb_main(int argc, char **argv)
llist_add_to(&control_tar_llist, "control.tar.bz2");
#endif
opt_complementary = "?c--efXx:e--cfXx:f--ceXx:X--cefx:x--cefX";
opt = getopt32(argc, argv, "cefXx");
bb_opt_complementally = "?c--efXx:e--cfXx:f--ceXx:X--cefx:x--cefX";
opt = bb_getopt_ulflags(argc, argv, "cefXx");
if (opt & DPKG_DEB_OPT_CONTENTS) {
tar_archive->action_header = header_verbose_list;
@@ -76,7 +81,7 @@ int dpkg_deb_main(int argc, char **argv)
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 */
/* 2nd argument is a dir name */
@@ -85,12 +90,12 @@ int dpkg_deb_main(int argc, char **argv)
}
if (extract_dir) {
mkdir(extract_dir, 0777); /* bb_make_directory(extract_dir, 0777, 0) */
xchdir(extract_dir);
bb_xchdir(extract_dir);
}
unpack_ar_archive(ar_archive);
/* Cleanup */
close(ar_archive->src_fd);
close (ar_archive->src_fd);
return EXIT_SUCCESS;
return(EXIT_SUCCESS);
}
+41 -44
View File
@@ -27,6 +27,13 @@
* See the file algorithm.doc for the compression algorithms and file formats.
*/
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include "busybox.h"
#include "unarchive.h"
@@ -34,56 +41,53 @@
#define GUNZIP_OPT_FORCE 2
#define GUNZIP_OPT_TEST 4
#define GUNZIP_OPT_DECOMPRESS 8
#define GUNZIP_OPT_VERBOSE 0x10
int gunzip_main(int argc, char **argv)
{
USE_DESKTOP(long long) int status;
int exitcode = 0;
unsigned opt;
char status = EXIT_SUCCESS;
unsigned long opt;
opt = getopt32(argc, argv, "cftdv");
opt = bb_getopt_ulflags(argc, argv, "cftd");
/* if called as zcat */
if (strcmp(applet_name, "zcat") == 0) {
if (strcmp(bb_applet_name, "zcat") == 0) {
opt |= GUNZIP_OPT_STDOUT;
}
do {
struct stat stat_buf;
char *old_path = argv[optind];
char *delete_path = NULL;
const char *old_path = argv[optind];
const char *delete_path = NULL;
char *new_path = NULL;
int src_fd;
int dst_fd;
optind++;
if (old_path == NULL || LONE_DASH(old_path)) {
if (old_path == NULL || strcmp(old_path, "-") == 0) {
src_fd = STDIN_FILENO;
opt |= GUNZIP_OPT_STDOUT;
USE_DESKTOP(opt &= ~GUNZIP_OPT_VERBOSE;)
optind = argc; /* we don't handle "gunzip - a.gz b.gz" */
} else {
src_fd = xopen(old_path, O_RDONLY);
src_fd = bb_xopen(old_path, O_RDONLY);
/* Get the time stamp on the input file. */
fstat(src_fd, &stat_buf);
xstat(old_path, &stat_buf);
}
/* Check that the input is sane. */
if (isatty(src_fd) && !(opt & GUNZIP_OPT_FORCE)) {
if (isatty(src_fd) && ((opt & GUNZIP_OPT_FORCE) == 0)) {
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 */
if (opt & GUNZIP_OPT_TEST) {
dst_fd = xopen(bb_dev_null, O_WRONLY); /* why does test use filenum 2 ? */
dst_fd = bb_xopen(bb_dev_null, O_WRONLY); /* why does test use filenum 2 ? */
} else if (opt & GUNZIP_OPT_STDOUT) {
dst_fd = STDOUT_FILENO;
} else {
char *extension;
new_path = xstrdup(old_path);
new_path = bb_xstrdup(old_path);
extension = strrchr(new_path, '.');
#ifdef CONFIG_FEATURE_GUNZIP_UNCOMPRESS
@@ -97,46 +101,40 @@ int gunzip_main(int argc, char **argv)
extension[2] = 'a';
extension[3] = 'r';
} else {
// FIXME: should we die or just skip to next?
bb_error_msg_and_die("invalid extension");
bb_error_msg_and_die("Invalid extension");
}
/* Open output file (with correct permissions) */
dst_fd = xopen3(new_path, O_WRONLY | O_CREAT | O_TRUNC,
stat_buf.st_mode);
dst_fd = bb_xopen3(new_path, O_WRONLY | O_CREAT, stat_buf.st_mode);
/* If unzip succeeds remove the old file */
delete_path = old_path;
}
status = -1;
/* do the decompression, and cleanup */
if (xread_char(src_fd) == 0x1f) {
unsigned char magic2;
magic2 = xread_char(src_fd);
if (ENABLE_FEATURE_GUNZIP_UNCOMPRESS && magic2 == 0x9d) {
#ifdef CONFIG_FEATURE_GUNZIP_UNCOMPRESS
if (magic2 == 0x9d) {
status = uncompress(src_fd, dst_fd);
} else if (magic2 == 0x8b) {
check_header_gzip(src_fd); // FIXME: xfunc? _or_die?
status = inflate_gunzip(src_fd, dst_fd);
} else {
bb_error_msg("invalid magic");
exitcode = 1;
}
if (status < 0) {
bb_error_msg("error inflating");
exitcode = 1;
}
else if (ENABLE_DESKTOP && (opt & GUNZIP_OPT_VERBOSE)) {
fprintf(stderr, "%s: %u%% - replaced with %s\n",
old_path, (unsigned)(stat_buf.st_size*100 / (status+1)), new_path);
}
} else
#endif
if (magic2 == 0x8b) {
check_header_gzip(src_fd);
status = inflate_gunzip(src_fd, dst_fd);
if (status != 0) {
bb_error_msg_and_die("Error inflating");
}
} else {
bb_error_msg_and_die("Invalid magic");
}
} else {
bb_error_msg("invalid magic");
exitcode = 1;
bb_error_msg_and_die("Invalid magic");
}
if (status < 0 && new_path) {
if ((status != EXIT_SUCCESS) && (new_path)) {
/* Unzip failed, remove new path instead of old path */
delete_path = new_path;
}
@@ -150,13 +148,12 @@ int gunzip_main(int argc, char **argv)
/* delete_path will be NULL if in test mode or from stdin */
if (delete_path && (unlink(delete_path) == -1)) {
bb_error_msg("cannot remove %s", delete_path);
exitcode = 1;
bb_error_msg_and_die("Couldn't remove %s", delete_path);
}
free(new_path);
} while (optind < argc);
return exitcode;
return status;
}
+1350 -1092
View File
File diff suppressed because it is too large. Load diff
-59
View File
@@ -1,59 +0,0 @@
# Makefile for busybox
#
# Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
#
# Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
lib-y:= \
\
data_skip.o \
data_extract_all.o \
data_extract_to_stdout.o \
data_extract_to_buffer.o \
\
filter_accept_all.o \
filter_accept_list.o \
filter_accept_reject_list.o \
\
header_skip.o \
header_list.o \
header_verbose_list.o \
\
archive_xread_all_eof.o \
\
seek_by_read.o \
seek_by_jump.o \
\
data_align.o \
find_list_entry.o \
open_transformer.o \
init_handle.o
GUNZIP_FILES:= check_header_gzip.o decompress_unzip.o
DPKG_FILES:= \
get_header_ar.o \
unpack_ar_archive.o \
get_header_tar.o \
filter_accept_list_reassign.o
lib-$(CONFIG_AR) += get_header_ar.o unpack_ar_archive.o
lib-$(CONFIG_BUNZIP2) += decompress_bunzip2.o
lib-$(CONFIG_UNLZMA) += decompress_unlzma.o
lib-$(CONFIG_CPIO) += get_header_cpio.o
lib-$(CONFIG_DPKG) += $(DPKG_FILES)
lib-$(CONFIG_DPKG_DEB) += $(DPKG_FILES)
lib-$(CONFIG_FEATURE_DEB_TAR_GZ) += $(GUNZIP_FILES) get_header_tar_gz.o
lib-$(CONFIG_FEATURE_DEB_TAR_BZ2) += decompress_bunzip2.o get_header_tar_bz2.o
lib-$(CONFIG_FEATURE_DEB_TAR_LZMA) += decompress_unlzma.o get_header_tar_lzma.o
lib-$(CONFIG_GUNZIP) += $(GUNZIP_FILES)
lib-$(CONFIG_FEATURE_GUNZIP_UNCOMPRESS) += decompress_uncompress.o
lib-$(CONFIG_RPM2CPIO) += $(GUNZIP_FILES) get_header_cpio.o
lib-$(CONFIG_RPM) += $(GUNZIP_FILES) get_header_cpio.o
lib-$(CONFIG_TAR) += get_header_tar.o
lib-$(CONFIG_FEATURE_TAR_BZIP2) += decompress_bunzip2.o get_header_tar_bz2.o
lib-$(CONFIG_FEATURE_TAR_LZMA) += decompress_unlzma.o get_header_tar_lzma.o
lib-$(CONFIG_FEATURE_TAR_GZIP) += $(GUNZIP_FILES) get_header_tar_gz.o
lib-$(CONFIG_FEATURE_TAR_COMPRESS) += decompress_uncompress.o
lib-$(CONFIG_UNCOMPRESS) += decompress_uncompress.o
lib-$(CONFIG_UNZIP) += $(GUNZIP_FILES)
lib-$(CONFIG_FEATURE_COMPRESS_USAGE) += decompress_bunzip2.o
+36
View File
@@ -0,0 +1,36 @@
# Makefile for busybox
#
# Copyright (C) 1999-2004 by Erik Andersen <andersen@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
#
ifndef top_srcdir
top_srcdir=../..
endif
ifndef top_builddir
top_builddir=../..
endif
srcdir=$(top_srcdir)/archival/libunarchive
LIBUNARCHIVE_DIR:=./
include $(top_srcdir)/Rules.mak
include $(top_builddir)/.config
include $(srcdir)/Makefile.in
all: $(libraries-y)
-include $(top_builddir)/.depend
clean:
rm -f *.o *.a $(AR_TARGET)
+83
View File
@@ -0,0 +1,83 @@
# Makefile for busybox
#
# Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
#
# Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
LIBUNARCHIVE_AR:=libunarchive.a
ifndef $(LIBUNARCHIVE_DIR)
LIBUNARCHIVE_DIR:=$(top_builddir)/archival/libunarchive
endif
srcdir=$(top_srcdir)/archival/libunarchive
LIBUNARCHIVE-obj:=$(LIBUNARCHIVE_DIR)/$(LIBUNARCHIVE_AR)
libraries-y+=$(LIBUNARCHIVE-obj)
LIBUNARCHIVE-y:= \
\
data_skip.o \
data_extract_all.o \
data_extract_to_stdout.o \
data_extract_to_buffer.o \
\
filter_accept_all.o \
filter_accept_list.o \
filter_accept_reject_list.o \
\
header_skip.o \
header_list.o \
header_verbose_list.o \
\
archive_xread_all_eof.o \
\
seek_by_char.o \
seek_by_jump.o \
\
data_align.o \
find_list_entry.o \
open_transformer.o \
init_handle.o
GUNZIP_FILES:= check_header_gzip.o decompress_unzip.o
DPKG_FILES:= \
get_header_ar.o \
unpack_ar_archive.o \
get_header_tar.o \
filter_accept_list_reassign.o
LIBUNARCHIVE-$(CONFIG_AR) += get_header_ar.o unpack_ar_archive.o
LIBUNARCHIVE-$(CONFIG_BUNZIP2) += decompress_bunzip2.o
LIBUNARCHIVE-$(CONFIG_UNLZMA) += decompress_unlzma.o
LIBUNARCHIVE-$(CONFIG_CPIO) += get_header_cpio.o
LIBUNARCHIVE-$(CONFIG_DPKG) += $(DPKG_FILES)
LIBUNARCHIVE-$(CONFIG_DPKG_DEB) += $(DPKG_FILES)
LIBUNARCHIVE-$(CONFIG_FEATURE_DEB_TAR_GZ) += $(GUNZIP_FILES) get_header_tar_gz.o
LIBUNARCHIVE-$(CONFIG_FEATURE_DEB_TAR_BZ2) += decompress_bunzip2.o get_header_tar_bz2.o
LIBUNARCHIVE-$(CONFIG_FEATURE_DEB_TAR_LZMA) += decompress_unlzma.o get_header_tar_lzma.o
LIBUNARCHIVE-$(CONFIG_GUNZIP) += $(GUNZIP_FILES)
LIBUNARCHIVE-$(CONFIG_FEATURE_GUNZIP_UNCOMPRESS) += decompress_uncompress.o
LIBUNARCHIVE-$(CONFIG_RPM2CPIO) += $(GUNZIP_FILES) get_header_cpio.o
LIBUNARCHIVE-$(CONFIG_RPM) += $(GUNZIP_FILES) get_header_cpio.o
LIBUNARCHIVE-$(CONFIG_TAR) += get_header_tar.o
LIBUNARCHIVE-$(CONFIG_FEATURE_TAR_BZIP2) += decompress_bunzip2.o get_header_tar_bz2.o
LIBUNARCHIVE-$(CONFIG_FEATURE_TAR_LZMA) += decompress_unlzma.o get_header_tar_lzma.o
LIBUNARCHIVE-$(CONFIG_FEATURE_TAR_GZIP) += $(GUNZIP_FILES) get_header_tar_gz.o
LIBUNARCHIVE-$(CONFIG_FEATURE_TAR_COMPRESS) += decompress_uncompress.o
LIBUNARCHIVE-$(CONFIG_UNCOMPRESS) += decompress_uncompress.o
LIBUNARCHIVE-$(CONFIG_UNZIP) += $(GUNZIP_FILES)
LIBUNARCHIVE-$(CONFIG_FEATURE_COMPRESS_USAGE) += decompress_bunzip2.o
LIBUNARCHIVE-y:=$(sort $(LIBUNARCHIVE-y))
LIBUNARCHIVE_SRC-y:=$(patsubst %,$(srcdir)/%,$(subst .o,.c,$(LIBUNARCHIVE-y)))
LIBUNARCHIVE_SRC-a:=$(wildcard $(srcdir)/*.c)
LIBRARY_SRC-y+=$(LIBUNARCHIVE_SRC-y)
LIBRARY_SRC-a+=$(LIBUNARCHIVE_SRC-a)
$(LIBUNARCHIVE_DIR)/$(LIBUNARCHIVE_AR): $(patsubst %,$(LIBUNARCHIVE_DIR)/%,$(LIBUNARCHIVE-y))
$(do_ar)
$(LIBUNARCHIVE_DIR)/%.o: $(srcdir)/%.c
$(compile.c)
@@ -3,18 +3,19 @@
* Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "unarchive.h"
#include "libbb.h"
ssize_t archive_xread_all_eof(archive_handle_t *archive_handle,
unsigned char *buf, size_t count)
ssize_t archive_xread_all_eof(archive_handle_t *archive_handle, unsigned char *buf, size_t count)
{
ssize_t size;
size = full_read(archive_handle->src_fd, buf, count);
if (size != 0 && size != count) {
bb_error_msg_and_die("short read: %u of %u",
(unsigned)size, (unsigned)count);
if ((size != 0) && (size != count)) {
bb_perror_msg_and_die("Short read, read %ld of %ld", (long)size, (long)count);
}
return size;
return(size);
}
+10 -10
View File
@@ -17,18 +17,18 @@ void check_header_gzip(int src_fd)
unsigned int mtime;
unsigned char xtra_flags;
unsigned char os_flags;
} formatted;
} formated;
} header;
xread(src_fd, header.raw, 8);
/* Check the compression method */
if (header.formatted.method != 8) {
bb_error_msg_and_die("unknown compression method %d",
header.formatted.method);
if (header.formated.method != 8) {
bb_error_msg_and_die("Unknown compression method %d",
header.formated.method);
}
if (header.formatted.flags & 0x04) {
if (header.formated.flags & 0x04) {
/* bit 2 set: extra field present */
unsigned char extra_short;
@@ -41,19 +41,19 @@ void check_header_gzip(int src_fd)
}
/* Discard original name if any */
if (header.formatted.flags & 0x08) {
if (header.formated.flags & 0x08) {
/* bit 3 set: original file name present */
while (xread_char(src_fd) != 0);
while(xread_char(src_fd) != 0);
}
/* Discard file comment if any */
if (header.formatted.flags & 0x10) {
if (header.formated.flags & 0x10) {
/* bit 4 set: file comment present */
while (xread_char(src_fd) != 0);
while(xread_char(src_fd) != 0);
}
/* Read the header checksum */
if (header.formatted.flags & 0x02) {
if (header.formated.flags & 0x02) {
xread_char(src_fd);
xread_char(src_fd);
}
+56 -58
View File
@@ -3,6 +3,16 @@
* Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
*/
#include <sys/types.h>
#include <errno.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#include <utime.h>
#include <unistd.h>
#include <stdlib.h>
#include "libbb.h"
#include "unarchive.h"
@@ -13,19 +23,16 @@ void data_extract_all(archive_handle_t *archive_handle)
int res;
if (archive_handle->flags & ARCHIVE_CREATE_LEADING_DIRS) {
char *name = xstrdup(file_header->name);
bb_make_directory(dirname(name), -1, FILEUTILS_RECUR);
char *name = bb_xstrdup(file_header->name);
bb_make_directory (dirname(name), -1, FILEUTILS_RECUR);
free(name);
}
/* Check if the file already exists */
if (archive_handle->flags & ARCHIVE_EXTRACT_UNCONDITIONAL) {
/* Remove the existing entry if it exists */
if (((file_header->mode & S_IFMT) != S_IFDIR)
&& (unlink(file_header->name) == -1)
&& (errno != ENOENT)
) {
bb_perror_msg_and_die("cannot remove old file");
if (((file_header->mode & S_IFMT) != S_IFDIR) && (unlink(file_header->name) == -1) && (errno != ENOENT)) {
bb_perror_msg_and_die("Couldnt remove old file");
}
}
else if (archive_handle->flags & ARCHIVE_EXTRACT_NEWER) {
@@ -33,83 +40,74 @@ void data_extract_all(archive_handle_t *archive_handle)
struct stat statbuf;
if (lstat(file_header->name, &statbuf) == -1) {
if (errno != ENOENT) {
bb_perror_msg_and_die("cannot stat old file");
bb_perror_msg_and_die("Couldnt stat old file");
}
}
else if (statbuf.st_mtime <= file_header->mtime) {
if (!(archive_handle->flags & ARCHIVE_EXTRACT_QUIET)) {
bb_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);
}
data_skip(archive_handle);
return;
}
else if ((unlink(file_header->name) == -1) && (errno != EISDIR)) {
bb_perror_msg_and_die("cannot remove old file %s",
file_header->name);
bb_perror_msg_and_die("Couldnt remove old file %s", file_header->name);
}
}
/* Handle hard links separately
* We identified hard links as regular files of size 0 with a symlink */
if (S_ISREG(file_header->mode) && (file_header->link_name)
&& (file_header->size == 0)
) {
if (S_ISREG(file_header->mode) && (file_header->link_name) && (file_header->size == 0)) {
/* hard link */
res = link(file_header->link_name, file_header->name);
if ((res == -1) && !(archive_handle->flags & ARCHIVE_EXTRACT_QUIET)) {
bb_perror_msg("cannot create hard link");
bb_perror_msg("Couldnt create hard link");
}
} else {
/* Create the filesystem entry */
switch (file_header->mode & S_IFMT) {
case S_IFREG: {
/* Regular file */
dst_fd = xopen3(file_header->name, O_WRONLY | O_CREAT | O_EXCL,
file_header->mode);
bb_copyfd_exact_size(archive_handle->src_fd, dst_fd, file_header->size);
close(dst_fd);
break;
}
case S_IFDIR:
res = mkdir(file_header->name, file_header->mode);
if ((errno != EISDIR) && (res == -1)
&& !(archive_handle->flags & ARCHIVE_EXTRACT_QUIET)
) {
bb_perror_msg("extract_archive: %s", file_header->name);
}
break;
case S_IFLNK:
/* Symlink */
res = symlink(file_header->link_name, file_header->name);
if ((res == -1)
&& !(archive_handle->flags & ARCHIVE_EXTRACT_QUIET)
) {
bb_perror_msg("cannot create symlink "
"from %s to '%s'",
file_header->name,
file_header->link_name);
}
break;
case S_IFSOCK:
case S_IFBLK:
case S_IFCHR:
case S_IFIFO:
res = mknod(file_header->name, file_header->mode, file_header->device);
if ((res == -1)
&& !(archive_handle->flags & ARCHIVE_EXTRACT_QUIET)
) {
bb_perror_msg("cannot create node %s", file_header->name);
}
break;
default:
bb_error_msg_and_die("unrecognized file type");
switch(file_header->mode & S_IFMT) {
case S_IFREG: {
/* Regular file */
dst_fd = bb_xopen(file_header->name, O_WRONLY | O_CREAT | O_EXCL);
bb_copyfd_size(archive_handle->src_fd, dst_fd, file_header->size);
close(dst_fd);
break;
}
case S_IFDIR:
res = mkdir(file_header->name, file_header->mode);
if ((errno != EISDIR) && (res == -1) && !(archive_handle->flags & ARCHIVE_EXTRACT_QUIET)) {
bb_perror_msg("extract_archive: %s", file_header->name);
}
break;
case S_IFLNK:
/* Symlink */
res = symlink(file_header->link_name, file_header->name);
if ((res == -1) && !(archive_handle->flags & ARCHIVE_EXTRACT_QUIET)) {
bb_perror_msg("Cannot create symlink from %s to '%s'", file_header->name, file_header->link_name);
}
break;
case S_IFSOCK:
case S_IFBLK:
case S_IFCHR:
case S_IFIFO:
res = mknod(file_header->name, file_header->mode, file_header->device);
if ((res == -1) && !(archive_handle->flags & ARCHIVE_EXTRACT_QUIET)) {
bb_perror_msg("Cannot create node %s", file_header->name);
}
break;
default:
bb_error_msg_and_die("Unrecognised file type");
}
}
if (!(archive_handle->flags & ARCHIVE_NOPRESERVE_OWN)) {
lchown(file_header->name, file_header->uid, file_header->gid);
}
if (!(archive_handle->flags & ARCHIVE_NOPRESERVE_PERM) &&
(file_header->mode & S_IFMT) != S_IFLNK)
{
chmod(file_header->name, file_header->mode);
}
if (archive_handle->flags & ARCHIVE_PRESERVE_DATE) {
struct utimbuf t;
@@ -10,8 +10,9 @@
void data_extract_to_buffer(archive_handle_t *archive_handle)
{
unsigned int size = archive_handle->file_header->size;
const unsigned int size = archive_handle->file_header->size;
archive_handle->buffer = xzalloc(size + 1);
xread(archive_handle->src_fd, archive_handle->buffer, size);
}
@@ -4,10 +4,9 @@
*/
#include "unarchive.h"
#include <unistd.h>
void data_extract_to_stdout(archive_handle_t *archive_handle)
{
bb_copyfd_exact_size(archive_handle->src_fd,
STDOUT_FILENO,
archive_handle->file_header->size);
bb_copyfd_size(archive_handle->src_fd, STDOUT_FILENO, archive_handle->file_header->size);
}
+52 -48
View File
@@ -28,29 +28,37 @@
Manuel
*/
#include <setjmp.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <limits.h>
#include "libbb.h"
#include "unarchive.h"
/* Constants for Huffman coding */
#define MAX_GROUPS 6
#define GROUP_SIZE 50 /* 64 would have been more efficient */
#define MAX_HUFCODE_BITS 20 /* Longest Huffman code allowed */
#define MAX_SYMBOLS 258 /* 256 literals + RUNA + RUNB */
#define SYMBOL_RUNA 0
#define SYMBOL_RUNB 1
#define MAX_GROUPS 6
#define GROUP_SIZE 50 /* 64 would have been more efficient */
#define MAX_HUFCODE_BITS 20 /* Longest Huffman code allowed */
#define MAX_SYMBOLS 258 /* 256 literals + RUNA + RUNB */
#define SYMBOL_RUNA 0
#define SYMBOL_RUNB 1
/* Status return values */
#define RETVAL_OK 0
#define RETVAL_LAST_BLOCK (-1)
#define RETVAL_NOT_BZIP_DATA (-2)
#define RETVAL_UNEXPECTED_INPUT_EOF (-3)
#define RETVAL_UNEXPECTED_OUTPUT_EOF (-4)
#define RETVAL_DATA_ERROR (-5)
#define RETVAL_OUT_OF_MEMORY (-6)
#define RETVAL_OBSOLETE_INPUT (-7)
#define RETVAL_OK 0
#define RETVAL_LAST_BLOCK (-1)
#define RETVAL_NOT_BZIP_DATA (-2)
#define RETVAL_UNEXPECTED_INPUT_EOF (-3)
#define RETVAL_UNEXPECTED_OUTPUT_EOF (-4)
#define RETVAL_DATA_ERROR (-5)
#define RETVAL_OUT_OF_MEMORY (-6)
#define RETVAL_OBSOLETE_INPUT (-7)
/* Other housekeeping constants */
#define IOBUF_SIZE 4096
#define IOBUF_SIZE 4096
/* This is what we know about each Huffman coding group */
struct group_data {
@@ -151,7 +159,7 @@ static int get_next_block(bunzip_data *bd)
/* Reset longjmp I/O error handling */
i=setjmp(bd->jmpbuf);
if (i) return i;
if(i) return i;
/* Read in header signature and CRC, then validate signature.
(last block signature means CRC is for whole file, return now) */
@@ -166,8 +174,8 @@ static int get_next_block(bunzip_data *bd)
some code for this in busybox 1.0.0-pre3, but nobody ever noticed that
it didn't actually work. */
if (get_bits(bd,1)) return RETVAL_OBSOLETE_INPUT;
if ((origPtr=get_bits(bd,24)) > dbufSize) return RETVAL_DATA_ERROR;
if(get_bits(bd,1)) return RETVAL_OBSOLETE_INPUT;
if((origPtr=get_bits(bd,24)) > dbufSize) return RETVAL_DATA_ERROR;
/* mapping table: if some byte values are never used (encoding things
like ascii text), the compression code removes the gaps to have fewer
@@ -180,7 +188,7 @@ static int get_next_block(bunzip_data *bd)
for (i=0;i<16;i++) {
if(t&(1<<(15-i))) {
k=get_bits(bd,16);
for (j=0;j<16;j++)
for(j=0;j<16;j++)
if(k&(1<<(15-j))) symToByte[symTotal++]=(16*i)+j;
}
}
@@ -196,17 +204,17 @@ static int get_next_block(bunzip_data *bd)
start of the list.) */
if(!(nSelectors=get_bits(bd, 15))) return RETVAL_DATA_ERROR;
for (i=0; i<groupCount; i++) mtfSymbol[i] = i;
for (i=0; i<nSelectors; i++) {
for(i=0; i<groupCount; i++) mtfSymbol[i] = i;
for(i=0; i<nSelectors; i++) {
/* Get next value */
for (j=0;get_bits(bd,1);j++) if (j>=groupCount) return RETVAL_DATA_ERROR;
for(j=0;get_bits(bd,1);j++) if (j>=groupCount) return RETVAL_DATA_ERROR;
/* Decode MTF to get the next selector */
uc = mtfSymbol[j];
for (;j;j--) mtfSymbol[j] = mtfSymbol[j-1];
for(;j;j--) mtfSymbol[j] = mtfSymbol[j-1];
mtfSymbol[0]=selectors[i]=uc;
}
@@ -227,7 +235,7 @@ static int get_next_block(bunzip_data *bd)
t=get_bits(bd, 5)-1;
for (i = 0; i < symCount; i++) {
for (;;) {
for(;;) {
if (((unsigned)t) > (MAX_HUFCODE_BITS-1))
return RETVAL_DATA_ERROR;
@@ -254,7 +262,7 @@ static int get_next_block(bunzip_data *bd)
/* Find largest and smallest lengths in this group */
minLen=maxLen=length[0];
for (i = 1; i < symCount; i++) {
for(i = 1; i < symCount; i++) {
if(length[i] > maxLen) maxLen = length[i];
else if(length[i] < minLen) minLen = length[i];
}
@@ -284,9 +292,9 @@ static int get_next_block(bunzip_data *bd)
/* Calculate permute[]. Concurently, initialize temp[] and limit[]. */
pp=0;
for (i=minLen;i<=maxLen;i++) {
for(i=minLen;i<=maxLen;i++) {
temp[i]=limit[i]=0;
for (t=0;t<symCount;t++)
for(t=0;t<symCount;t++)
if(length[t]==i) hufGroup->permute[pp++] = t;
}
@@ -325,7 +333,7 @@ static int get_next_block(bunzip_data *bd)
/* Initialize symbol occurrence counters and symbol Move To Front table */
for (i=0;i<256;i++) {
for(i=0;i<256;i++) {
byteCount[i] = 0;
mtfSymbol[i]=(unsigned char)i;
}
@@ -333,7 +341,7 @@ static int get_next_block(bunzip_data *bd)
/* Loop through compressed symbols. */
runPos=dbufCount=selector=0;
for (;;) {
for(;;) {
/* fetch next Huffman coding group from list. */
@@ -372,7 +380,7 @@ got_huff_bits:
/* Figure how how many bits are in next symbol and unget extras */
i=hufGroup->minLen;
while (j>limit[i]) ++i;
while(j>limit[i]) ++i;
bd->inbufBitCount += (hufGroup->maxLen - i);
/* Huffman decode value to get nextSym (with bounds checking) */
@@ -421,7 +429,7 @@ got_huff_bits:
uc = symToByte[mtfSymbol[0]];
byteCount[uc] += t;
while (t--) dbuf[dbufCount++]=uc;
while(t--) dbuf[dbufCount++]=uc;
}
/* Is this the terminating symbol? */
@@ -473,7 +481,7 @@ end_of_huffman_loop:
/* Turn byteCount into cumulative occurrence counts of 0 to n-1. */
j=0;
for (i=0;i<256;i++) {
for(i=0;i<256;i++) {
k=j+byteCount[i];
byteCount[i] = j;
j=k;
@@ -535,7 +543,7 @@ static int read_bunzip(bunzip_data *bd, char *outbuf, int len)
/* Loop outputting bytes */
for (;;) {
for(;;) {
/* If the output buffer is full, snapshot state and return */
@@ -647,7 +655,7 @@ static int start_bunzip(bunzip_data **bdp, int in_fd, unsigned char *inbuf,
/* Init the CRC32 table (big endian) */
bd->crc32Table = crc32_filltable(1);
bd->crc32Table = bb_crc32_filltable(1);
/* Setup for I/O error handling via longjmp */
@@ -671,24 +679,20 @@ static int start_bunzip(bunzip_data **bdp, int in_fd, unsigned char *inbuf,
/* Example usage: decompress src_fd to dst_fd. (Stops at end of bzip data,
not end of file.) */
USE_DESKTOP(long long) int
uncompressStream(int src_fd, int dst_fd)
int uncompressStream(int src_fd, int dst_fd)
{
USE_DESKTOP(long long total_written = 0;)
char *outbuf;
bunzip_data *bd;
int i;
outbuf=xmalloc(IOBUF_SIZE);
i=start_bunzip(&bd,src_fd,0,0);
if(!i) {
for (;;) {
if(!(i=start_bunzip(&bd,src_fd,0,0))) {
for(;;) {
if((i=read_bunzip(bd,outbuf,IOBUF_SIZE)) <= 0) break;
if(i!=write(dst_fd,outbuf,i)) {
i=RETVAL_UNEXPECTED_OUTPUT_EOF;
break;
}
USE_DESKTOP(total_written += i;)
}
}
@@ -696,27 +700,27 @@ uncompressStream(int src_fd, int dst_fd)
if(i==RETVAL_LAST_BLOCK) {
if (bd->headerCRC!=bd->totalCRC) {
bb_error_msg("data integrity error when decompressing");
bb_error_msg("Data integrity error when decompressing.");
} else {
i=RETVAL_OK;
}
} else if (i==RETVAL_UNEXPECTED_OUTPUT_EOF) {
bb_error_msg("compressed file ends unexpectedly");
bb_error_msg("Compressed file ends unexpectedly");
} else {
bb_error_msg("decompression failed");
bb_error_msg("Decompression failed");
}
free(bd->dbuf);
free(bd);
free(outbuf);
return i ? i : USE_DESKTOP(total_written) + 0;
return i;
}
#ifdef TESTING
static char * const bunzip_errors[]={NULL,"Bad file checksum","Not bzip data",
"Unexpected input EOF","Unexpected output EOF","Data error",
"Out of memory","Obsolete (pre 0.9.5) bzip format not supported."};
"Out of memory","Obsolete (pre 0.9.5) bzip format not supported."};
/* Dumb little test thing, decompress stdin to stdout */
int main(int argc, char *argv[])
@@ -724,8 +728,8 @@ int main(int argc, char *argv[])
int i=uncompressStream(0,1);
char c;
if(i<0) fprintf(stderr,"%s\n", bunzip_errors[-i]);
else if(read(0,&c,1)) fprintf(stderr,"Trailing garbage ignored\n");
if(i) fprintf(stderr,"%s\n", bunzip_errors[-i]);
else if(read(0,&c,1)) fprintf(stderr,"Trailing garbage ignored\n");
return -i;
}
#endif
+40 -58
View File
@@ -64,12 +64,28 @@
#undef MAXSEG_64K
#define MAXCODE(n) (1L << (n))
/* Block compress mode -C compatible with 2.0 */
static int block_mode = BLOCK_MODE;
/* user settable max # bits/code */
static int maxbits = BITS;
/* Input buffer */
static unsigned char inbuf[IBUFSIZ + 64];
/* Output buffer */
static unsigned char outbuf[OBUFSIZ + 2048];
static unsigned char htab[HSIZE];
static unsigned short codetab[HSIZE];
#define htabof(i) htab[i]
#define codetabof(i) codetab[i]
#define tab_prefixof(i) codetabof(i)
#define tab_suffixof(i) ((unsigned char *)(htab))[i]
#define de_stack ((unsigned char *)&(htab[HSIZE-1]))
#define clear_htab() memset(htab, -1, HSIZE)
#define clear_htab() memset(htab, -1, sizeof(htab))
#define clear_tab_prefixof() memset(codetab, 0, 256);
@@ -80,10 +96,8 @@
* with those of the compress() routine. See the definitions above.
*/
USE_DESKTOP(long long) int
uncompress(int fd_in, int fd_out)
int uncompress(int fd_in, int fd_out)
{
USE_DESKTOP(long long total_written = 0;)
unsigned char *stackp;
long int code;
int finchar;
@@ -99,42 +113,23 @@ uncompress(int fd_in, int fd_out)
long int maxmaxcode;
int n_bits;
int rsize = 0;
RESERVE_CONFIG_UBUFFER(inbuf, IBUFSIZ + 64);
RESERVE_CONFIG_UBUFFER(outbuf, OBUFSIZ + 2048);
unsigned char htab[HSIZE];
unsigned short codetab[HSIZE];
/* Hmm, these were statics - why?! */
/* user settable max # bits/code */
int maxbits; /* = BITS; */
/* block compress mode -C compatible with 2.0 */
int block_mode; /* = BLOCK_MODE; */
memset(inbuf, 0, IBUFSIZ + 64);
memset(outbuf, 0, OBUFSIZ + 2048);
insize = 0;
/* xread isn't good here, we have to return - caller may want
* to do some cleanup (e.g. delete incomplete unpacked file etc) */
if (full_read(fd_in, inbuf, 1) != 1) {
bb_error_msg("short read");
return -1;
}
inbuf[0] = xread_char(fd_in);
maxbits = inbuf[0] & BIT_MASK;
block_mode = inbuf[0] & BLOCK_MODE;
maxmaxcode = MAXCODE(maxbits);
if (maxbits > BITS) {
bb_error_msg("compressed with %d bits, can only handle "
"%d bits", maxbits, BITS);
bb_error_msg("compressed with %d bits, can only handle %d bits", maxbits,
BITS);
return -1;
}
n_bits = INIT_BITS;
maxcode = MAXCODE(INIT_BITS) - 1;
bitmask = (1 << INIT_BITS) - 1;
maxcode = MAXCODE(n_bits = INIT_BITS) - 1;
bitmask = (1 << n_bits) - 1;
oldcode = -1;
finchar = 0;
outpos = 0;
@@ -150,14 +145,13 @@ uncompress(int fd_in, int fd_out)
}
do {
resetbuf:
resetbuf:;
{
int i;
int e;
int o;
o = posbits >> 3;
e = insize - o;
e = insize - (o = (posbits >> 3));
for (i = 0; i < e; ++i)
inbuf[i] = inbuf[i + o];
@@ -166,9 +160,8 @@ uncompress(int fd_in, int fd_out)
posbits = 0;
}
if (insize < (int) (IBUFSIZ + 64) - IBUFSIZ) {
if (insize < (int) sizeof(inbuf) - IBUFSIZ) {
rsize = safe_read(fd_in, inbuf + insize, IBUFSIZ);
//error check??
insize += rsize;
}
@@ -193,16 +186,16 @@ uncompress(int fd_in, int fd_out)
{
unsigned char *p = &inbuf[posbits >> 3];
code = ((((long) (p[0])) | ((long) (p[1]) << 8) |
((long) (p[2]) << 16)) >> (posbits & 0x7)) & bitmask;
code =
((((long) (p[0])) | ((long) (p[1]) << 8) |
((long) (p[2]) << 16)) >> (posbits & 0x7)) & bitmask;
}
posbits += n_bits;
if (oldcode == -1) {
oldcode = code;
finchar = (int) oldcode;
outbuf[outpos++] = (unsigned char) finchar;
outbuf[outpos++] = (unsigned char) (finchar =
(int) (oldcode = code));
continue;
}
@@ -213,9 +206,8 @@ uncompress(int fd_in, int fd_out)
((posbits - 1) +
((n_bits << 3) -
(posbits - 1 + (n_bits << 3)) % (n_bits << 3)));
n_bits = INIT_BITS;
maxcode = MAXCODE(INIT_BITS) - 1;
bitmask = (1 << INIT_BITS) - 1;
maxcode = MAXCODE(n_bits = INIT_BITS) - 1;
bitmask = (1 << n_bits) - 1;
goto resetbuf;
}
@@ -248,15 +240,13 @@ uncompress(int fd_in, int fd_out)
code = tab_prefixof(code);
}
finchar = tab_suffixof(code);
*--stackp = (unsigned char) finchar;
*--stackp = (unsigned char) (finchar = tab_suffixof(code));
/* And put them out in forward order */
{
int i;
i = de_stack - stackp;
if (outpos + i >= OBUFSIZ) {
if (outpos + (i = (de_stack - stackp)) >= OBUFSIZ) {
do {
if (i > OBUFSIZ - outpos) {
i = OBUFSIZ - outpos;
@@ -268,14 +258,11 @@ uncompress(int fd_in, int fd_out)
}
if (outpos >= OBUFSIZ) {
full_write(fd_out, outbuf, outpos);
//error check??
USE_DESKTOP(total_written += outpos;)
write(fd_out, outbuf, outpos);
outpos = 0;
}
stackp += i;
i = de_stack - stackp;
} while (i > 0);
} while ((i = (de_stack - stackp)) > 0);
} else {
memcpy(outbuf + outpos, stackp, i);
outpos += i;
@@ -283,8 +270,7 @@ uncompress(int fd_in, int fd_out)
}
/* Generate the new entry. */
code = free_ent;
if (code < maxmaxcode) {
if ((code = free_ent) < maxmaxcode) {
tab_prefixof(code) = (unsigned short) oldcode;
tab_suffixof(code) = (unsigned char) finchar;
free_ent = code + 1;
@@ -297,12 +283,8 @@ uncompress(int fd_in, int fd_out)
} while (rsize > 0);
if (outpos > 0) {
full_write(fd_out, outbuf, outpos);
//error check??
USE_DESKTOP(total_written += outpos;)
write(fd_out, outbuf, outpos);
}
RELEASE_CONFIG_BUFFER(inbuf);
RELEASE_CONFIG_BUFFER(outbuf);
return USE_DESKTOP(total_written) + 0;
return 0;
}
+93 -120
View File
@@ -22,23 +22,15 @@
typedef struct {
int fd;
uint8_t *ptr;
/* Was keeping rc on stack in unlzma and separately allocating buffer,
* but with "buffer 'attached to' allocated rc" code is smaller: */
/* uint8_t *buffer; */
#define RC_BUFFER ((uint8_t*)(rc+1))
uint8_t *buffer;
uint8_t *buffer_end;
/* Had provisions for variable buffer, but we don't need it here */
/* int buffer_size; */
#define RC_BUFFER_SIZE 0x10000
int buffer_size;
uint32_t code;
uint32_t range;
uint32_t bound;
} rc_t;
#define RC_TOP_BITS 24
#define RC_MOVE_BITS 5
#define RC_MODEL_TOTAL_BITS 11
@@ -47,24 +39,22 @@ typedef struct {
/* Called twice: once at startup and once in rc_normalize() */
static void rc_read(rc_t * rc)
{
int buffer_size = safe_read(rc->fd, RC_BUFFER, RC_BUFFER_SIZE);
if (buffer_size <= 0)
rc->buffer_size = read(rc->fd, rc->buffer, rc->buffer_size);
if (rc->buffer_size <= 0)
bb_error_msg_and_die("unexpected EOF");
rc->ptr = RC_BUFFER;
rc->buffer_end = RC_BUFFER + buffer_size;
rc->ptr = rc->buffer;
rc->buffer_end = rc->buffer + rc->buffer_size;
}
/* Called once */
static rc_t* rc_init(int fd) /*, int buffer_size) */
static void rc_init(rc_t * rc, int fd, int buffer_size)
{
int i;
rc_t* rc;
rc = xmalloc(sizeof(rc_t) + RC_BUFFER_SIZE);
rc->fd = fd;
/* rc->buffer_size = buffer_size; */
rc->buffer_end = RC_BUFFER + RC_BUFFER_SIZE;
rc->buffer = xmalloc(buffer_size);
rc->buffer_size = buffer_size;
rc->buffer_end = rc->buffer + rc->buffer_size;
rc->ptr = rc->buffer_end;
rc->code = 0;
@@ -74,14 +64,13 @@ static rc_t* rc_init(int fd) /*, int buffer_size) */
rc_read(rc);
rc->code = (rc->code << 8) | *rc->ptr++;
}
return rc;
}
/* Called once */
/* Called once. TODO: bb_maybe_free() */
static ATTRIBUTE_ALWAYS_INLINE void rc_free(rc_t * rc)
{
if (ENABLE_FEATURE_CLEAN_UP)
free(rc);
free(rc->buffer);
}
/* Called twice, but one callsite is in speed_inline'd rc_is_bit_0_helper() */
@@ -174,63 +163,57 @@ typedef struct {
} __attribute__ ((packed)) lzma_header_t;
/* #defines will force compiler to compute/optimize each one with each usage.
* Have heart and use enum instead. */
enum {
LZMA_BASE_SIZE = 1846,
LZMA_LIT_SIZE = 768,
#define LZMA_BASE_SIZE 1846
#define LZMA_LIT_SIZE 768
LZMA_NUM_POS_BITS_MAX = 4,
#define LZMA_NUM_POS_BITS_MAX 4
LZMA_LEN_NUM_LOW_BITS = 3,
LZMA_LEN_NUM_MID_BITS = 3,
LZMA_LEN_NUM_HIGH_BITS = 8,
#define LZMA_LEN_NUM_LOW_BITS 3
#define LZMA_LEN_NUM_MID_BITS 3
#define LZMA_LEN_NUM_HIGH_BITS 8
LZMA_LEN_CHOICE = 0,
LZMA_LEN_CHOICE_2 = (LZMA_LEN_CHOICE + 1),
LZMA_LEN_LOW = (LZMA_LEN_CHOICE_2 + 1),
LZMA_LEN_MID = (LZMA_LEN_LOW \
+ (1 << (LZMA_NUM_POS_BITS_MAX + LZMA_LEN_NUM_LOW_BITS))),
LZMA_LEN_HIGH = (LZMA_LEN_MID \
+ (1 << (LZMA_NUM_POS_BITS_MAX + LZMA_LEN_NUM_MID_BITS))),
LZMA_NUM_LEN_PROBS = (LZMA_LEN_HIGH + (1 << LZMA_LEN_NUM_HIGH_BITS)),
#define LZMA_LEN_CHOICE 0
#define LZMA_LEN_CHOICE_2 (LZMA_LEN_CHOICE + 1)
#define LZMA_LEN_LOW (LZMA_LEN_CHOICE_2 + 1)
#define LZMA_LEN_MID (LZMA_LEN_LOW \
+ (1 << (LZMA_NUM_POS_BITS_MAX + LZMA_LEN_NUM_LOW_BITS)))
#define LZMA_LEN_HIGH (LZMA_LEN_MID \
+(1 << (LZMA_NUM_POS_BITS_MAX + LZMA_LEN_NUM_MID_BITS)))
#define LZMA_NUM_LEN_PROBS (LZMA_LEN_HIGH + (1 << LZMA_LEN_NUM_HIGH_BITS))
LZMA_NUM_STATES = 12,
LZMA_NUM_LIT_STATES = 7,
#define LZMA_NUM_STATES 12
#define LZMA_NUM_LIT_STATES 7
LZMA_START_POS_MODEL_INDEX = 4,
LZMA_END_POS_MODEL_INDEX = 14,
LZMA_NUM_FULL_DISTANCES = (1 << (LZMA_END_POS_MODEL_INDEX >> 1)),
#define LZMA_START_POS_MODEL_INDEX 4
#define LZMA_END_POS_MODEL_INDEX 14
#define LZMA_NUM_FULL_DISTANCES (1 << (LZMA_END_POS_MODEL_INDEX >> 1))
LZMA_NUM_POS_SLOT_BITS = 6,
LZMA_NUM_LEN_TO_POS_STATES = 4,
#define LZMA_NUM_POS_SLOT_BITS 6
#define LZMA_NUM_LEN_TO_POS_STATES 4
LZMA_NUM_ALIGN_BITS = 4,
#define LZMA_NUM_ALIGN_BITS 4
LZMA_MATCH_MIN_LEN = 2,
#define LZMA_MATCH_MIN_LEN 2
LZMA_IS_MATCH = 0,
LZMA_IS_REP = (LZMA_IS_MATCH + (LZMA_NUM_STATES << LZMA_NUM_POS_BITS_MAX)),
LZMA_IS_REP_G0 = (LZMA_IS_REP + LZMA_NUM_STATES),
LZMA_IS_REP_G1 = (LZMA_IS_REP_G0 + LZMA_NUM_STATES),
LZMA_IS_REP_G2 = (LZMA_IS_REP_G1 + LZMA_NUM_STATES),
LZMA_IS_REP_0_LONG = (LZMA_IS_REP_G2 + LZMA_NUM_STATES),
LZMA_POS_SLOT = (LZMA_IS_REP_0_LONG \
+ (LZMA_NUM_STATES << LZMA_NUM_POS_BITS_MAX)),
LZMA_SPEC_POS = (LZMA_POS_SLOT \
+ (LZMA_NUM_LEN_TO_POS_STATES << LZMA_NUM_POS_SLOT_BITS)),
LZMA_ALIGN = (LZMA_SPEC_POS \
+ LZMA_NUM_FULL_DISTANCES - LZMA_END_POS_MODEL_INDEX),
LZMA_LEN_CODER = (LZMA_ALIGN + (1 << LZMA_NUM_ALIGN_BITS)),
LZMA_REP_LEN_CODER = (LZMA_LEN_CODER + LZMA_NUM_LEN_PROBS),
LZMA_LITERAL = (LZMA_REP_LEN_CODER + LZMA_NUM_LEN_PROBS),
};
#define LZMA_IS_MATCH 0
#define LZMA_IS_REP (LZMA_IS_MATCH + (LZMA_NUM_STATES <<LZMA_NUM_POS_BITS_MAX))
#define LZMA_IS_REP_G0 (LZMA_IS_REP + LZMA_NUM_STATES)
#define LZMA_IS_REP_G1 (LZMA_IS_REP_G0 + LZMA_NUM_STATES)
#define LZMA_IS_REP_G2 (LZMA_IS_REP_G1 + LZMA_NUM_STATES)
#define LZMA_IS_REP_0_LONG (LZMA_IS_REP_G2 + LZMA_NUM_STATES)
#define LZMA_POS_SLOT (LZMA_IS_REP_0_LONG \
+ (LZMA_NUM_STATES << LZMA_NUM_POS_BITS_MAX))
#define LZMA_SPEC_POS (LZMA_POS_SLOT \
+(LZMA_NUM_LEN_TO_POS_STATES << LZMA_NUM_POS_SLOT_BITS))
#define LZMA_ALIGN (LZMA_SPEC_POS \
+ LZMA_NUM_FULL_DISTANCES - LZMA_END_POS_MODEL_INDEX)
#define LZMA_LEN_CODER (LZMA_ALIGN + (1 << LZMA_NUM_ALIGN_BITS))
#define LZMA_REP_LEN_CODER (LZMA_LEN_CODER + LZMA_NUM_LEN_PROBS)
#define LZMA_LITERAL (LZMA_REP_LEN_CODER + LZMA_NUM_LEN_PROBS)
USE_DESKTOP(long long) int
unlzma(int src_fd, int dst_fd)
int unlzma(int src_fd, int dst_fd)
{
USE_DESKTOP(long long total_written = 0;)
lzma_header_t header;
int lc, pb, lp;
uint32_t pos_state_mask;
@@ -241,7 +224,7 @@ unlzma(int src_fd, int dst_fd)
uint16_t *prob_lit;
int num_bits;
int num_probs;
rc_t *rc;
rc_t rc;
int i, mi;
uint8_t *buffer;
uint8_t previous_byte = 0;
@@ -250,7 +233,8 @@ unlzma(int src_fd, int dst_fd)
int state = 0;
uint32_t rep0 = 1, rep1 = 1, rep2 = 1, rep3 = 1;
xread(src_fd, &header, sizeof(header));
if (read(src_fd, &header, sizeof(header)) != sizeof(header))
bb_error_msg_and_die("can't read header");
if (header.pos >= (9 * 5 * 5))
bb_error_msg_and_die("bad header");
@@ -275,16 +259,16 @@ unlzma(int src_fd, int dst_fd)
for (i = 0; i < num_probs; i++)
p[i] = (1 << RC_MODEL_TOTAL_BITS) >> 1;
rc = rc_init(src_fd); /*, RC_BUFFER_SIZE); */
rc_init(&rc, src_fd, 0x10000);
while (global_pos + buffer_pos < header.dst_size) {
int pos_state = (buffer_pos + global_pos) & pos_state_mask;
prob =
p + LZMA_IS_MATCH + (state << LZMA_NUM_POS_BITS_MAX) + pos_state;
if (rc_is_bit_0(rc, prob)) {
if (rc_is_bit_0(&rc, prob)) {
mi = 1;
rc_update_bit_0(rc, prob);
rc_update_bit_0(&rc, prob);
prob = (p + LZMA_LITERAL + (LZMA_LIT_SIZE
* ((((buffer_pos + global_pos) & literal_pos_mask) << lc)
+ (previous_byte >> (8 - lc)))));
@@ -302,7 +286,7 @@ unlzma(int src_fd, int dst_fd)
match_byte <<= 1;
bit = match_byte & 0x100;
prob_lit = prob + 0x100 + bit + mi;
if (rc_get_bit(rc, prob_lit, &mi)) {
if (rc_get_bit(&rc, prob_lit, &mi)) {
if (!bit)
break;
} else {
@@ -313,7 +297,7 @@ unlzma(int src_fd, int dst_fd)
}
while (mi < 0x100) {
prob_lit = prob + mi;
rc_get_bit(rc, prob_lit, &mi);
rc_get_bit(&rc, prob_lit, &mi);
}
previous_byte = (uint8_t) mi;
@@ -321,9 +305,7 @@ unlzma(int src_fd, int dst_fd)
if (buffer_pos == header.dict_size) {
buffer_pos = 0;
global_pos += header.dict_size;
if (full_write(dst_fd, buffer, header.dict_size) != header.dict_size)
goto bad;
USE_DESKTOP(total_written += header.dict_size;)
write(dst_fd, buffer, header.dict_size);
}
if (state < 4)
state = 0;
@@ -335,24 +317,24 @@ unlzma(int src_fd, int dst_fd)
int offset;
uint16_t *prob_len;
rc_update_bit_1(rc, prob);
rc_update_bit_1(&rc, prob);
prob = p + LZMA_IS_REP + state;
if (rc_is_bit_0(rc, prob)) {
rc_update_bit_0(rc, prob);
if (rc_is_bit_0(&rc, prob)) {
rc_update_bit_0(&rc, prob);
rep3 = rep2;
rep2 = rep1;
rep1 = rep0;
state = state < LZMA_NUM_LIT_STATES ? 0 : 3;
prob = p + LZMA_LEN_CODER;
} else {
rc_update_bit_1(rc, prob);
rc_update_bit_1(&rc, prob);
prob = p + LZMA_IS_REP_G0 + state;
if (rc_is_bit_0(rc, prob)) {
rc_update_bit_0(rc, prob);
if (rc_is_bit_0(&rc, prob)) {
rc_update_bit_0(&rc, prob);
prob = (p + LZMA_IS_REP_0_LONG
+ (state << LZMA_NUM_POS_BITS_MAX) + pos_state);
if (rc_is_bit_0(rc, prob)) {
rc_update_bit_0(rc, prob);
if (rc_is_bit_0(&rc, prob)) {
rc_update_bit_0(&rc, prob);
state = state < LZMA_NUM_LIT_STATES ? 9 : 11;
pos = buffer_pos - rep0;
@@ -363,30 +345,28 @@ unlzma(int src_fd, int dst_fd)
if (buffer_pos == header.dict_size) {
buffer_pos = 0;
global_pos += header.dict_size;
if (full_write(dst_fd, buffer, header.dict_size) != header.dict_size)
goto bad;
USE_DESKTOP(total_written += header.dict_size;)
write(dst_fd, buffer, header.dict_size);
}
continue;
} else {
rc_update_bit_1(rc, prob);
rc_update_bit_1(&rc, prob);
}
} else {
uint32_t distance;
rc_update_bit_1(rc, prob);
rc_update_bit_1(&rc, prob);
prob = p + LZMA_IS_REP_G1 + state;
if (rc_is_bit_0(rc, prob)) {
rc_update_bit_0(rc, prob);
if (rc_is_bit_0(&rc, prob)) {
rc_update_bit_0(&rc, prob);
distance = rep1;
} else {
rc_update_bit_1(rc, prob);
rc_update_bit_1(&rc, prob);
prob = p + LZMA_IS_REP_G2 + state;
if (rc_is_bit_0(rc, prob)) {
rc_update_bit_0(rc, prob);
if (rc_is_bit_0(&rc, prob)) {
rc_update_bit_0(&rc, prob);
distance = rep2;
} else {
rc_update_bit_1(rc, prob);
rc_update_bit_1(&rc, prob);
distance = rep3;
rep3 = rep2;
}
@@ -400,30 +380,30 @@ unlzma(int src_fd, int dst_fd)
}
prob_len = prob + LZMA_LEN_CHOICE;
if (rc_is_bit_0(rc, prob_len)) {
rc_update_bit_0(rc, prob_len);
if (rc_is_bit_0(&rc, prob_len)) {
rc_update_bit_0(&rc, prob_len);
prob_len = (prob + LZMA_LEN_LOW
+ (pos_state << LZMA_LEN_NUM_LOW_BITS));
offset = 0;
num_bits = LZMA_LEN_NUM_LOW_BITS;
} else {
rc_update_bit_1(rc, prob_len);
rc_update_bit_1(&rc, prob_len);
prob_len = prob + LZMA_LEN_CHOICE_2;
if (rc_is_bit_0(rc, prob_len)) {
rc_update_bit_0(rc, prob_len);
if (rc_is_bit_0(&rc, prob_len)) {
rc_update_bit_0(&rc, prob_len);
prob_len = (prob + LZMA_LEN_MID
+ (pos_state << LZMA_LEN_NUM_MID_BITS));
offset = 1 << LZMA_LEN_NUM_LOW_BITS;
num_bits = LZMA_LEN_NUM_MID_BITS;
} else {
rc_update_bit_1(rc, prob_len);
rc_update_bit_1(&rc, prob_len);
prob_len = prob + LZMA_LEN_HIGH;
offset = ((1 << LZMA_LEN_NUM_LOW_BITS)
+ (1 << LZMA_LEN_NUM_MID_BITS));
num_bits = LZMA_LEN_NUM_HIGH_BITS;
}
}
rc_bit_tree_decode(rc, prob_len, num_bits, &len);
rc_bit_tree_decode(&rc, prob_len, num_bits, &len);
len += offset;
if (state < 4) {
@@ -436,7 +416,7 @@ unlzma(int src_fd, int dst_fd)
LZMA_NUM_LEN_TO_POS_STATES ? len :
LZMA_NUM_LEN_TO_POS_STATES - 1)
<< LZMA_NUM_POS_SLOT_BITS);
rc_bit_tree_decode(rc, prob, LZMA_NUM_POS_SLOT_BITS,
rc_bit_tree_decode(&rc, prob, LZMA_NUM_POS_SLOT_BITS,
&pos_slot);
if (pos_slot >= LZMA_START_POS_MODEL_INDEX) {
num_bits = (pos_slot >> 1) - 1;
@@ -447,7 +427,7 @@ unlzma(int src_fd, int dst_fd)
} else {
num_bits -= LZMA_NUM_ALIGN_BITS;
while (num_bits--)
rep0 = (rep0 << 1) | rc_direct_bit(rc);
rep0 = (rep0 << 1) | rc_direct_bit(&rc);
prob = p + LZMA_ALIGN;
rep0 <<= LZMA_NUM_ALIGN_BITS;
num_bits = LZMA_NUM_ALIGN_BITS;
@@ -455,7 +435,7 @@ unlzma(int src_fd, int dst_fd)
i = 1;
mi = 1;
while (num_bits--) {
if (rc_get_bit(rc, prob + mi, &mi))
if (rc_get_bit(&rc, prob + mi, &mi))
rep0 |= i;
i <<= 1;
}
@@ -476,22 +456,15 @@ unlzma(int src_fd, int dst_fd)
if (buffer_pos == header.dict_size) {
buffer_pos = 0;
global_pos += header.dict_size;
if (full_write(dst_fd, buffer, header.dict_size) != header.dict_size)
goto bad;
USE_DESKTOP(total_written += header.dict_size;)
write(dst_fd, buffer, header.dict_size);
}
len--;
} while (len != 0 && buffer_pos < header.dst_size);
}
}
if (full_write(dst_fd, buffer, buffer_pos) != buffer_pos) {
bad:
rc_free(rc);
return -1;
}
rc_free(rc);
USE_DESKTOP(total_written += buffer_pos;)
return USE_DESKTOP(total_written) + 0;
write(dst_fd, buffer, buffer_pos);
rc_free(&rc);
return 0;
}
File diff suppressed because it is too large. Load diff
+5 -3
View File
@@ -11,7 +11,9 @@
/* Accept any non-null name, its not really a filter at all */
char filter_accept_all(archive_handle_t *archive_handle)
{
if (archive_handle->file_header->name)
return EXIT_SUCCESS;
return EXIT_FAILURE;
if (archive_handle->file_header->name) {
return(EXIT_SUCCESS);
} else {
return(EXIT_FAILURE);
}
}
+5 -3
View File
@@ -13,7 +13,9 @@
*/
char filter_accept_list(archive_handle_t *archive_handle)
{
if (find_list_entry(archive_handle->accept, archive_handle->file_header->name))
return EXIT_SUCCESS;
return EXIT_FAILURE;
if (find_list_entry(archive_handle->accept, archive_handle->file_header->name)) {
return(EXIT_SUCCESS);
} else {
return(EXIT_FAILURE);
}
}
@@ -5,13 +5,17 @@
* Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
*/
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "libbb.h"
#include "unarchive.h"
/*
* Reassign the subarchive metadata parser based on the filename extension
* e.g. if its a .tar.gz modify archive_handle->sub_archive to process a .tar.gz
* or if its a .tar.bz2 make archive_handle->sub_archive handle that
* Reassign the subarchive metadata parser based on the filename extension
* e.g. if its a .tar.gz modify archive_handle->sub_archive to process a .tar.gz
* or if its a .tar.bz2 make archive_handle->sub_archive handle that
*/
char filter_accept_list_reassign(archive_handle_t *archive_handle)
{
@@ -26,19 +30,19 @@ char filter_accept_list_reassign(archive_handle_t *archive_handle)
#ifdef CONFIG_FEATURE_DEB_TAR_GZ
if (strcmp(name_ptr, ".gz") == 0) {
archive_handle->action_data_subarchive = get_header_tar_gz;
return EXIT_SUCCESS;
return(EXIT_SUCCESS);
}
#endif
#ifdef CONFIG_FEATURE_DEB_TAR_BZ2
if (strcmp(name_ptr, ".bz2") == 0) {
archive_handle->action_data_subarchive = get_header_tar_bz2;
return EXIT_SUCCESS;
return(EXIT_SUCCESS);
}
#endif
if (ENABLE_FEATURE_DEB_TAR_LZMA && !strcmp(name_ptr, ".lzma")) {
archive_handle->action_data_subarchive = get_header_tar_lzma;
return EXIT_SUCCESS;
return(EXIT_SUCCESS);
}
}
return EXIT_FAILURE;
return(EXIT_FAILURE);
}
@@ -14,20 +14,20 @@
char filter_accept_reject_list(archive_handle_t *archive_handle)
{
const char *key = archive_handle->file_header->name;
const llist_t *reject_entry = find_list_entry2(archive_handle->reject, key);
const llist_t *reject_entry = find_list_entry(archive_handle->reject, key);
const llist_t *accept_entry;
/* If the key is in a reject list fail */
if (reject_entry) {
return EXIT_FAILURE;
return(EXIT_FAILURE);
}
accept_entry = find_list_entry2(archive_handle->accept, key);
accept_entry = find_list_entry(archive_handle->accept, key);
/* Fail if an accept list was specified and the key wasnt in there */
if ((accept_entry == NULL) && archive_handle->accept) {
return EXIT_FAILURE;
return(EXIT_FAILURE);
}
/* Accepted */
return EXIT_SUCCESS;
return(EXIT_SUCCESS);
}
+3 -35
View File
@@ -9,46 +9,14 @@
#include <stdlib.h>
#include "unarchive.h"
/* Find a string in a shell pattern list */
/* Find a string in a list */
const llist_t *find_list_entry(const llist_t *list, const char *filename)
{
while (list) {
if (fnmatch(list->data, filename, 0) == 0) {
return list;
return (list);
}
list = list->link;
}
return NULL;
}
/* Same, but compares only path components present in pattern
* (extra trailing path components in filename are assumed to match)
*/
const llist_t *find_list_entry2(const llist_t *list, const char *filename)
{
char buf[PATH_MAX];
int pattern_slash_cnt;
const char *c;
char *d;
while (list) {
c = list->data;
pattern_slash_cnt = 0;
while (*c)
if (*c++ == '/') pattern_slash_cnt++;
c = filename;
d = buf;
/* paranoia is better that buffer overflows */
while (*c && d != buf + sizeof(buf)-1) {
if (*c == '/' && --pattern_slash_cnt < 0)
break;
*d++ = *c++;
}
*d = '\0';
if (fnmatch(list->data, buf, 0) == 0) {
return list;
}
list = list->link;
}
return NULL;
return(NULL);
}
+27 -33
View File
@@ -4,12 +4,15 @@
* Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
*/
#include "libbb.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "unarchive.h"
#include "libbb.h"
char get_header_ar(archive_handle_t *archive_handle)
{
int err;
file_header_t *typed = archive_handle->file_header;
union {
char raw[60];
@@ -21,17 +24,17 @@ char get_header_ar(archive_handle_t *archive_handle)
char mode[8];
char size[10];
char magic[2];
} formatted;
} formated;
} ar;
#ifdef CONFIG_FEATURE_AR_LONG_FILENAMES
static char *ar_long_names;
static unsigned int ar_long_name_size;
#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) {
/* End Of File */
return EXIT_FAILURE;
return(EXIT_FAILURE);
}
/* ar header starts on an even byte (2 byte aligned)
@@ -46,28 +49,20 @@ char get_header_ar(archive_handle_t *archive_handle)
archive_handle->offset += 60;
/* align the headers based on the header magic */
if (ar.formatted.magic[0] != '`' || ar.formatted.magic[1] != '\n')
bb_error_msg_and_die("invalid ar header");
if ((ar.formated.magic[0] != '`') || (ar.formated.magic[1] != '\n')) {
bb_error_msg_and_die("Invalid ar header");
}
/* FIXME: more thorough routine would be in order here */
/* (we have something like that in tar) */
/* but for now we are lax. This code works because */
/* on misformatted numbers bb_strtou returns all-ones */
typed->mode = err = bb_strtou(ar.formatted.mode, NULL, 8);
if (err == -1) bb_error_msg_and_die("invalid ar header");
typed->mtime = err = bb_strtou(ar.formatted.date, NULL, 10);
if (err == -1) bb_error_msg_and_die("invalid ar header");
typed->uid = err = bb_strtou(ar.formatted.uid, NULL, 10);
if (err == -1) bb_error_msg_and_die("invalid ar header");
typed->gid = err = bb_strtou(ar.formatted.gid, NULL, 10);
if (err == -1) bb_error_msg_and_die("invalid ar header");
typed->size = err = bb_strtou(ar.formatted.size, NULL, 10);
if (err == -1) bb_error_msg_and_die("invalid ar header");
typed->mode = strtol(ar.formated.mode, NULL, 8);
typed->mtime = atoi(ar.formated.date);
typed->uid = atoi(ar.formated.uid);
typed->gid = atoi(ar.formated.gid);
typed->size = atoi(ar.formated.size);
/* long filenames have '/' as the first character */
if (ar.formatted.name[0] == '/') {
if (ar.formated.name[0] == '/') {
#ifdef CONFIG_FEATURE_AR_LONG_FILENAMES
if (ar.formatted.name[1] == '/') {
if (ar.formated.name[1] == '/') {
/* If the second char is a '/' then this entries data section
* stores long filename for multiple entries, they are stored
* in static variable long_names for use in future entries */
@@ -77,27 +72,27 @@ char get_header_ar(archive_handle_t *archive_handle)
archive_handle->offset += ar_long_name_size;
/* This ar entries data section only contained filenames for other records
* they are stored in the static ar_long_names for future reference */
return get_header_ar(archive_handle); /* Return next header */
} else if (ar.formatted.name[1] == ' ') {
return (get_header_ar(archive_handle)); /* Return next header */
} else if (ar.formated.name[1] == ' ') {
/* This is the index of symbols in the file for compilers */
data_skip(archive_handle);
archive_handle->offset += typed->size;
return get_header_ar(archive_handle); /* Return next header */
return (get_header_ar(archive_handle)); /* Return next header */
} else {
/* The number after the '/' indicates the offset in the ar data section
(saved in variable long_name) that conatains the real filename */
const unsigned int long_offset = atoi(&ar.formatted.name[1]);
const unsigned int long_offset = atoi(&ar.formated.name[1]);
if (long_offset >= ar_long_name_size) {
bb_error_msg_and_die("can't 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
bb_error_msg_and_die("long filenames not supported");
#endif
} else {
/* short filenames */
typed->name = xstrndup(ar.formatted.name, 16);
typed->name = bb_xstrndup(ar.formated.name, 16);
}
typed->name[strcspn(typed->name, " /")] = '\0';
@@ -105,8 +100,7 @@ char get_header_ar(archive_handle_t *archive_handle)
if (archive_handle->filter(archive_handle) == EXIT_SUCCESS) {
archive_handle->action_header(typed);
if (archive_handle->sub_archive) {
while (archive_handle->action_data_subarchive(archive_handle->sub_archive) == EXIT_SUCCESS)
/* repeat */;
while (archive_handle->action_data_subarchive(archive_handle->sub_archive) == EXIT_SUCCESS);
} else {
archive_handle->action_data(archive_handle);
}
@@ -118,5 +112,5 @@ char get_header_ar(archive_handle_t *archive_handle)
/* Set the file pointer to the correct spot, we may have been reading a compressed file */
lseek(archive_handle->src_fd, archive_handle->offset, SEEK_SET);
return EXIT_SUCCESS;
return(EXIT_SUCCESS);
}
+50 -60
View File
@@ -4,11 +4,16 @@
* Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
*/
#include "libbb.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/sysmacros.h> /* major() and minor() */
#include "unarchive.h"
#include "libbb.h"
typedef struct hardlinks_s {
char *name;
file_header_t *entry;
int inode;
struct hardlinks_s *next;
} hardlinks_t;
@@ -17,81 +22,60 @@ char get_header_cpio(archive_handle_t *archive_handle)
{
static hardlinks_t *saved_hardlinks = NULL;
static unsigned short pending_hardlinks = 0;
static int inode;
file_header_t *file_header = archive_handle->file_header;
char cpio_header[110];
int namesize;
char dummy[16];
int major, minor, nlink;
int major, minor, nlink, inode;
if (pending_hardlinks) { /* Deal with any pending hardlinks */
hardlinks_t *tmp, *oldtmp;
hardlinks_t *tmp;
hardlinks_t *oldtmp;
tmp = saved_hardlinks;
oldtmp = NULL;
file_header->link_name = file_header->name;
file_header->size = 0;
while (tmp) {
if (tmp->inode != inode) {
tmp = tmp->next;
bb_error_msg_and_die("need to fix this\n");
if (tmp->entry->link_name) { /* Found a hardlink ready to be extracted */
file_header = tmp->entry;
if (oldtmp) {
oldtmp->next = tmp->next; /* Remove item from linked list */
} else {
saved_hardlinks = tmp->next;
}
free(tmp);
continue;
}
file_header->name = tmp->name;
if (archive_handle->filter(archive_handle) == EXIT_SUCCESS) {
archive_handle->action_data(archive_handle);
archive_handle->action_header(archive_handle->file_header);
}
pending_hardlinks--;
oldtmp = tmp;
tmp = tmp->next;
free(oldtmp->name);
free(oldtmp);
if (oldtmp == saved_hardlinks)
saved_hardlinks = tmp;
}
file_header->name = file_header->link_name;
if (pending_hardlinks > 1) {
bb_error_msg("error resolving hardlink: archive made by GNU cpio 2.0-2.2?");
}
/* No more pending hardlinks, read next file entry */
pending_hardlinks = 0;
pending_hardlinks = 0; /* No more pending hardlinks, read next file entry */
}
/* There can be padding before archive header */
data_align(archive_handle, 4);
if (archive_xread_all_eof(archive_handle, (unsigned char*)cpio_header, 110) == 0) {
return EXIT_FAILURE;
return(EXIT_FAILURE);
}
archive_handle->offset += 110;
if (strncmp(&cpio_header[0], "07070", 5) != 0
|| (cpio_header[5] != '1' && cpio_header[5] != '2')
) {
bb_error_msg_and_die("unsupported cpio format, use newc or crc");
if ((strncmp(&cpio_header[0], "07070", 5) != 0) || ((cpio_header[5] != '1') && (cpio_header[5] != '2'))) {
bb_error_msg_and_die("Unsupported cpio format, use newc or crc");
}
{
unsigned long tmpsize;
sscanf(cpio_header, "%6c%8x%8x%8x%8x%8x%8lx%8lx%16c%8x%8x%8x%8c",
unsigned long tmpsize;
sscanf(cpio_header, "%6c%8x%8x%8x%8x%8x%8lx%8lx%16c%8x%8x%8x%8c",
dummy, &inode, (unsigned int*)&file_header->mode,
(unsigned int*)&file_header->uid, (unsigned int*)&file_header->gid,
&nlink, &file_header->mtime, &tmpsize,
dummy, &major, &minor, &namesize, dummy);
file_header->size = tmpsize;
file_header->size = tmpsize;
}
free(file_header->name);
file_header->name = xzalloc(namesize + 1);
file_header->name = (char *) xzalloc(namesize + 1);
/* Read in filename */
xread(archive_handle->src_fd, file_header->name, namesize);
archive_handle->offset += namesize;
@@ -100,29 +84,26 @@ char get_header_cpio(archive_handle_t *archive_handle)
data_align(archive_handle, 4);
if (strcmp(file_header->name, "TRAILER!!!") == 0) {
/* Always round up */
printf("%d blocks\n", (int) (archive_handle->offset % 512 ?
archive_handle->offset / 512 + 1 :
archive_handle->offset / 512
));
printf("%d blocks\n", (int) (archive_handle->offset % 512 ? (archive_handle->offset / 512) + 1 : archive_handle->offset / 512)); /* Always round up */
if (saved_hardlinks) { /* Bummer - we still have unresolved hardlinks */
hardlinks_t *tmp = saved_hardlinks;
hardlinks_t *oldtmp = NULL;
while (tmp) {
bb_error_msg("%s not created: cannot resolve hardlink", tmp->name);
bb_error_msg("%s not created: cannot resolve hardlink", tmp->entry->name);
oldtmp = tmp;
tmp = tmp->next;
free(oldtmp->name);
free(oldtmp);
free (oldtmp->entry->name);
free (oldtmp->entry);
free (oldtmp);
}
saved_hardlinks = NULL;
pending_hardlinks = 0;
}
return EXIT_FAILURE;
return(EXIT_FAILURE);
}
if (S_ISLNK(file_header->mode)) {
file_header->link_name = xzalloc(file_header->size + 1);
file_header->link_name = (char *) xzalloc(file_header->size + 1);
xread(archive_handle->src_fd, file_header->link_name, file_header->size);
archive_handle->offset += file_header->size;
file_header->size = 0; /* Stop possible seeks in future */
@@ -134,14 +115,23 @@ char get_header_cpio(archive_handle_t *archive_handle)
hardlinks_t *new = xmalloc(sizeof(hardlinks_t));
new->next = saved_hardlinks;
new->inode = inode;
/* name current allocated, freed later */
new->name = file_header->name;
file_header->name = NULL;
new->entry = file_header;
saved_hardlinks = new;
return EXIT_SUCCESS; /* Skip this one */
return(EXIT_SUCCESS); // Skip this one
} else { /* Found the file with data in */
hardlinks_t *tmp = saved_hardlinks;
pending_hardlinks = 1;
while (tmp) {
if (tmp->inode == inode) {
tmp->entry->link_name = bb_xstrdup(file_header->name);
nlink--;
}
tmp = tmp->next;
}
if (nlink > 1) {
bb_error_msg("error resolving hardlink: did you create the archive with GNU cpio 2.0-2.2?");
}
}
/* Found the file with data in */
pending_hardlinks = nlink;
}
file_header->device = makedev(major, minor);
@@ -156,5 +146,5 @@ char get_header_cpio(archive_handle_t *archive_handle)
free(file_header->link_name);
return EXIT_SUCCESS;
return (EXIT_SUCCESS);
}
+114 -176
View File
@@ -1,4 +1,3 @@
/* vi: set sw=4 ts=4: */
/* Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
*
* FIXME:
@@ -11,172 +10,142 @@
* http://www.opengroup.org/onlinepubs/007904975/utilities/pax.html
*/
#include "libbb.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/sysmacros.h> /* For makedev */
#include "unarchive.h"
#include "libbb.h"
#if ENABLE_FEATURE_TAR_GNU_EXTENSIONS
static char *longname;
static char *linkname;
#else
enum {
longname = 0,
linkname = 0,
};
#ifdef CONFIG_FEATURE_TAR_GNU_EXTENSIONS
static char *longname = NULL;
static char *linkname = NULL;
#endif
/* NB: _DESTROYS_ str[len] character! */
static unsigned long long getOctal(char *str, int len)
{
unsigned long long v;
/* Actually, tar header allows leading spaces also.
* Oh well, we will be liberal and skip this...
* The only downside probably is that we allow "-123" too :)
if (*str < '0' || *str > '7')
bb_error_msg_and_die("corrupted octal value in tar header");
*/
str[len] = '\0';
v = strtoull(str, &str, 8);
if (*str)
bb_error_msg_and_die("corrupted octal value in tar header");
return v;
}
#define GET_OCTAL(a) getOctal((a), sizeof(a))
void BUG_tar_header_size(void);
char get_header_tar(archive_handle_t *archive_handle)
{
static int end;
file_header_t *file_header = archive_handle->file_header;
struct {
union {
/* ustar header, Posix 1003.1 */
char name[100]; /* 0-99 */
char mode[8]; /* 100-107 */
char uid[8]; /* 108-115 */
char gid[8]; /* 116-123 */
char size[12]; /* 124-135 */
char mtime[12]; /* 136-147 */
char chksum[8]; /* 148-155 */
char typeflag; /* 156-156 */
char linkname[100]; /* 157-256 */
char magic[6]; /* 257-262 */
char version[2]; /* 263-264 */
char uname[32]; /* 265-296 */
char gname[32]; /* 297-328 */
char devmajor[8]; /* 329-336 */
char devminor[8]; /* 337-344 */
char prefix[155]; /* 345-499 */
char padding[12]; /* 500-512 */
unsigned char raw[512];
struct {
char name[100]; /* 0-99 */
char mode[8]; /* 100-107 */
char uid[8]; /* 108-115 */
char gid[8]; /* 116-123 */
char size[12]; /* 124-135 */
char mtime[12]; /* 136-147 */
char chksum[8]; /* 148-155 */
char typeflag; /* 156-156 */
char linkname[100]; /* 157-256 */
char magic[6]; /* 257-262 */
char version[2]; /* 263-264 */
char uname[32]; /* 265-296 */
char gname[32]; /* 297-328 */
char devmajor[8]; /* 329-336 */
char devminor[8]; /* 337-344 */
char prefix[155]; /* 345-499 */
char padding[12]; /* 500-512 */
} formated;
} tar;
char *cp;
int sum, i;
int parse_names;
long sum = 0;
long i;
static int end = 0;
if (sizeof(tar) != 512)
BUG_tar_header_size();
#if ENABLE_FEATURE_TAR_GNU_EXTENSIONS
again:
#endif
/* Align header */
data_align(archive_handle, 512);
again_after_align:
xread(archive_handle->src_fd, &tar, 512);
if (bb_full_read(archive_handle->src_fd, tar.raw, 512) != 512) {
/* Assume end of file */
bb_error_msg_and_die("Short header");
//return(EXIT_FAILURE);
}
archive_handle->offset += 512;
/* If there is no filename its an empty header */
if (tar.name[0] == 0) {
if (tar.formated.name[0] == 0) {
if (end) {
/* This is the second consecutive empty header! End of archive!
* Read until the end to empty the pipe from gz or bz2
*/
while (full_read(archive_handle->src_fd, &tar, 512) == 512)
/* repeat */;
return EXIT_FAILURE;
while (bb_full_read(archive_handle->src_fd, tar.raw, 512) == 512);
return(EXIT_FAILURE);
}
end = 1;
return EXIT_SUCCESS;
return(EXIT_SUCCESS);
}
end = 0;
/* Check header has valid magic, "ustar" is for the proper tar
* 0's are for the old tar format
*/
if (strncmp(tar.magic, "ustar", 5) != 0) {
#if ENABLE_FEATURE_TAR_OLDGNU_COMPATIBILITY
if (memcmp(tar.magic, "\0\0\0\0", 5) != 0)
if (strncmp(tar.formated.magic, "ustar", 5) != 0) {
#ifdef CONFIG_FEATURE_TAR_OLDGNU_COMPATIBILITY
if (strncmp(tar.formated.magic, "\0\0\0\0\0", 5) != 0)
#endif
bb_error_msg_and_die("invalid tar magic");
bb_error_msg_and_die("Invalid tar magic");
}
/* Do checksum on headers */
sum = ' ' * sizeof(tar.chksum);
for (i = 0; i < 148 ; i++) {
sum += ((char*)&tar)[i];
for (i = 0; i < 148 ; i++) {
sum += tar.raw[i];
}
for (i = 156; i < 512 ; i++) {
sum += ((char*)&tar)[i];
sum += ' ' * 8;
for (i = 156; i < 512 ; i++) {
sum += tar.raw[i];
}
/* This field does not need special treatment (getOctal) */
if (sum != xstrtoul(tar.chksum, 8)) {
bb_error_msg_and_die("invalid tar header checksum");
if (sum != strtol(tar.formated.chksum, NULL, 8)) {
bb_error_msg("Invalid tar header checksum");
return(EXIT_FAILURE);
}
/* 0 is reserved for high perf file, treat as normal file */
if (!tar.typeflag) tar.typeflag = '0';
parse_names = (tar.typeflag >= '0' && tar.typeflag <= '7');
#ifdef CONFIG_FEATURE_TAR_GNU_EXTENSIONS
if (longname) {
file_header->name = longname;
longname = NULL;
}
else if (linkname) {
file_header->name = linkname;
linkname = NULL;
} else
#endif
{
file_header->name = bb_xstrndup(tar.formated.name,100);
/* getOctal trashes subsequent field, therefore we call it
* on fields in reverse order */
if (tar.devmajor[0]) {
unsigned minor = GET_OCTAL(tar.devminor);
unsigned major = GET_OCTAL(tar.devmajor);
file_header->device = makedev(major, minor);
if (tar.formated.prefix[0]) {
char *temp = file_header->name;
file_header->name = concat_path_file(tar.formated.prefix, temp);
free(temp);
}
}
file_header->link_name = NULL;
if (!linkname && parse_names && tar.linkname[0]) {
/* we trash magic[0] here, it's ok */
tar.linkname[sizeof(tar.linkname)] = '\0';
file_header->link_name = xstrdup(tar.linkname);
/* FIXME: what if we have non-link object with link_name? */
/* Will link_name be free()ed? */
}
file_header->mtime = GET_OCTAL(tar.mtime);
file_header->size = GET_OCTAL(tar.size);
file_header->gid = GET_OCTAL(tar.gid);
file_header->uid = GET_OCTAL(tar.uid);
file_header->uid = strtol(tar.formated.uid, NULL, 8);
file_header->gid = strtol(tar.formated.gid, NULL, 8);
file_header->size = strtol(tar.formated.size, NULL, 8);
file_header->mtime = strtol(tar.formated.mtime, NULL, 8);
file_header->link_name = (tar.formated.linkname[0] != '\0') ?
bb_xstrdup(tar.formated.linkname) : NULL;
file_header->device = makedev(strtol(tar.formated.devmajor, NULL, 8),
strtol(tar.formated.devminor, NULL, 8));
/* Set bits 0-11 of the files mode */
file_header->mode = 07777 & GET_OCTAL(tar.mode);
file_header->name = NULL;
if (!longname && parse_names) {
/* we trash mode[0] here, it's ok */
tar.name[sizeof(tar.name)] = '\0';
if (tar.prefix[0]) {
/* and padding[0] */
tar.prefix[sizeof(tar.prefix)] = '\0';
file_header->name = concat_path_file(tar.prefix, tar.name);
} else
file_header->name = xstrdup(tar.name);
}
file_header->mode = 07777 & strtol(tar.formated.mode, NULL, 8);
/* Set bits 12-15 of the files mode */
/* (typeflag was not trashed because chksum does not use getOctal) */
switch (tar.typeflag) {
switch (tar.formated.typeflag) {
/* busybox identifies hard links as being regular files with 0 size and a link name */
case '1':
file_header->mode |= S_IFREG;
break;
case '7':
/* case 0: */
/* Reserved for high performance files, treat as normal file */
case 0:
case '0':
#if ENABLE_FEATURE_TAR_OLDGNU_COMPATIBILITY
#ifdef CONFIG_FEATURE_TAR_OLDGNU_COMPATIBILITY
if (last_char_is(file_header->name, '/')) {
file_header->mode |= S_IFDIR;
} else
#endif
file_header->mode |= S_IFREG;
file_header->mode |= S_IFREG;
break;
case '2':
file_header->mode |= S_IFLNK;
@@ -193,85 +162,54 @@ char get_header_tar(archive_handle_t *archive_handle)
case '6':
file_header->mode |= S_IFIFO;
break;
#if ENABLE_FEATURE_TAR_GNU_EXTENSIONS
case 'L':
/* free: paranoia: tar with several consecutive longnames */
free(longname);
/* For paranoia reasons we allocate extra NUL char */
longname = xzalloc(file_header->size + 1);
/* We read ASCIZ string, including NUL */
xread(archive_handle->src_fd, longname, file_header->size);
archive_handle->offset += file_header->size;
/* return get_header_tar(archive_handle); */
/* gcc 4.1.1 didn't optimize it into jump */
/* so we will do it ourself, this also saves stack */
goto again;
case 'K':
free(linkname);
linkname = xzalloc(file_header->size + 1);
xread(archive_handle->src_fd, linkname, file_header->size);
archive_handle->offset += file_header->size;
/* return get_header_tar(archive_handle); */
goto again;
#ifdef CONFIG_FEATURE_TAR_GNU_EXTENSIONS
case 'L': {
longname = xzalloc(file_header->size + 1);
archive_xread_all(archive_handle, longname, file_header->size);
archive_handle->offset += file_header->size;
return(get_header_tar(archive_handle));
}
case 'K': {
linkname = xzalloc(file_header->size + 1);
archive_xread_all(archive_handle, linkname, file_header->size);
archive_handle->offset += file_header->size;
file_header->name = linkname;
return(get_header_tar(archive_handle));
}
case 'D': /* GNU dump dir */
case 'M': /* Continuation of multi volume archive */
case 'M': /* Continuation of multi volume archive*/
case 'N': /* Old GNU for names > 100 characters */
case 'S': /* Sparse file */
case 'V': /* Volume header */
#endif
case 'g': /* pax global header */
case 'x': { /* pax extended header */
off_t sz;
bb_error_msg("warning: skipping header '%c'", tar.typeflag);
sz = (file_header->size + 511) & ~(off_t)511;
archive_handle->offset += sz;
sz >>= 9; /* sz /= 512 but w/o contortions for signed div */
while (sz--)
xread(archive_handle->src_fd, &tar, 512);
/* return get_header_tar(archive_handle); */
goto again_after_align;
}
case 'x': /* pax extended header */
bb_error_msg("Ignoring extension type %c", tar.formated.typeflag);
break;
default:
bb_error_msg_and_die("unknown typeflag: 0x%x", tar.typeflag);
bb_error_msg("Unknown typeflag: 0x%x", tar.formated.typeflag);
}
#if ENABLE_FEATURE_TAR_GNU_EXTENSIONS
if (longname) {
file_header->name = longname;
longname = NULL;
{ /* Strip trailing '/' in directories */
/* Must be done after mode is set as '/' is used to check if its a directory */
char *tmp = last_char_is(file_header->name, '/');
if (tmp) {
*tmp = '\0';
}
}
if (linkname) {
file_header->link_name = linkname;
linkname = NULL;
}
#endif
if (!strncmp(file_header->name, "/../"+1, 3)
|| strstr(file_header->name, "/../")
) {
bb_error_msg_and_die("name with '..' encountered: '%s'",
file_header->name);
}
/* Strip trailing '/' in directories */
/* Must be done after mode is set as '/' is used to check if it's a directory */
cp = last_char_is(file_header->name, '/');
if (archive_handle->filter(archive_handle) == EXIT_SUCCESS) {
archive_handle->action_header(archive_handle->file_header);
/* Note that we kill the '/' only after action_header() */
/* (like GNU tar 1.15.1: verbose mode outputs "dir/dir/") */
if (cp) *cp = '\0';
archive_handle->flags |= ARCHIVE_EXTRACT_QUIET;
archive_handle->action_data(archive_handle);
llist_add_to(&(archive_handle->passed), file_header->name);
} else {
data_skip(archive_handle);
free(file_header->name);
}
archive_handle->offset += file_header->size;
free(file_header->link_name);
/* Do not free(file_header->name)! */
return EXIT_SUCCESS;
return(EXIT_SUCCESS);
}
+11 -4
View File
@@ -3,18 +3,25 @@
* Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
*/
#include <sys/types.h>
#include <sys/wait.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "libbb.h"
#include "unarchive.h"
char get_header_tar_bz2(archive_handle_t *archive_handle)
{
/* Can't lseek over pipes */
archive_handle->seek = seek_by_read;
/* Cant lseek over pipe's */
archive_handle->seek = seek_by_char;
archive_handle->src_fd = open_transformer(archive_handle->src_fd, uncompressStream);
archive_handle->offset = 0;
while (get_header_tar(archive_handle) == EXIT_SUCCESS) /**/;
while (get_header_tar(archive_handle) == EXIT_SUCCESS);
/* Can only do one file at a time */
return EXIT_FAILURE;
return(EXIT_FAILURE);
}
+5 -5
View File
@@ -12,20 +12,20 @@ char get_header_tar_gz(archive_handle_t *archive_handle)
{
unsigned char magic[2];
/* Can't lseek over pipes */
archive_handle->seek = seek_by_read;
/* Cant lseek over pipe's */
archive_handle->seek = seek_by_char;
xread(archive_handle->src_fd, &magic, 2);
if ((magic[0] != 0x1f) || (magic[1] != 0x8b)) {
bb_error_msg_and_die("invalid gzip magic");
bb_error_msg_and_die("Invalid gzip magic");
}
check_header_gzip(archive_handle->src_fd);
archive_handle->src_fd = open_transformer(archive_handle->src_fd, inflate_gunzip);
archive_handle->offset = 0;
while (get_header_tar(archive_handle) == EXIT_SUCCESS) /**/;
while (get_header_tar(archive_handle) == EXIT_SUCCESS);
/* Can only do one file at a time */
return EXIT_FAILURE;
return(EXIT_FAILURE);
}
+3 -2
View File
@@ -11,12 +11,13 @@
char get_header_tar_lzma(archive_handle_t * archive_handle)
{
/* Can't lseek over pipes */
archive_handle->seek = seek_by_read;
archive_handle->seek = seek_by_char;
archive_handle->src_fd = open_transformer(archive_handle->src_fd, unlzma);
archive_handle->offset = 0;
while (get_header_tar(archive_handle) == EXIT_SUCCESS) /**/;
while (get_header_tar(archive_handle) == EXIT_SUCCESS);
/* Can only do one file at a time */
return EXIT_FAILURE;
}
+5 -2
View File
@@ -3,6 +3,9 @@
* Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
*/
#include <stdio.h>
#include <string.h>
#include <time.h>
#include "libbb.h"
#include "unarchive.h"
@@ -10,11 +13,11 @@ void header_verbose_list(const file_header_t *file_header)
{
struct tm *mtime = localtime(&(file_header->mtime));
printf("%s %d/%d %9"OFF_FMT"u %4u-%02u-%02u %02u:%02u:%02u %s",
printf("%s %d/%d%10u %4u-%02u-%02u %02u:%02u:%02u %s",
bb_mode_string(file_header->mode),
file_header->uid,
file_header->gid,
file_header->size,
(unsigned int) file_header->size,
1900 + mtime->tm_year,
1 + mtime->tm_mon,
mtime->tm_mday,
+5 -3
View File
@@ -3,6 +3,8 @@
* Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
*/
#include <unistd.h>
#include <string.h>
#include "libbb.h"
#include "unarchive.h"
@@ -10,13 +12,13 @@ archive_handle_t *init_handle(void)
{
archive_handle_t *archive_handle;
/* Initialize default values */
/* Initialise default values */
archive_handle = xzalloc(sizeof(archive_handle_t));
archive_handle->file_header = xzalloc(sizeof(file_header_t));
archive_handle->file_header = xmalloc(sizeof(file_header_t));
archive_handle->action_header = header_skip;
archive_handle->action_data = data_skip;
archive_handle->filter = filter_accept_all;
archive_handle->seek = seek_by_jump;
return archive_handle;
return(archive_handle);
}
+9 -11
View File
@@ -11,34 +11,32 @@
#include "unarchive.h"
/* transformer(), more than meets the eye */
int open_transformer(int src_fd,
USE_DESKTOP(long long) int (*transformer)(int src_fd, int dst_fd))
int open_transformer(int src_fd, int (*transformer)(int src_fd, int dst_fd))
{
int fd_pipe[2];
int pid;
if (pipe(fd_pipe) != 0) {
bb_perror_msg_and_die("can't create pipe");
bb_perror_msg_and_die("Can't create pipe");
}
pid = fork();
if (pid == -1) {
bb_perror_msg_and_die("fork failed");
bb_perror_msg_and_die("Fork failed");
}
if (pid == 0) {
/* child process */
close(fd_pipe[0]); /* We don't wan't to read from the parent */
// FIXME: error check?
transformer(src_fd, fd_pipe[1]);
close(fd_pipe[1]); /* Send EOF */
close(fd_pipe[0]); /* We don't wan't to read from the parent */
transformer(src_fd, fd_pipe[1]);
close(fd_pipe[1]); /* Send EOF */
close(src_fd);
exit(0);
/* notreached */
exit(0);
/* notreached */
}
/* parent process */
close(fd_pipe[1]); /* Don't want to write to the child */
return fd_pipe[0];
return(fd_pipe[0]);
}
@@ -8,11 +8,16 @@
#include "unarchive.h"
#include "libbb.h"
/* If we are reading through a pipe(), or from stdin then we can't lseek,
/* If we are reading through a pipe(), or from stdin then we cant lseek,
* we must read and discard the data to skip over it.
*
* TODO: rename to seek_by_read
*/
void seek_by_read(const archive_handle_t *archive_handle, const unsigned int jump_size)
void seek_by_char(const archive_handle_t *archive_handle, const unsigned int jump_size)
{
if (jump_size)
bb_copyfd_exact_size(archive_handle->src_fd, -1, jump_size);
if (jump_size) {
bb_copyfd_size(archive_handle->src_fd, -1, jump_size);
}
}
+2 -2
View File
@@ -16,9 +16,9 @@ void seek_by_jump(const archive_handle_t *archive_handle, const unsigned int amo
if (lseek(archive_handle->src_fd, (off_t) amount, SEEK_CUR) == (off_t) -1) {
#ifdef CONFIG_FEATURE_UNARCHIVE_TAPE
if (errno == ESPIPE) {
seek_by_read(archive_handle, amount);
seek_by_char(archive_handle, amount);
} else
#endif
bb_perror_msg_and_die("seek failure");
bb_perror_msg_and_die("Seek failure");
}
}
+1 -1
View File
@@ -14,7 +14,7 @@ void unpack_ar_archive(archive_handle_t *ar_archive)
xread(ar_archive->src_fd, magic, 7);
if (strncmp(magic, "!<arch>", 7) != 0) {
bb_error_msg_and_die("invalid ar magic");
bb_error_msg_and_die("Invalid ar magic");
}
ar_archive->offset += 7;
+159 -188
View File
@@ -7,47 +7,57 @@
* Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
*/
#include <stdio.h>
#include <unistd.h>
#include <signal.h>
#include <stdlib.h>
#include <fcntl.h>
#include <netinet/in.h> /* For ntohl & htonl function */
#include <string.h> /* For strncmp */
#include <sys/mman.h> /* For mmap */
#include <time.h> /* For ctime */
#include "busybox.h"
#include "unarchive.h"
#define RPM_HEADER_MAGIC "\216\255\350"
#define RPM_CHAR_TYPE 1
#define RPM_INT8_TYPE 2
#define RPM_INT16_TYPE 3
#define RPM_INT32_TYPE 4
/* #define RPM_INT64_TYPE 5 ---- These aren't supported (yet) */
#define RPM_STRING_TYPE 6
#define RPM_BIN_TYPE 7
#define RPM_STRING_ARRAY_TYPE 8
#define RPM_I18NSTRING_TYPE 9
#define RPM_HEADER_MAGIC "\216\255\350"
#define RPM_CHAR_TYPE 1
#define RPM_INT8_TYPE 2
#define RPM_INT16_TYPE 3
#define RPM_INT32_TYPE 4
/* #define RPM_INT64_TYPE 5 ---- These aren't supported (yet) */
#define RPM_STRING_TYPE 6
#define RPM_BIN_TYPE 7
#define RPM_STRING_ARRAY_TYPE 8
#define RPM_I18NSTRING_TYPE 9
#define TAG_NAME 1000
#define TAG_VERSION 1001
#define TAG_RELEASE 1002
#define TAG_SUMMARY 1004
#define TAG_DESCRIPTION 1005
#define TAG_BUILDTIME 1006
#define TAG_BUILDHOST 1007
#define TAG_SIZE 1009
#define TAG_VENDOR 1011
#define TAG_LICENSE 1014
#define TAG_PACKAGER 1015
#define TAG_GROUP 1016
#define TAG_URL 1020
#define TAG_PREIN 1023
#define TAG_POSTIN 1024
#define TAG_FILEFLAGS 1037
#define TAG_FILEUSERNAME 1039
#define TAG_FILEGROUPNAME 1040
#define TAG_SOURCERPM 1044
#define TAG_PREINPROG 1085
#define TAG_POSTINPROG 1086
#define TAG_PREFIXS 1098
#define TAG_DIRINDEXES 1116
#define TAG_BASENAMES 1117
#define TAG_DIRNAMES 1118
#define RPMFILE_CONFIG (1 << 0)
#define RPMFILE_DOC (1 << 1)
#define RPMTAG_NAME 1000
#define RPMTAG_VERSION 1001
#define RPMTAG_RELEASE 1002
#define RPMTAG_SUMMARY 1004
#define RPMTAG_DESCRIPTION 1005
#define RPMTAG_BUILDTIME 1006
#define RPMTAG_BUILDHOST 1007
#define RPMTAG_SIZE 1009
#define RPMTAG_VENDOR 1011
#define RPMTAG_LICENSE 1014
#define RPMTAG_PACKAGER 1015
#define RPMTAG_GROUP 1016
#define RPMTAG_URL 1020
#define RPMTAG_PREIN 1023
#define RPMTAG_POSTIN 1024
#define RPMTAG_FILEFLAGS 1037
#define RPMTAG_FILEUSERNAME 1039
#define RPMTAG_FILEGROUPNAME 1040
#define RPMTAG_SOURCERPM 1044
#define RPMTAG_PREINPROG 1085
#define RPMTAG_POSTINPROG 1086
#define RPMTAG_PREFIXS 1098
#define RPMTAG_DIRINDEXES 1116
#define RPMTAG_BASENAMES 1117
#define RPMTAG_DIRNAMES 1118
#define RPMFILE_CONFIG (1 << 0)
#define RPMFILE_DOC (1 << 1)
enum rpm_functions_e {
rpm_query = 1,
@@ -70,42 +80,43 @@ static void *map;
static rpm_index **mytags;
static int tagcount;
static void extract_cpio_gz(int fd);
static rpm_index **rpm_gettags(int fd, int *num_tags);
static int bsearch_rpmtag(const void *key, const void *item);
static char *rpm_getstr(int tag, int itemindex);
static int rpm_getint(int tag, int itemindex);
static int rpm_getcount(int tag);
static void fileaction_dobackup(char *filename, int fileref);
static void fileaction_setowngrp(char *filename, int fileref);
static void loop_through_files(int filetag, void (*fileaction)(char *filename, int fileref));
void extract_cpio_gz(int fd);
rpm_index **rpm_gettags(int fd, int *num_tags);
int bsearch_rpmtag(const void *key, const void *item);
char *rpm_getstring(int tag, int itemindex);
int rpm_getint(int tag, int itemindex);
int rpm_getcount(int tag);
void exec_script(int progtag, int datatag, char *prefix);
void fileaction_dobackup(char *filename, int fileref);
void fileaction_setowngrp(char *filename, int fileref);
void fileaction_list(char *filename, int itemno);
void loop_through_files(int filetag, void (*fileaction)(char *filename, int fileref));
int rpm_main(int argc, char **argv)
{
int opt = 0, func = 0, rpm_fd, offset;
const int pagesize = getpagesize();
while ((opt = getopt(argc, argv, "iqpldc")) != -1) {
switch (opt) {
case 'i': /* First arg: Install mode, with q: Information */
if (!func) func = rpm_install;
case 'i': // First arg: Install mode, with q: Information
if (!func) func |= rpm_install;
else func |= rpm_query_info;
break;
case 'q': /* First arg: Query mode */
if (func) bb_show_usage();
func = rpm_query;
case 'q': // First arg: Query mode
if (!func) func |= rpm_query;
else bb_show_usage();
break;
case 'p': /* Query a package */
case 'p': // Query a package
func |= rpm_query_package;
break;
case 'l': /* List files in a package */
case 'l': // List files in a package
func |= rpm_query_list;
break;
case 'd': /* List doc files in a package (implies list) */
case 'd': // List doc files in a package (implies list)
func |= rpm_query_list;
func |= rpm_query_list_doc;
break;
case 'c': /* List config files in a package (implies list) */
case 'c': // List config files in a package (implies list)
func |= rpm_query_list;
func |= rpm_query_list_config;
break;
@@ -113,84 +124,68 @@ int rpm_main(int argc, char **argv)
bb_show_usage();
}
}
argv += optind;
argc -= optind;
if (!argc) bb_show_usage();
while (*argv) {
rpm_fd = xopen(*argv++, O_RDONLY);
mytags = rpm_gettags(rpm_fd, &tagcount);
if (!mytags)
bb_error_msg_and_die("error reading rpm header");
offset = xlseek(rpm_fd, 0, SEEK_CUR);
/* Mimimum is one page */
map = mmap(0, offset > pagesize ? (offset + offset % pagesize) : pagesize, PROT_READ, MAP_PRIVATE, rpm_fd, 0);
if (optind == argc) bb_show_usage();
while (optind < argc) {
rpm_fd = bb_xopen(argv[optind], O_RDONLY);
mytags = rpm_gettags(rpm_fd, (int *) &tagcount);
offset = lseek(rpm_fd, 0, SEEK_CUR);
if (!mytags) { printf("Error reading rpm header\n"); exit(-1); }
map = mmap(0, offset > getpagesize() ? (offset + offset % getpagesize()) : getpagesize(), PROT_READ, MAP_PRIVATE, rpm_fd, 0); // Mimimum is one page
if (func & rpm_install) {
/* Backup any config files */
loop_through_files(TAG_BASENAMES, fileaction_dobackup);
/* Extact the archive */
extract_cpio_gz(rpm_fd);
/* Set the correct file uid/gid's */
loop_through_files(TAG_BASENAMES, fileaction_setowngrp);
}
else if ((func & (rpm_query|rpm_query_package)) == (rpm_query|rpm_query_package)) {
if (!(func & (rpm_query_info|rpm_query_list))) {
/* If just a straight query, just give package name */
printf("%s-%s-%s\n", rpm_getstr(TAG_NAME, 0), rpm_getstr(TAG_VERSION, 0), rpm_getstr(TAG_RELEASE, 0));
loop_through_files(RPMTAG_BASENAMES, fileaction_dobackup); /* Backup any config files */
extract_cpio_gz(rpm_fd); // Extact the archive
loop_through_files(RPMTAG_BASENAMES, fileaction_setowngrp); /* Set the correct file uid/gid's */
} else if (func & rpm_query && func & rpm_query_package) {
if (!((func & rpm_query_info) || (func & rpm_query_list))) { // If just a straight query, just give package name
printf("%s-%s-%s\n", rpm_getstring(RPMTAG_NAME, 0), rpm_getstring(RPMTAG_VERSION, 0), rpm_getstring(RPMTAG_RELEASE, 0));
}
if (func & rpm_query_info) {
/* Do the nice printout */
time_t bdate_time;
struct tm *bdate;
char bdatestring[50];
printf("Name : %-29sRelocations: %s\n", rpm_getstr(TAG_NAME, 0), rpm_getstr(TAG_PREFIXS, 0) ? rpm_getstr(TAG_PREFIXS, 0) : "(not relocateable)");
printf("Version : %-34sVendor: %s\n", rpm_getstr(TAG_VERSION, 0), rpm_getstr(TAG_VENDOR, 0) ? rpm_getstr(TAG_VENDOR, 0) : "(none)");
bdate_time = rpm_getint(TAG_BUILDTIME, 0);
printf("Name : %-29sRelocations: %s\n", rpm_getstring(RPMTAG_NAME, 0), rpm_getstring(RPMTAG_PREFIXS, 0) ? rpm_getstring(RPMTAG_PREFIXS, 0) : "(not relocateable)");
printf("Version : %-34sVendor: %s\n", rpm_getstring(RPMTAG_VERSION, 0), rpm_getstring(RPMTAG_VENDOR, 0) ? rpm_getstring(RPMTAG_VENDOR, 0) : "(none)");
bdate_time = rpm_getint(RPMTAG_BUILDTIME, 0);
bdate = localtime((time_t *) &bdate_time);
strftime(bdatestring, 50, "%a %d %b %Y %T %Z", bdate);
printf("Release : %-30sBuild Date: %s\n", rpm_getstr(TAG_RELEASE, 0), bdatestring);
printf("Install date: %-30sBuild Host: %s\n", "(not installed)", rpm_getstr(TAG_BUILDHOST, 0));
printf("Group : %-30sSource RPM: %s\n", rpm_getstr(TAG_GROUP, 0), rpm_getstr(TAG_SOURCERPM, 0));
printf("Size : %-33dLicense: %s\n", rpm_getint(TAG_SIZE, 0), rpm_getstr(TAG_LICENSE, 0));
printf("URL : %s\n", rpm_getstr(TAG_URL, 0));
printf("Summary : %s\n", rpm_getstr(TAG_SUMMARY, 0));
printf("Description :\n%s\n", rpm_getstr(TAG_DESCRIPTION, 0));
printf("Release : %-30sBuild Date: %s\n", rpm_getstring(RPMTAG_RELEASE, 0), bdatestring);
printf("Install date: %-30sBuild Host: %s\n", "(not installed)", rpm_getstring(RPMTAG_BUILDHOST, 0));
printf("Group : %-30sSource RPM: %s\n", rpm_getstring(RPMTAG_GROUP, 0), rpm_getstring(RPMTAG_SOURCERPM, 0));
printf("Size : %-33dLicense: %s\n", rpm_getint(RPMTAG_SIZE, 0), rpm_getstring(RPMTAG_LICENSE, 0));
printf("URL : %s\n", rpm_getstring(RPMTAG_URL, 0));
printf("Summary : %s\n", rpm_getstring(RPMTAG_SUMMARY, 0));
printf("Description :\n%s\n", rpm_getstring(RPMTAG_DESCRIPTION, 0));
}
if (func & rpm_query_list) {
int count, it, flags;
count = rpm_getcount(TAG_BASENAMES);
count = rpm_getcount(RPMTAG_BASENAMES);
for (it = 0; it < count; it++) {
flags = rpm_getint(TAG_FILEFLAGS, it);
switch (func & (rpm_query_list_doc|rpm_query_list_config)) {
case rpm_query_list_doc:
if (!(flags & RPMFILE_DOC)) continue;
break;
case rpm_query_list_config:
if (!(flags & RPMFILE_CONFIG)) continue;
break;
case rpm_query_list_doc|rpm_query_list_config:
if (!(flags & (RPMFILE_CONFIG|RPMFILE_DOC))) continue;
break;
flags = rpm_getint(RPMTAG_FILEFLAGS, it);
switch ((func & rpm_query_list_doc) + (func & rpm_query_list_config))
{
case rpm_query_list_doc: if (!(flags & RPMFILE_DOC)) continue; break;
case rpm_query_list_config: if (!(flags & RPMFILE_CONFIG)) continue; break;
case rpm_query_list_doc + rpm_query_list_config: if (!((flags & RPMFILE_CONFIG) || (flags & RPMFILE_DOC))) continue; break;
}
printf("%s%s\n",
rpm_getstr(TAG_DIRNAMES, rpm_getint(TAG_DIRINDEXES, it)),
rpm_getstr(TAG_BASENAMES, it));
printf("%s%s\n", rpm_getstring(RPMTAG_DIRNAMES, rpm_getint(RPMTAG_DIRINDEXES, it)), rpm_getstring(RPMTAG_BASENAMES, it));
}
}
}
free(mytags);
optind++;
free (mytags);
}
return 0;
}
static void extract_cpio_gz(int fd) {
void extract_cpio_gz(int fd) {
archive_handle_t *archive_handle;
unsigned char magic[2];
/* Initialise */
archive_handle = init_handle();
archive_handle->seek = seek_by_read;
archive_handle->seek = seek_by_char;
//archive_handle->action_header = header_list;
archive_handle->action_data = data_extract_all;
archive_handle->flags |= ARCHIVE_PRESERVE_DATE;
@@ -200,28 +195,24 @@ static void extract_cpio_gz(int fd) {
xread(archive_handle->src_fd, &magic, 2);
if ((magic[0] != 0x1f) || (magic[1] != 0x8b)) {
bb_error_msg_and_die("invalid gzip magic");
bb_error_msg_and_die("Invalid gzip magic");
}
check_header_gzip(archive_handle->src_fd);
xchdir("/"); /* Install RPM's to root */
bb_xchdir("/"); // Install RPM's to root
archive_handle->src_fd = open_transformer(archive_handle->src_fd, inflate_gunzip);
archive_handle->offset = 0;
while (get_header_cpio(archive_handle) == EXIT_SUCCESS)
/* loop */;
while (get_header_cpio(archive_handle) == EXIT_SUCCESS);
}
static rpm_index **rpm_gettags(int fd, int *num_tags)
rpm_index **rpm_gettags(int fd, int *num_tags)
{
/* We should never need mode than 200, and realloc later */
rpm_index **tags = xzalloc(200 * sizeof(struct rpmtag *));
rpm_index **tags = xzalloc(200 * sizeof(struct rpmtag *)); /* We should never need mode than 200, and realloc later */
int pass, tagindex = 0;
lseek(fd, 96, SEEK_CUR); /* Seek past the unused lead */
xlseek(fd, 96, SEEK_CUR); /* Seek past the unused lead */
/* 1st pass is the signature headers, 2nd is the main stuff */
for (pass = 0; pass < 2; pass++) {
for (pass = 0; pass < 2; pass++) { /* 1st pass is the signature headers, 2nd is the main stuff */
struct {
char magic[3]; /* 3 byte magic: 0x8e 0xad 0xe8 */
uint8_t version; /* 1 byte version number */
@@ -232,112 +223,87 @@ static rpm_index **rpm_gettags(int fd, int *num_tags)
rpm_index *tmpindex;
int storepos;
xread(fd, &header, sizeof(header));
if (strncmp((char *) &header.magic, RPM_HEADER_MAGIC, 3) != 0)
return NULL; /* Invalid magic */
if (header.version != 1)
return NULL; /* This program only supports v1 headers */
read(fd, &header, sizeof(header));
if (strncmp((char *) &header.magic, RPM_HEADER_MAGIC, 3) != 0) return NULL; /* Invalid magic */
if (header.version != 1) return NULL; /* This program only supports v1 headers */
header.size = ntohl(header.size);
header.entries = ntohl(header.entries);
storepos = xlseek(fd,0,SEEK_CUR) + header.entries * 16;
storepos = lseek(fd,0,SEEK_CUR) + header.entries * 16;
while (header.entries--) {
tmpindex = tags[tagindex++] = xmalloc(sizeof(rpm_index));
xread(fd, tmpindex, sizeof(rpm_index));
tmpindex->tag = ntohl(tmpindex->tag);
tmpindex->type = ntohl(tmpindex->type);
tmpindex->count = ntohl(tmpindex->count);
read(fd, tmpindex, sizeof(rpm_index));
tmpindex->tag = ntohl(tmpindex->tag); tmpindex->type = ntohl(tmpindex->type); tmpindex->count = ntohl(tmpindex->count);
tmpindex->offset = storepos + ntohl(tmpindex->offset);
if (pass==0)
tmpindex->tag -= 743;
if (pass==0) tmpindex->tag -= 743;
}
xlseek(fd, header.size, SEEK_CUR); /* Seek past store */
/* Skip padding to 8 byte boundary after reading signature headers */
if (pass==0)
xlseek(fd, (8 - (xlseek(fd,0,SEEK_CUR) % 8)) % 8, SEEK_CUR);
lseek(fd, header.size, SEEK_CUR); /* Seek past store */
if (pass==0) lseek(fd, (8 - (lseek(fd,0,SEEK_CUR) % 8)) % 8, SEEK_CUR); /* Skip padding to 8 byte boundary after reading signature headers */
}
tags = xrealloc(tags, tagindex * sizeof(struct rpmtag *)); /* realloc tags to save space */
tags = realloc(tags, tagindex * sizeof(struct rpmtag *)); /* realloc tags to save space */
*num_tags = tagindex;
return tags; /* All done, leave the file at the start of the gzipped cpio archive */
}
static int bsearch_rpmtag(const void *key, const void *item)
int bsearch_rpmtag(const void *key, const void *item)
{
int *tag = (int *)key;
rpm_index **tmp = (rpm_index **) item;
return (*tag - tmp[0]->tag);
}
static int rpm_getcount(int tag)
int rpm_getcount(int tag)
{
rpm_index **found;
found = bsearch(&tag, mytags, tagcount, sizeof(struct rpmtag *), bsearch_rpmtag);
if (!found)
return 0;
return found[0]->count;
if (!found) return 0;
else return found[0]->count;
}
static char *rpm_getstr(int tag, int itemindex)
char *rpm_getstring(int tag, int itemindex)
{
rpm_index **found;
found = bsearch(&tag, mytags, tagcount, sizeof(struct rpmtag *), bsearch_rpmtag);
if (!found || itemindex >= found[0]->count)
return NULL;
if (!found || itemindex >= found[0]->count) return NULL;
if (found[0]->type == RPM_STRING_TYPE || found[0]->type == RPM_I18NSTRING_TYPE || found[0]->type == RPM_STRING_ARRAY_TYPE) {
int n;
char *tmpstr = (char *) (map + found[0]->offset);
for (n=0; n < itemindex; n++)
tmpstr = tmpstr + strlen(tmpstr) + 1;
for (n=0; n < itemindex; n++) tmpstr = tmpstr + strlen(tmpstr) + 1;
return tmpstr;
}
return NULL;
} else return NULL;
}
static int rpm_getint(int tag, int itemindex)
int rpm_getint(int tag, int itemindex)
{
rpm_index **found;
int *tmpint; /* NB: using int8_t* would be easier to code */
int n, *tmpint;
/* gcc throws warnings here when sizeof(void*)!=sizeof(int) ...
* it's ok to ignore it because tag won't be used as a pointer */
found = bsearch(&tag, mytags, tagcount, sizeof(struct rpmtag *), bsearch_rpmtag);
if (!found || itemindex >= found[0]->count)
return -1;
if (!found || itemindex >= found[0]->count) return -1;
tmpint = (int *) (map + found[0]->offset);
if (found[0]->type == RPM_INT32_TYPE) {
tmpint = (int *) ((char *) tmpint + itemindex*4);
/*return ntohl(*tmpint);*/
/* int can be != int32_t */
return ntohl(*(int32_t*)tmpint);
}
if (found[0]->type == RPM_INT16_TYPE) {
tmpint = (int *) ((char *) tmpint + itemindex*2);
/* ??? read int, and THEN ntohs() it?? */
/*return ntohs(*tmpint);*/
return ntohs(*(int16_t*)tmpint);
}
if (found[0]->type == RPM_INT8_TYPE) {
tmpint = (int *) ((char *) tmpint + itemindex);
/* ??? why we don't read byte here??? */
/*return ntohs(*tmpint);*/
return *(int8_t*)tmpint;
}
return -1;
for (n=0; n<itemindex; n++) tmpint = (int *) ((void *) tmpint + 4);
return ntohl(*tmpint);
} else if (found[0]->type == RPM_INT16_TYPE) {
for (n=0; n<itemindex; n++) tmpint = (int *) ((void *) tmpint + 2);
return ntohs(*tmpint);
} else if (found[0]->type == RPM_INT8_TYPE) {
for (n=0; n<itemindex; n++) tmpint = (int *) ((void *) tmpint + 1);
return ntohs(*tmpint);
} else return -1;
}
static void fileaction_dobackup(char *filename, int fileref)
void fileaction_dobackup(char *filename, int fileref)
{
struct stat oldfile;
int stat_res;
char *newname;
if (rpm_getint(TAG_FILEFLAGS, fileref) & RPMFILE_CONFIG) {
/* Only need to backup config files */
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 */
newname = xasprintf("%s.rpmorig", filename);
if (rpm_getint(RPMTAG_FILEFLAGS, fileref) & RPMFILE_CONFIG) { /* Only need to backup config files */
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 */
newname = bb_xstrdup(filename);
newname = strcat(newname, ".rpmorig");
copy_file(filename, newname, FILEUTILS_RECUR | FILEUTILS_PRESERVE_STATUS);
remove_file(filename, FILEUTILS_RECUR | FILEUTILS_FORCE);
free(newname);
@@ -345,21 +311,26 @@ static void fileaction_dobackup(char *filename, int fileref)
}
}
static void fileaction_setowngrp(char *filename, int fileref)
void fileaction_setowngrp(char *filename, int fileref)
{
int uid, gid;
uid = xuname2uid(rpm_getstr(TAG_FILEUSERNAME, fileref));
gid = xgroup2gid(rpm_getstr(TAG_FILEGROUPNAME, fileref));
chown(filename, uid, gid);
uid = bb_xgetpwnam(rpm_getstring(RPMTAG_FILEUSERNAME, fileref));
gid = bb_xgetgrnam(rpm_getstring(RPMTAG_FILEGROUPNAME, fileref));
chown (filename, uid, gid);
}
static void loop_through_files(int filetag, void (*fileaction)(char *filename, int fileref))
void fileaction_list(char *filename, int ATTRIBUTE_UNUSED fileref)
{
printf("%s\n", filename);
}
void loop_through_files(int filetag, void (*fileaction)(char *filename, int fileref))
{
int count = 0;
while (rpm_getstr(filetag, count)) {
char* filename = xasprintf("%s%s",
rpm_getstr(TAG_DIRNAMES, rpm_getint(TAG_DIRINDEXES, count)),
rpm_getstr(TAG_BASENAMES, count));
while (rpm_getstring(filetag, count)) {
char * filename = bb_xasprintf("%s%s",
rpm_getstring(RPMTAG_DIRNAMES, rpm_getint(RPMTAG_DIRINDEXES,
count)), rpm_getstring(RPMTAG_BASENAMES, count));
fileaction(filename, count++);
free(filename);
}
+12 -7
View File
@@ -6,6 +6,11 @@
*
* Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
*/
#include <sys/types.h>
#include <netinet/in.h> /* For ntohl & htonl function */
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include "busybox.h"
#include "unarchive.h"
@@ -37,10 +42,10 @@ static void skip_header(int rpm_fd)
xread(rpm_fd, &header, sizeof(struct rpm_header));
if (strncmp((char *) &header.magic, RPM_HEADER_MAGIC, 3) != 0) {
bb_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) {
bb_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.size = ntohl(header.size);
@@ -58,12 +63,12 @@ int rpm2cpio_main(int argc, char **argv)
if (argc == 1) {
rpm_fd = STDIN_FILENO;
} else {
rpm_fd = xopen(argv[1], O_RDONLY);
rpm_fd = bb_xopen(argv[1], O_RDONLY);
}
xread(rpm_fd, &lead, sizeof(struct rpm_lead));
if (strncmp((char *) &lead.magic, RPM_MAGIC, 4) != 0) {
bb_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 */
@@ -75,12 +80,12 @@ int rpm2cpio_main(int argc, char **argv)
xread(rpm_fd, &magic, 2);
if ((magic[0] != 0x1f) || (magic[1] != 0x8b)) {
bb_error_msg_and_die("invalid gzip magic");
bb_error_msg_and_die("Invalid gzip magic");
}
check_header_gzip(rpm_fd);
if (inflate_gunzip(rpm_fd, STDOUT_FILENO) < 0) {
bb_error_msg("error inflating");
if (inflate_gunzip(rpm_fd, STDOUT_FILENO) != 0) {
bb_error_msg("Error inflating");
}
close(rpm_fd);
+389 -455
View File
File diff suppressed because it is too large. Load diff
+17 -11
View File
@@ -5,6 +5,13 @@
* Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
*/
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include "busybox.h"
#include "unarchive.h"
@@ -16,20 +23,20 @@ int uncompress_main(int argc, char **argv)
int status = EXIT_SUCCESS;
unsigned long flags;
flags = getopt32(argc, argv, "cf");
flags = bb_getopt_ulflags(argc, argv, "cf");
while (optind < argc) {
char *compressed_file = argv[optind++];
char *delete_path = NULL;
const char *compressed_file = argv[optind++];
const char *delete_path = NULL;
char *uncompressed_file = NULL;
int src_fd;
int dst_fd;
if (LONE_DASH(compressed_file)) {
if (strcmp(compressed_file, "-") == 0) {
src_fd = STDIN_FILENO;
flags |= GUNZIP_TO_STDOUT;
} else {
src_fd = xopen(compressed_file, O_RDONLY);
src_fd = bb_xopen(compressed_file, O_RDONLY);
}
/* Check that the input is sane. */
@@ -45,18 +52,17 @@ int uncompress_main(int argc, char **argv)
struct stat stat_buf;
char *extension;
uncompressed_file = xstrdup(compressed_file);
uncompressed_file = bb_xstrdup(compressed_file);
extension = strrchr(uncompressed_file, '.');
if (!extension || (strcmp(extension, ".Z") != 0)) {
bb_error_msg_and_die("invalid extension");
bb_error_msg_and_die("Invalid extension");
}
*extension = '\0';
/* Open output file */
xstat(compressed_file, &stat_buf);
dst_fd = xopen3(uncompressed_file,
O_WRONLY | O_CREAT | O_TRUNC,
dst_fd = bb_xopen3(uncompressed_file, O_WRONLY | O_CREAT,
stat_buf.st_mode);
/* If unzip succeeds remove the old file */
@@ -65,7 +71,7 @@ int uncompress_main(int argc, char **argv)
/* do the decompression, and cleanup */
if ((xread_char(src_fd) != 0x1f) || (xread_char(src_fd) != 0x9d)) {
bb_error_msg_and_die("invalid magic");
bb_error_msg_and_die("Invalid magic");
}
status = uncompress(src_fd, dst_fd);
@@ -84,7 +90,7 @@ int uncompress_main(int argc, char **argv)
/* delete_path will be NULL if in test mode or from stdin */
if (delete_path && (unlink(delete_path) == -1)) {
bb_error_msg_and_die("cannot remove %s", delete_path);
bb_error_msg_and_die("Couldn't remove %s", delete_path);
}
free(uncompressed_file);
+21 -18
View File
@@ -8,7 +8,11 @@
* Licensed under GPL v2, see file LICENSE in this tarball for details.
*/
/* Why our g[un]zip/bunzip2 are so ugly compared to this beauty? */
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "busybox.h"
#include "unarchive.h"
@@ -17,48 +21,47 @@
int unlzma_main(int argc, char **argv)
{
USE_DESKTOP(long long) int status;
char *filename;
unsigned opt;
int src_fd, dst_fd;
unsigned long opt;
int status, src_fd, dst_fd;
opt = getopt32(argc, argv, "c");
opt = bb_getopt_ulflags(argc, argv, "c");
/* Set input filename and number */
filename = argv[optind];
if (filename && NOT_LONE_DASH(filename)) {
if ((filename) && (filename[0] != '-') && (filename[1] != '\0')) {
/* Open input file */
src_fd = xopen(filename, O_RDONLY);
src_fd = bb_xopen(filename, O_RDONLY);
} else {
src_fd = STDIN_FILENO;
filename = 0;
}
/* if called as lzmacat force the stdout flag */
if ((opt & UNLZMA_OPT_STDOUT) || applet_name[4] == 'c')
if ((opt & UNLZMA_OPT_STDOUT) || bb_applet_name[4] == 'c')
filename = 0;
if (filename) {
struct stat stat_buf;
/* bug: char *extension = filename + strlen(filename) - 5; */
char *extension = strrchr(filename, '.');
if (!extension || strcmp(extension, ".lzma") != 0) {
bb_error_msg_and_die("invalid extension");
char *extension = filename + strlen(filename) - 5;
if (strcmp(extension, ".lzma") != 0) {
bb_error_msg_and_die("Invalid extension");
}
xstat(filename, &stat_buf);
*extension = '\0';
dst_fd = xopen3(filename, O_WRONLY | O_CREAT | O_TRUNC,
stat_buf.st_mode);
*extension = 0;
dst_fd = bb_xopen3(filename, O_WRONLY | O_CREAT, stat_buf.st_mode);
} else
dst_fd = STDOUT_FILENO;
status = unlzma(src_fd, dst_fd);
if (filename) {
if (status >= 0) /* if success delete src, else delete dst */
if (!status)
filename[strlen(filename)] = '.';
if (unlink(filename) < 0) {
bb_error_msg_and_die("cannot remove %s", filename);
bb_error_msg_and_die("Couldn't remove %s", filename);
}
}
return (status < 0);
return status;
}
+74 -58
View File
@@ -24,14 +24,22 @@
* - central directory
*/
#include "busybox.h"
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include "unarchive.h"
#include "busybox.h"
#define ZIP_FILEHEADER_MAGIC SWAP_LE32(0x04034b50)
#define ZIP_CDS_MAGIC SWAP_LE32(0x02014b50)
#define ZIP_CDS_END_MAGIC SWAP_LE32(0x06054b50)
#define ZIP_DD_MAGIC SWAP_LE32(0x08074b50)
extern unsigned int gunzip_crc;
extern unsigned int gunzip_bytes_out;
typedef union {
unsigned char raw[26];
struct {
@@ -45,48 +53,50 @@ typedef union {
unsigned int ucmpsize ATTRIBUTE_PACKED; /* 18-21 */
unsigned short filename_len; /* 22-23 */
unsigned short extra_len; /* 24-25 */
} formatted ATTRIBUTE_PACKED;
} formated ATTRIBUTE_PACKED;
} zip_header_t;
static void unzip_skip(int fd, off_t skip)
{
if (lseek(fd, skip, SEEK_CUR) == (off_t)-1) {
if (errno != ESPIPE)
bb_error_msg_and_die("seek failure");
bb_copyfd_exact_size(fd, -1, skip);
if ((errno != ESPIPE) || (bb_copyfd_size(fd, -1, skip) != skip)) {
bb_error_msg_and_die("Seek failure");
}
}
}
static void unzip_create_leading_dirs(char *fn)
{
/* Create all leading directories */
char *name = xstrdup(fn);
char *name = bb_xstrdup(fn);
if (bb_make_directory(dirname(name), 0777, FILEUTILS_RECUR)) {
bb_error_msg_and_die("exiting"); /* bb_make_directory is noisy */
bb_error_msg_and_die("Exiting"); /* bb_make_directory is noisy */
}
free(name);
}
static int unzip_extract(zip_header_t *zip_header, int src_fd, int dst_fd)
{
if (zip_header->formatted.method == 0) {
if (zip_header->formated.method == 0) {
/* Method 0 - stored (not compressed) */
off_t size = zip_header->formatted.ucmpsize;
if (size)
bb_copyfd_exact_size(src_fd, dst_fd, size);
int size = zip_header->formated.ucmpsize;
if (size && (bb_copyfd_size(src_fd, dst_fd, size) != size)) {
bb_error_msg_and_die("Cannot complete extraction");
}
} else {
/* Method 8 - inflate */
inflate_unzip_result res;
/* err = */ inflate_unzip(&res, zip_header->formatted.cmpsize, src_fd, dst_fd);
// we should check for -1 error return
inflate_init(zip_header->formated.cmpsize);
inflate_unzip(src_fd, dst_fd);
inflate_cleanup();
/* Validate decompression - crc */
if (zip_header->formatted.crc32 != (res.crc ^ 0xffffffffL)) {
bb_error_msg("invalid compressed data--%s error", "crc");
if (zip_header->formated.crc32 != (gunzip_crc ^ 0xffffffffL)) {
bb_error_msg("Invalid compressed data--crc error");
return 1;
}
/* Validate decompression - size */
if (zip_header->formatted.ucmpsize != res.bytes_out) {
bb_error_msg("invalid compressed data--%s error", "length");
if (zip_header->formated.ucmpsize != gunzip_bytes_out) {
bb_error_msg("Invalid compressed data--length error");
return 1;
}
}
@@ -109,10 +119,10 @@ int unzip_main(int argc, char **argv)
char key_buf[512];
struct stat stat_buf;
while ((opt = getopt(argc, argv, "-d:lnopqx")) != -1) {
switch (opt_range) {
while((opt = getopt(argc, argv, "-d:lnopqx")) != -1) {
switch(opt_range) {
case 0: /* Options */
switch (opt) {
switch(opt) {
case 'l': /* List */
verbosity = v_list;
break;
@@ -133,7 +143,7 @@ int unzip_main(int argc, char **argv)
break;
case 1 : /* The zip file */
src_fn = xstrndup(optarg, strlen(optarg)+4);
src_fn = bb_xstrndup(optarg, strlen(optarg)+4);
opt_range++;
break;
@@ -182,26 +192,27 @@ int unzip_main(int argc, char **argv)
}
/* Open input file */
if (LONE_DASH(src_fn)) {
if (strcmp("-", src_fn) == 0) {
src_fd = STDIN_FILENO;
/* Cannot use prompt mode since zip data is arriving on STDIN */
overwrite = (overwrite == o_prompt) ? o_never : overwrite;
} else {
static const char *const extn[] = {"", ".zip", ".ZIP"};
int orig_src_fn_len = strlen(src_fn);
for (i = 0; (i < 3) && (src_fd == -1); i++) {
for(i = 0; (i < 3) && (src_fd == -1); i++) {
strcpy(src_fn + orig_src_fn_len, extn[i]);
src_fd = open(src_fn, O_RDONLY);
}
if (src_fd == -1) {
src_fn[orig_src_fn_len] = 0;
bb_error_msg_and_die("cannot open %s, %s.zip, %s.ZIP", src_fn, src_fn, src_fn);
bb_error_msg_and_die("Cannot open %s, %s.zip, %s.ZIP", src_fn, src_fn, src_fn);
}
}
/* Change dir if necessary */
if (base_dir)
xchdir(base_dir);
bb_xchdir(base_dir);
if (verbosity != v_silent)
printf("Archive: %s\n", src_fn);
@@ -216,36 +227,36 @@ int unzip_main(int argc, char **argv)
if (magic == ZIP_CDS_MAGIC) {
break;
} else if (magic != ZIP_FILEHEADER_MAGIC) {
bb_error_msg_and_die("invalid zip magic %08X", magic);
bb_error_msg_and_die("Invalid zip magic %08X", magic);
}
/* Read the file header */
xread(src_fd, zip_header.raw, 26);
zip_header.formatted.version = SWAP_LE32(zip_header.formatted.version);
zip_header.formatted.flags = SWAP_LE32(zip_header.formatted.flags);
zip_header.formatted.method = SWAP_LE32(zip_header.formatted.method);
zip_header.formatted.modtime = SWAP_LE32(zip_header.formatted.modtime);
zip_header.formatted.moddate = SWAP_LE32(zip_header.formatted.moddate);
zip_header.formatted.crc32 = SWAP_LE32(zip_header.formatted.crc32);
zip_header.formatted.cmpsize = SWAP_LE32(zip_header.formatted.cmpsize);
zip_header.formatted.ucmpsize = SWAP_LE32(zip_header.formatted.ucmpsize);
zip_header.formatted.filename_len = SWAP_LE32(zip_header.formatted.filename_len);
zip_header.formatted.extra_len = SWAP_LE32(zip_header.formatted.extra_len);
if ((zip_header.formatted.method != 0) && (zip_header.formatted.method != 8)) {
bb_error_msg_and_die("unsupported compression method %d", zip_header.formatted.method);
zip_header.formated.version = SWAP_LE32(zip_header.formated.version);
zip_header.formated.flags = SWAP_LE32(zip_header.formated.flags);
zip_header.formated.method = SWAP_LE32(zip_header.formated.method);
zip_header.formated.modtime = SWAP_LE32(zip_header.formated.modtime);
zip_header.formated.moddate = SWAP_LE32(zip_header.formated.moddate);
zip_header.formated.crc32 = SWAP_LE32(zip_header.formated.crc32);
zip_header.formated.cmpsize = SWAP_LE32(zip_header.formated.cmpsize);
zip_header.formated.ucmpsize = SWAP_LE32(zip_header.formated.ucmpsize);
zip_header.formated.filename_len = SWAP_LE32(zip_header.formated.filename_len);
zip_header.formated.extra_len = SWAP_LE32(zip_header.formated.extra_len);
if ((zip_header.formated.method != 0) && (zip_header.formated.method != 8)) {
bb_error_msg_and_die("Unsupported compression method %d", zip_header.formated.method);
}
/* Read filename */
free(dst_fn);
dst_fn = xzalloc(zip_header.formatted.filename_len + 1);
xread(src_fd, dst_fn, zip_header.formatted.filename_len);
dst_fn = xzalloc(zip_header.formated.filename_len + 1);
xread(src_fd, dst_fn, zip_header.formated.filename_len);
/* Skip extra header bytes */
unzip_skip(src_fd, zip_header.formatted.extra_len);
unzip_skip(src_fd, zip_header.formated.extra_len);
if ((verbosity == v_list) && !list_header_done){
puts(" Length Date Time Name\n"
" -------- ---- ---- ----");
printf(" Length Date Time Name\n"
" -------- ---- ---- ----\n");
list_header_done = 1;
}
@@ -255,12 +266,12 @@ int unzip_main(int argc, char **argv)
i = 'n';
} else { /* Extract entry */
total_size += zip_header.formatted.ucmpsize;
total_size += zip_header.formated.ucmpsize;
if (verbosity == v_list) { /* List entry */
unsigned int dostime = zip_header.formatted.modtime | (zip_header.formatted.moddate << 16);
unsigned int dostime = zip_header.formated.modtime | (zip_header.formated.moddate << 16);
printf("%9u %02u-%02u-%02u %02u:%02u %s\n",
zip_header.formatted.ucmpsize,
zip_header.formated.ucmpsize,
(dostime & 0x01e00000) >> 21,
(dostime & 0x001f0000) >> 16,
(((dostime & 0xfe000000) >> 25) + 1980) % 100,
@@ -269,19 +280,21 @@ int unzip_main(int argc, char **argv)
dst_fn);
total_entries++;
i = 'n';
} else if (dst_fd == STDOUT_FILENO) { /* Extracting to STDOUT */
i = -1;
} else if (last_char_is(dst_fn, '/')) { /* Extract directory */
if (stat(dst_fn, &stat_buf) == -1) {
if (errno != ENOENT) {
bb_perror_msg_and_die("cannot stat '%s'",dst_fn);
bb_perror_msg_and_die("Cannot stat '%s'",dst_fn);
}
if (verbosity == v_normal) {
printf(" creating: %s\n", dst_fn);
}
unzip_create_leading_dirs(dst_fn);
if (bb_make_directory(dst_fn, 0777, 0)) {
bb_error_msg_and_die("exiting");
bb_error_msg_and_die("Exiting");
}
} else {
if (!S_ISDIR(stat_buf.st_mode)) {
@@ -291,25 +304,28 @@ int unzip_main(int argc, char **argv)
i = 'n';
} else { /* Extract file */
_check_file:
_check_file:
if (stat(dst_fn, &stat_buf) == -1) { /* File does not exist */
if (errno != ENOENT) {
bb_perror_msg_and_die("cannot stat '%s'",dst_fn);
bb_perror_msg_and_die("Cannot stat '%s'",dst_fn);
}
i = 'y';
} else { /* File already exists */
if (overwrite == o_never) {
i = 'n';
} else if (S_ISREG(stat_buf.st_mode)) { /* File is regular file */
if (overwrite == o_always) {
i = 'y';
} else {
printf("replace %s? [y]es, [n]o, [A]ll, [N]one, [r]ename: ", dst_fn);
if (!fgets(key_buf, 512, stdin)) {
bb_perror_msg_and_die("cannot read input");
bb_perror_msg_and_die("Cannot read input");
}
i = key_buf[0];
}
} else { /* File is not regular file */
bb_error_msg_and_die("'%s' exists but is not regular file",dst_fn);
}
@@ -322,13 +338,13 @@ int unzip_main(int argc, char **argv)
overwrite = o_always;
case 'y': /* Open file and fall into unzip */
unzip_create_leading_dirs(dst_fn);
dst_fd = xopen(dst_fn, O_WRONLY | O_CREAT | O_TRUNC);
dst_fd = bb_xopen(dst_fn, O_WRONLY | O_CREAT);
case -1: /* Unzip */
if (verbosity == v_normal) {
printf(" inflating: %s\n", dst_fn);
}
if (unzip_extract(&zip_header, src_fd, dst_fd)) {
failed = 1;
failed = 1;
}
if (dst_fd != STDOUT_FILENO) {
/* closing STDOUT is potentially bad for future business */
@@ -340,17 +356,17 @@ int unzip_main(int argc, char **argv)
overwrite = o_never;
case 'n':
/* Skip entry data */
unzip_skip(src_fd, zip_header.formatted.cmpsize);
unzip_skip(src_fd, zip_header.formated.cmpsize);
break;
case 'r':
/* Prompt for new name */
printf("new name: ");
if (!fgets(key_buf, 512, stdin)) {
bb_perror_msg_and_die("cannot read input");
bb_perror_msg_and_die("Cannot read input");
}
free(dst_fn);
dst_fn = xstrdup(key_buf);
dst_fn = bb_xstrdup(key_buf);
chomp(dst_fn);
goto _check_file;
@@ -360,7 +376,7 @@ int unzip_main(int argc, char **argv)
}
/* Data descriptor section */
if (zip_header.formatted.flags & 4) {
if (zip_header.formated.flags & 4) {
/* skip over duplicate crc, compressed size and uncompressed size */
unzip_skip(src_fd, 12);
}
+598
View File
@@ -0,0 +1,598 @@
Various bug fixes that apply to busybox 1.2.0, cherry-picked from the
ongoing development branch. This will form the basis for busybox 1.2.1.
I'll append fixes to this as they come up. (Check the file date, or the bug
list below.) This file is basically a concatenation of the following:
http://busybox.net/downloads/patches/svn-15575.patch
http://busybox.net/downloads/patches/svn-15653.patch
http://busybox.net/downloads/patches/svn-15656.patch
http://busybox.net/downloads/patches/svn-15658.patch
http://busybox.net/downloads/patches/svn-15659.patch
http://busybox.net/downloads/patches/svn-15660.patch
http://busybox.net/downloads/patches/svn-15670.patch
http://busybox.net/downloads/patches/svn-15698.patch
http://busybox.net/downloads/patches/svn-15700.patch
http://busybox.net/downloads/patches/svn-15702.patch
http://busybox.net/downloads/patches/svn-15705.patch
http://busybox.net/downloads/patches/svn-15727.patch
------------------------------------------------------------------------
r15575 | landley | 2006-07-01 13:19:02 -0400 (Sat, 01 Jul 2006) | 2 lines
Changed paths:
M /trunk/busybox/shell/lash.c
Patch from Shaun Jackman moving the var=value logic to where it can do some
good.
------------------------------------------------------------------------
Index: shell/lash.c
===================================================================
--- shell/lash.c (revision 15574)
+++ shell/lash.c (revision 15575)
@@ -1171,12 +1171,6 @@
{
struct built_in_command *x;
- /* Check if the command sets an environment variable. */
- if( strchr(child->argv[0], '=') != NULL ) {
- child->argv[1] = child->argv[0];
- _exit(builtin_export(child));
- }
-
/* Check if the command matches any of the non-forking builtins.
* Depending on context, this might be redundant. But it's
* easier to waste a few CPU cycles than it is to figure out
@@ -1300,6 +1294,12 @@
* is doomed to failure, and doesn't work on bash, either.
*/
if (newjob->num_progs == 1) {
+ /* Check if the command sets an environment variable. */
+ if (strchr(child->argv[0], '=') != NULL) {
+ child->argv[1] = child->argv[0];
+ return builtin_export(child);
+ }
+
for (x = bltins; x->cmd; x++) {
if (strcmp(child->argv[0], x->cmd) == 0 ) {
int rcode;
------------------------------------------------------------------------
r15653 | landley | 2006-07-05 21:09:21 -0400 (Wed, 05 Jul 2006) | 6 lines
Changed paths:
M /trunk/busybox/shell/ash.c
Bug fix from Vladimir Oleynic via Paul Fox for:
echo "+bond0" > /sys/class/net/bonding_masters
while true; do
echo hello
done
------------------------------------------------------------------------
Index: shell/ash.c
===================================================================
--- shell/ash.c (revision 15652)
+++ shell/ash.c (revision 15653)
@@ -3469,6 +3469,7 @@
flushall();
cmddone:
exitstatus |= ferror(stdout);
+ clearerr(stdout);
commandname = savecmdname;
exsig = 0;
handler = savehandler;
------------------------------------------------------------------------
r15656 | landley | 2006-07-06 12:41:56 -0400 (Thu, 06 Jul 2006) | 5 lines
Changed paths:
M /trunk/busybox/util-linux/dmesg.c
Fix three embarassing thinkos in the new dmesg.c:
1) the c argument shouldn't have had a : after that, dunno how that got there.
2) the xgetlarg for level was using size
3) because xgetlarg's error message _SUCKS_ (it does a show_usage() rather than giving any specific info about the range that was violated) I dropped the range down to 2 bytes. (Which works fine, I dunno why we were nit-picking about that...)
------------------------------------------------------------------------
Index: util-linux/dmesg.c
===================================================================
--- util-linux/dmesg.c (revision 15655)
+++ util-linux/dmesg.c (revision 15656)
@@ -15,16 +15,16 @@
int dmesg_main(int argc, char *argv[])
{
char *size, *level;
- int flags = bb_getopt_ulflags(argc, argv, "c:s:n:", &size, &level);
+ int flags = bb_getopt_ulflags(argc, argv, "cs:n:", &size, &level);
if (flags & 4) {
- if(klogctl(8, NULL, bb_xgetlarg(size, 10, 0, 10)))
+ if(klogctl(8, NULL, bb_xgetlarg(level, 10, 0, 10)))
bb_perror_msg_and_die("klogctl");
} else {
int len;
char *buf;
- len = (flags & 2) ? bb_xgetlarg(size, 10, 4096, INT_MAX) : 16384;
+ len = (flags & 2) ? bb_xgetlarg(size, 10, 2, INT_MAX) : 16384;
buf = xmalloc(len);
if (0 > (len = klogctl(3 + (flags & 1), buf, len)))
bb_perror_msg_and_die("klogctl");
------------------------------------------------------------------------
r15658 | pgf | 2006-07-06 16:00:43 -0400 (Thu, 06 Jul 2006) | 4 lines
Changed paths:
M /trunk/busybox/Makefile
fix dependencies so that compressed usage gets rebuilt if
a) include/usage.h is changed, and
b) after "make clean".
------------------------------------------------------------------------
Index: Makefile
===================================================================
--- Makefile (revision 15657)
+++ Makefile (revision 15658)
@@ -436,13 +436,16 @@
ifeq ($(strip $(CONFIG_FEATURE_COMPRESS_USAGE)),y)
USAGE_BIN:=scripts/usage
-$(USAGE_BIN): $(top_srcdir)/scripts/usage.c .config
+$(USAGE_BIN): $(top_srcdir)/scripts/usage.c .config \
+ $(top_srcdir)/include/usage.h
$(do_link.h)
DEP_INCLUDES += include/usage_compressed.h
-include/usage_compressed.h: .config $(USAGE_BIN) $(top_srcdir)/scripts/usage_compressed
- $(Q)SED="$(SED)" $(SHELL) $(top_srcdir)/scripts/usage_compressed "$(top_builddir)/scripts" > $@
+include/usage_compressed.h: .config $(USAGE_BIN) \
+ $(top_srcdir)/scripts/usage_compressed
+ $(Q)SED="$(SED)" $(SHELL) $(top_srcdir)/scripts/usage_compressed \
+ "$(top_builddir)/scripts" > $@
endif # CONFIG_FEATURE_COMPRESS_USAGE
# workaround alleged bug in make-3.80, make-3.81
@@ -470,7 +473,8 @@
docs/BusyBox.txt docs/BusyBox.1 docs/BusyBox.html \
docs/busybox.net/BusyBox.html busybox.links \
libbusybox.so* \
- .config.old busybox busybox_unstripped
+ .config.old busybox busybox_unstripped \
+ include/usage_compressed.h scripts/usage
- rm -r -f _install testsuite/links
- find . -name .\*.flags -o -name \*.o -o -name \*.om -o -name \*.syn \
-o -name \*.os -o -name \*.osm -o -name \*.a | xargs rm -f
------------------------------------------------------------------------
r15659 | landley | 2006-07-06 16:02:47 -0400 (Thu, 06 Jul 2006) | 3 lines
Changed paths:
M /trunk/busybox/libbb/Makefile
Attempt to address Shaun Jackman's problem adding "busybox: busybox.bflt" to
.config.mak.
------------------------------------------------------------------------
Index: libbb/Makefile
===================================================================
--- libbb/Makefile (revision 15658)
+++ libbb/Makefile (revision 15659)
@@ -12,6 +12,12 @@
endif
srcdir=$(top_srcdir)/libbb
LIBBB_DIR:=./
+
+# Ensure "all" is still the default target when make is run by itself in
+# libbb, even if the files we include define rules for targets.
+
+all:
+
include $(top_srcdir)/Rules.mak
include $(top_builddir)/.config
include Makefile.in
------------------------------------------------------------------------
r15660 | landley | 2006-07-06 16:30:19 -0400 (Thu, 06 Jul 2006) | 3 lines
Changed paths:
M /trunk/busybox/archival/libunarchive/get_header_tar.c
Fix tar so it can extract git-generated tarballs, based on a suggestion
from Erik Frederiksen.
------------------------------------------------------------------------
Index: archival/libunarchive/get_header_tar.c
===================================================================
--- archival/libunarchive/get_header_tar.c (revision 15659)
+++ archival/libunarchive/get_header_tar.c (revision 15660)
@@ -137,10 +137,6 @@
case '1':
file_header->mode |= S_IFREG;
break;
- case 'x':
- case 'g':
- bb_error_msg_and_die("pax is not tar");
- break;
case '7':
/* Reserved for high performance files, treat as normal file */
case 0:
@@ -188,8 +184,11 @@
case 'N': /* Old GNU for names > 100 characters */
case 'S': /* Sparse file */
case 'V': /* Volume header */
- bb_error_msg("Ignoring GNU extension type %c", tar.formated.typeflag);
#endif
+ case 'g': /* pax global header */
+ case 'x': /* pax extended header */
+ bb_error_msg("Ignoring extension type %c", tar.formated.typeflag);
+ break;
default:
bb_error_msg("Unknown typeflag: 0x%x", tar.formated.typeflag);
}
------------------------------------------------------------------------
r15670 | landley | 2006-07-09 13:03:07 -0400 (Sun, 09 Jul 2006) | 3 lines
Changed paths:
M /trunk/busybox/shell/lash.c
Bugfix from Shaun Jackman (check that argv[optind] isn't null before
dereferencing it) plus a bunch of tweaks from me.
------------------------------------------------------------------------
Index: shell/lash.c
===================================================================
--- shell/lash.c (revision 15669)
+++ shell/lash.c (revision 15670)
@@ -1498,6 +1498,8 @@
remove_job(&job_list, job_list.fg);
}
}
+#else
+void free_memory(void);
#endif
#ifdef CONFIG_LASH_JOB_CONTROL
@@ -1528,7 +1530,7 @@
/* Put ourselves in our own process group. */
setsid();
shell_pgrp = getpid ();
- setpgid (shell_pgrp, shell_pgrp);
+ setpgid(shell_pgrp, shell_pgrp);
/* Grab control of the terminal. */
tcsetpgrp(shell_terminal, shell_pgrp);
@@ -1577,7 +1579,7 @@
argv = argv+optind;
break;
case 'i':
- interactive = TRUE;
+ interactive++;
break;
default:
bb_show_usage();
@@ -1591,18 +1593,18 @@
* standard output is a terminal
* Refer to Posix.2, the description of the `sh' utility. */
if (argv[optind]==NULL && input==stdin &&
- isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
- interactive=TRUE;
+ isatty(STDIN_FILENO) && isatty(STDOUT_FILENO))
+ {
+ interactive++;
}
setup_job_control();
- if (interactive==TRUE) {
- //printf( "optind=%d argv[optind]='%s'\n", optind, argv[optind]);
+ if (interactive) {
/* Looks like they want an interactive shell */
-#ifndef CONFIG_FEATURE_SH_EXTRA_QUIET
- printf( "\n\n%s Built-in shell (lash)\n", BB_BANNER);
- printf( "Enter 'help' for a list of built-in commands.\n\n");
-#endif
- } else if (local_pending_command==NULL) {
+ if (!ENABLE_FEATURE_SH_EXTRA_QUIET) {
+ printf( "\n\n%s Built-in shell (lash)\n", BB_BANNER);
+ printf( "Enter 'help' for a list of built-in commands.\n\n");
+ }
+ } else if (!local_pending_command && argv[optind]) {
//printf( "optind=%d argv[optind]='%s'\n", optind, argv[optind]);
input = bb_xfopen(argv[optind], "r");
/* be lazy, never mark this closed */
@@ -1614,15 +1616,10 @@
if (!cwd)
cwd = bb_msg_unknown;
-#ifdef CONFIG_FEATURE_CLEAN_UP
- atexit(free_memory);
-#endif
+ if (ENABLE_FEATURE_CLEAN_UP) atexit(free_memory);
-#ifdef CONFIG_FEATURE_COMMAND_EDITING
- cmdedit_set_initial_prompt();
-#else
- PS1 = NULL;
-#endif
+ if (ENABLE_FEATURE_COMMAND_EDITING) cmdedit_set_initial_prompt();
+ else PS1 = NULL;
return (busy_loop(input));
}
------------------------------------------------------------------------
r15698 | vapier | 2006-07-14 23:59:00 -0400 (Fri, 14 Jul 2006) | 2 lines
Changed paths:
M /trunk/busybox/libbb/obscure.c
Tito writes: If the gecos field of an user is empty, obscure reports a false "similar to gecos" error.
------------------------------------------------------------------------
Index: libbb/obscure.c
===================================================================
--- libbb/obscure.c (revision 15697)
+++ libbb/obscure.c (revision 15698)
@@ -109,7 +109,7 @@
return "similar to username";
}
/* no gecos as-is, as sub-string, reversed, capitalized, doubled */
- if (string_checker(new_p, pw->pw_gecos)) {
+ if (*pw->pw_gecos && string_checker(new_p, pw->pw_gecos)) {
return "similar to gecos";
}
/* hostname as-is, as sub-string, reversed, capitalized, doubled */
------------------------------------------------------------------------
r15700 | landley | 2006-07-15 19:00:46 -0400 (Sat, 15 Jul 2006) | 4 lines
Changed paths:
M /trunk/busybox/include/libbb.h
M /trunk/busybox/libbb/xfuncs.c
We need xsetuid() and xsetgid() because per-user process resource limits can
prevent a process from switching to a user that has too many processes, and
when that happens WE'RE STILL ROOT. See http://lwn.net/Articles/190331/
------------------------------------------------------------------------
Index: libbb/xfuncs.c
===================================================================
--- libbb/xfuncs.c (revision 15699)
+++ libbb/xfuncs.c (revision 15700)
@@ -232,3 +232,15 @@
return 0;
}
#endif
+
+#ifdef L_setuid
+void xsetgid(gid_t gid)
+{
+ if (setgid(gid)) bb_error_msg_and_die("setgid");
+}
+
+void xsetuid(uid_t uid)
+{
+ if (setuid(uid)) bb_error_msg_and_die("setuid");
+}
+#endif
Index: include/libbb.h
===================================================================
--- include/libbb.h (revision 15699)
+++ include/libbb.h (revision 15700)
@@ -185,6 +185,8 @@
extern bb_xbind(int sockfd, struct sockaddr *my_addr, socklen_t addrlen);
extern void bb_xlisten(int s, int backlog);
extern void bb_xchdir(const char *path);
+extern void xsetgid(gid_t gid);
+extern void xsetuid(uid_t uid);
#define BB_GETOPT_ERROR 0x80000000UL
extern const char *bb_opt_complementally;
------------------------------------------------------------------------
r15702 | landley | 2006-07-16 04:06:34 -0400 (Sun, 16 Jul 2006) | 2 lines
Changed paths:
M /trunk/busybox/loginutils/passwd.c
M /trunk/busybox/networking/arping.c
M /trunk/busybox/networking/ether-wake.c
M /trunk/busybox/networking/fakeidentd.c
M /trunk/busybox/networking/inetd.c
M /trunk/busybox/networking/traceroute.c
Convert setuid/setgid users to xsetuid/xsetgid.
------------------------------------------------------------------------
Index: networking/fakeidentd.c
===================================================================
--- networking/fakeidentd.c (revision 15701)
+++ networking/fakeidentd.c (revision 15702)
@@ -159,8 +159,8 @@
close(0);
inetbind();
- if (setgid(nogrp)) bb_error_msg_and_die("Could not setgid()");
- if (setuid(nobody)) bb_error_msg_and_die("Could not setuid()");
+ xsetgid(nogrp);
+ xsetuid(nobody);
close(1);
close(2);
Index: networking/ether-wake.c
===================================================================
--- networking/ether-wake.c (revision 15701)
+++ networking/ether-wake.c (revision 15702)
@@ -145,7 +145,7 @@
s = make_socket();
/* now that we have a raw socket we can drop root */
- setuid(getuid());
+ xsetuid(getuid());
/* look up the dest mac address */
get_dest_addr(argv[optind], &eaddr);
Index: networking/inetd.c
===================================================================
--- networking/inetd.c (revision 15701)
+++ networking/inetd.c (revision 15702)
@@ -1513,11 +1513,11 @@
if (sep->se_group) {
pwd->pw_gid = grp->gr_gid;
}
- setgid ((gid_t) pwd->pw_gid);
+ xsetgid ((gid_t) pwd->pw_gid);
initgroups (pwd->pw_name, pwd->pw_gid);
- setuid ((uid_t) pwd->pw_uid);
+ xsetuid((uid_t) pwd->pw_uid);
} else if (sep->se_group) {
- setgid (grp->gr_gid);
+ xsetgid(grp->gr_gid);
setgroups (1, &grp->gr_gid);
}
dup2 (ctrl, 0);
Index: networking/traceroute.c
===================================================================
--- networking/traceroute.c (revision 15701)
+++ networking/traceroute.c (revision 15702)
@@ -941,7 +941,6 @@
#endif
u_short off = 0;
struct IFADDRLIST *al;
- int uid = getuid();
char *device = NULL;
int max_ttl = 30;
char *max_ttl_str = NULL;
@@ -1010,8 +1009,7 @@
* set the ip source address of the outbound
* probe (e.g., on a multi-homed host).
*/
- if (uid)
- bb_error_msg_and_die("-s %s: Permission denied", source);
+ if (getuid()) bb_error_msg_and_die("-s %s: Permission denied", source);
}
if(waittime_str)
waittime = str2val(waittime_str, "wait time", 2, 24 * 60 * 60);
@@ -1160,8 +1158,8 @@
sizeof(on));
/* Revert to non-privileged user after opening sockets */
- setgid(getgid());
- setuid(uid);
+ xsetgid(getgid());
+ xsetuid(getuid());
outip = (struct ip *)xcalloc(1, (unsigned)packlen);
Index: networking/arping.c
===================================================================
--- networking/arping.c (revision 15701)
+++ networking/arping.c (revision 15702)
@@ -262,7 +262,8 @@
s = socket(PF_PACKET, SOCK_DGRAM, 0);
ifindex = errno;
- setuid(getuid());
+ // Drop suid root privileges
+ xsetuid(getuid());
{
unsigned long opt;
Index: loginutils/passwd.c
===================================================================
--- loginutils/passwd.c (revision 15701)
+++ loginutils/passwd.c (revision 15702)
@@ -227,10 +227,7 @@
signal(SIGINT, SIG_IGN);
signal(SIGQUIT, SIG_IGN);
umask(077);
- if (setuid(0)) {
- syslog(LOG_ERR, "can't setuid(0)");
- bb_error_msg_and_die( "Cannot change ID to root.\n");
- }
+ xsetuid(0);
if (!update_passwd(pw, crypt_passwd)) {
syslog(LOG_INFO, "password for `%s' changed by user `%s'", name,
myname);
------------------------------------------------------------------------
r15705 | landley | 2006-07-16 14:58:18 -0400 (Sun, 16 Jul 2006) | 2 lines
Changed paths:
M /trunk/busybox/loginutils/adduser.c
Bugfix from Tito to make sure /etc/group gets updated.
------------------------------------------------------------------------
Index: loginutils/adduser.c
===================================================================
--- loginutils/adduser.c (revision 15704)
+++ loginutils/adduser.c (revision 15705)
@@ -96,6 +96,7 @@
static int adduser(struct passwd *p, unsigned long flags)
{
FILE *file;
+ int addgroup = !p->pw_gid;
/* make sure everything is kosher and setup uid && gid */
file = bb_xfopen(bb_path_passwd_file, "a");
@@ -132,9 +133,8 @@
/* add to group */
/* addgroup should be responsible for dealing w/ gshadow */
/* if using a pre-existing group, don't create one */
- if (p->pw_gid == 0) {
- addgroup_wrapper(p);
- }
+ if (addgroup) addgroup_wrapper(p);
+
/* Clear the umask for this process so it doesn't
* * screw up the permissions on the mkdir and chown. */
umask(0);
------------------------------------------------------------------------
r15727 | landley | 2006-07-19 17:33:42 -0400 (Wed, 19 Jul 2006) | 4 lines
Changed paths:
M /trunk/busybox/modutils/modprobe.c
Patch from Yann Morin to look for modules.conf in the right place on 2.6.
Fixes http://bugs.busybox.net/view.php?id=942
------------------------------------------------------------------------
Index: modutils/modprobe.c
===================================================================
--- modutils/modprobe.c (revision 15726)
+++ modutils/modprobe.c (revision 15727)
@@ -545,29 +545,37 @@
}
close ( fd );
+ /*
+ * First parse system-specific options and aliases
+ * as they take precedence over the kernel ones.
+ */
if (!ENABLE_FEATURE_2_6_MODULES
|| ( fd = open ( "/etc/modprobe.conf", O_RDONLY )) < 0 )
if (( fd = open ( "/etc/modules.conf", O_RDONLY )) < 0 )
- if (( fd = open ( "/etc/conf.modules", O_RDONLY )) < 0 )
- return first;
+ fd = open ( "/etc/conf.modules", O_RDONLY );
- include_conf (&first, &current, buffer, sizeof(buffer), fd);
- close(fd);
+ if (fd >= 0) {
+ include_conf (&first, &current, buffer, sizeof(buffer), fd);
+ close(fd);
+ }
- filename = bb_xasprintf("/lib/modules/%s/modules.alias", un.release);
- fd = open ( filename, O_RDONLY );
- if (ENABLE_FEATURE_CLEAN_UP)
- free(filename);
- if (fd < 0) {
- /* Ok, that didn't work. Fall back to looking in /lib/modules */
- if (( fd = open ( "/lib/modules/modules.alias", O_RDONLY )) < 0 ) {
- return first;
+ /* Only 2.6 has a modules.alias file */
+ if (ENABLE_FEATURE_2_6_MODULES) {
+ /* Parse kernel-declared aliases */
+ filename = bb_xasprintf("/lib/modules/%s/modules.alias", un.release);
+ if ((fd = open ( filename, O_RDONLY )) < 0) {
+ /* Ok, that didn't work. Fall back to looking in /lib/modules */
+ fd = open ( "/lib/modules/modules.alias", O_RDONLY );
}
+ if (ENABLE_FEATURE_CLEAN_UP)
+ free(filename);
+
+ if (fd >= 0) {
+ include_conf (&first, &current, buffer, sizeof(buffer), fd);
+ close(fd);
+ }
}
- include_conf (&first, &current, buffer, sizeof(buffer), fd);
- close(fd);
-
return first;
}
+13 -30
View File
@@ -5,98 +5,81 @@
menu "Console Utilities"
config CHVT
config CONFIG_CHVT
bool "chvt"
default n
help
This program is used to change to another terminal.
Example: chvt 4 (change to terminal /dev/tty4)
config CLEAR
config CONFIG_CLEAR
bool "clear"
default n
help
This program clears the terminal screen.
config DEALLOCVT
config CONFIG_DEALLOCVT
bool "deallocvt"
default n
help
This program deallocates unused virtual consoles.
config DUMPKMAP
config CONFIG_DUMPKMAP
bool "dumpkmap"
default n
help
This program dumps the kernel's keyboard translation table to
stdout, in binary format. You can then use loadkmap to load it.
config LOADFONT
config CONFIG_LOADFONT
bool "loadfont"
default n
help
This program loads a console font from standard input.
config LOADKMAP
config CONFIG_LOADKMAP
bool "loadkmap"
default n
help
This program loads a keyboard translation table from
standard input.
config OPENVT
config CONFIG_OPENVT
bool "openvt"
default n
help
This program is used to start a command on an unused
virtual terminal.
config RESET
config CONFIG_RESET
bool "reset"
default n
help
This program is used to reset the terminal screen, if it
gets messed up.
config RESIZE
bool "resize"
default n
help
This program is used to (re)set the width and height of your current
terminal.
config FEATURE_RESIZE_PRINT
bool "print environment variables"
default n
depends on RESIZE
help
Prints the newly set size (number of columns and rows) of
the terminal.
E.g.:
COLUMNS=80;LINES=44;export COLUMNS LINES;
config SETCONSOLE
config CONFIG_SETCONSOLE
bool "setconsole"
default n
help
This program redirects the system console to another device,
like the current tty while logged in via telnet.
config FEATURE_SETCONSOLE_LONG_OPTIONS
config CONFIG_FEATURE_SETCONSOLE_LONG_OPTIONS
bool "Enable long options"
default n
depends on SET_CONSOLE && GETOPT_LONG
depends on CONFIG_SET_CONSOLE && CONFIG_GETOPT_LONG
help
Support long options for the setconsole applet.
config SETKEYCODES
config CONFIG_SETKEYCODES
bool "setkeycodes"
default n
help
This program loads entries into the kernel's scancode-to-keycode
map, allowing unusual keyboards to generate usable keycodes.
config SETLOGCONS
config CONFIG_SETLOGCONS
bool "setlogcons"
default n
help
-19
View File
@@ -1,19 +0,0 @@
# Makefile for busybox
#
# Copyright (C) 1999-2005 by Erik Andersen <andersen@codepoet.org>
#
# Licensed under the GPL v2, see the file LICENSE in this tarball.
lib-y:=
lib-$(CONFIG_CHVT) += chvt.o
lib-$(CONFIG_CLEAR) += clear.o
lib-$(CONFIG_DEALLOCVT) += deallocvt.o
lib-$(CONFIG_DUMPKMAP) += dumpkmap.o
lib-$(CONFIG_SETCONSOLE) += setconsole.o
lib-$(CONFIG_LOADFONT) += loadfont.o
lib-$(CONFIG_LOADKMAP) += loadkmap.o
lib-$(CONFIG_OPENVT) += openvt.o
lib-$(CONFIG_RESET) += reset.o
lib-$(CONFIG_RESIZE) += resize.o
lib-$(CONFIG_SETKEYCODES) += setkeycodes.o
lib-$(CONFIG_SETLOGCONS) += setlogcons.o
+23
View File
@@ -0,0 +1,23 @@
# Makefile for busybox
#
# Copyright (C) 1999-2005 by Erik Andersen <andersen@codepoet.org>
#
# Licensed under the GPL v2, see the file LICENSE in this tarball.
ifndef top_srcdir
top_srcdir=..
endif
ifndef top_builddir
top_builddir=..
endif
srcdir=$(top_srcdir)/console/tools
CONSOLETOOLS_DIR:=./
include $(top_srcdir)/Rules.mak
include $(top_builddir)/.config
include $(srcdir)/Makefile.in
all: $(libraries-y)
-include $(top_builddir)/.depend
clean:
rm -f *.o *.a $(AR_TARGET)
+38
View File
@@ -0,0 +1,38 @@
# Makefile for busybox
#
# Copyright (C) 1999-2005 by Erik Andersen <andersen@codepoet.org>
#
# Licensed under the GPL v2, see the file LICENSE in this tarball.
CONSOLETOOLS_AR:=console-tools.a
ifndef $(CONSOLETOOLS_DIR)
CONSOLETOOLS_DIR:=$(top_builddir)/console-tools/
endif
srcdir=$(top_srcdir)/console-tools
CONSOLETOOLS-y:=
CONSOLETOOLS-$(CONFIG_CHVT) += chvt.o
CONSOLETOOLS-$(CONFIG_CLEAR) += clear.o
CONSOLETOOLS-$(CONFIG_DEALLOCVT) += deallocvt.o
CONSOLETOOLS-$(CONFIG_DUMPKMAP) += dumpkmap.o
CONSOLETOOLS-$(CONFIG_SETCONSOLE) += setconsole.o
CONSOLETOOLS-$(CONFIG_LOADFONT) += loadfont.o
CONSOLETOOLS-$(CONFIG_LOADKMAP) += loadkmap.o
CONSOLETOOLS-$(CONFIG_OPENVT) += openvt.o
CONSOLETOOLS-$(CONFIG_RESET) += reset.o
CONSOLETOOLS-$(CONFIG_SETKEYCODES) += setkeycodes.o
CONSOLETOOLS-$(CONFIG_SETLOGCONS) += setlogcons.o
ifneq ($(strip $(CONSOLETOOLS-y)),)
libraries-y+=$(CONSOLETOOLS_DIR)$(CONSOLETOOLS_AR)
endif
CONSOLETOOLS_SRC-y:=$(patsubst %.o,$(srcdir)/%.c,$(CONSOLETOOLS-y))
CONSOLETOOLS_SRC-a:=$(wildcard $(srcdir)/*.c)
APPLET_SRC-y+=$(CONSOLETOOLS_SRC-y)
APPLET_SRC-a+=$(CONSOLETOOLS_SRC-a)
$(CONSOLETOOLS_DIR)$(CONSOLETOOLS_AR): $(patsubst %,$(CONSOLETOOLS_DIR)%, $(CONSOLETOOLS-y))
$(do_ar)
$(CONSOLETOOLS_DIR)%.o: $(srcdir)/%.c
$(compile.c)
+6 -1
View File
@@ -7,6 +7,11 @@
* Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
*/
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/ioctl.h>
#include "busybox.h"
/* From <linux/vt.h> */
@@ -24,7 +29,7 @@ int chvt_main(int argc, char **argv)
}
fd = get_console_fd();
num = xatoul_range(argv[1], 1, 63);
num = bb_xgetlarg(argv[1], 10, 0, INT_MAX);
if ((-1 == ioctl(fd, VT_ACTIVATE, num))
|| (-1 == ioctl(fd, VT_WAITACTIVE, num))) {
bb_perror_msg_and_die("ioctl");
+13 -6
View File
@@ -10,6 +10,11 @@
/* no options, no getopt */
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/ioctl.h>
#include "busybox.h"
/* From <linux/vt.h> */
@@ -21,13 +26,15 @@ int deallocvt_main(int argc, char *argv[])
int num = 0;
switch (argc) {
case 2:
num = xatoul_range(argv[1], 1, 63);
case 2:
if ((num = bb_xgetlarg(argv[1], 10, 0, INT_MAX)) == 0) {
bb_error_msg_and_die("0: illegal VT number");
}
/* Fallthrough */
case 1:
break;
default:
bb_show_usage();
case 1:
break;
default:
bb_show_usage();
}
if (-1 == ioctl(get_console_fd(), VT_DISALLOCATE, num)) {
+8 -1
View File
@@ -8,6 +8,13 @@
*
*/
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <sys/ioctl.h>
#include "busybox.h"
/* From <linux/kd.h> */
@@ -31,7 +38,7 @@ int dumpkmap_main(int argc, char **argv)
if (argc >= 2 && *argv[1] == '-')
bb_show_usage();
fd = xopen(CURRENT_VC, O_RDWR);
fd = bb_xopen(CURRENT_VC, O_RDWR);
write(1, magic, 7);
+25 -15
View File
@@ -7,10 +7,20 @@
* Loads the console font, and possibly the corresponding screen map(s).
* (Adapted for busybox by Matej Vela.)
*/
#include "busybox.h"
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <dirent.h>
#include <errno.h>
#include <sys/ioctl.h>
#include <sys/kd.h>
#include <endian.h>
#include "busybox.h"
enum {
enum{
PSF_MAGIC1 = 0x36,
PSF_MAGIC2 = 0x04,
@@ -37,7 +47,7 @@ int loadfont_main(int argc, char **argv)
if (argc != 1)
bb_show_usage();
fd = xopen(CURRENT_VC, O_RDWR);
fd = bb_xopen(CURRENT_VC, O_RDWR);
loadnewfont(fd);
return EXIT_SUCCESS;
@@ -51,7 +61,7 @@ static void do_loadfont(int fd, unsigned char *inbuf, int unit, int fontsize)
memset(buf, 0, sizeof(buf));
if (unit < 1 || unit > 32)
bb_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++)
memcpy(buf + (32 * i), inbuf + (unit * i), unit);
@@ -81,14 +91,14 @@ do_loadtable(int fd, unsigned char *inbuf, int tailsz, int fontsize)
struct unipair *up;
int ct = 0, maxct;
int glyph;
uint16_t unicode;
u_short unicode;
maxct = tailsz; /* more than enough */
up = xmalloc(maxct * sizeof(struct unipair));
up = (struct unipair *) xmalloc(maxct * sizeof(struct unipair));
for (glyph = 0; glyph < fontsize; glyph++) {
while (tailsz >= 2) {
unicode = (((uint16_t) inbuf[1]) << 8) + inbuf[0];
unicode = (((u_short) inbuf[1]) << 8) + inbuf[0];
tailsz -= 2;
inbuf += 2;
if (unicode == PSF_SEPARATOR)
@@ -108,8 +118,8 @@ do_loadtable(int fd, unsigned char *inbuf, int tailsz, int fontsize)
if (ioctl(fd, PIO_UNIMAPCLR, &advice)) {
#ifdef ENOIOCTLCMD
if (errno == ENOIOCTLCMD) {
bb_error_msg("it seems this kernel is older than 1.1.92");
bb_error_msg_and_die("no Unicode mapping table loaded");
bb_error_msg("It seems this kernel is older than 1.1.92");
bb_error_msg_and_die("No Unicode mapping table loaded.");
} else
#endif
bb_perror_msg_and_die("PIO_UNIMAPCLR");
@@ -134,13 +144,13 @@ static void loadnewfont(int fd)
*/
inputlth = fread(inbuf, 1, sizeof(inbuf), stdin);
if (ferror(stdin))
bb_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;
maybe these do not occur: 16kB for the font,
and 16kB for the map leaves 32 unicode values
for each font position */
if (!feof(stdin))
bb_perror_msg_and_die("font too large");
bb_perror_msg_and_die("Font too large");
/* test for psf first */
{
@@ -158,11 +168,11 @@ static void loadnewfont(int fd)
goto no_psf;
if (psfhdr.mode > PSF_MAXMODE)
bb_error_msg_and_die("unsupported psf file mode");
bb_error_msg_and_die("Unsupported psf file mode");
fontsize = ((psfhdr.mode & PSF_MODE512) ? 512 : 256);
#if !defined( PIO_FONTX ) || defined( __sparc__ )
if (fontsize != 256)
bb_error_msg_and_die("only fontsize 256 supported");
bb_error_msg_and_die("Only fontsize 256 supported");
#endif
hastable = (psfhdr.mode & PSF_MODEHASTAB);
unit = psfhdr.charsize;
@@ -170,7 +180,7 @@ static void loadnewfont(int fd)
head = head0 + fontsize * unit;
if (head > inputlth || (!hastable && head != inputlth))
bb_error_msg_and_die("input file: bad length");
bb_error_msg_and_die("Input file: bad length");
do_loadfont(fd, inbuf + head0, unit, fontsize);
if (hastable)
do_loadtable(fd, inbuf + head, inputlth - head, fontsize);
@@ -185,7 +195,7 @@ static void loadnewfont(int fd)
} else {
/* bare font */
if (inputlth & 0377)
bb_error_msg_and_die("bad input file size");
bb_error_msg_and_die("Bad input file size");
offset = 0;
unit = inputlth / 256;
}
+11 -4
View File
@@ -8,6 +8,13 @@
*
*/
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include "busybox.h"
#define BINARY_KEYMAP_MAGIC "bkeymap"
@@ -29,24 +36,24 @@ int loadkmap_main(int argc, char **argv)
{
struct kbentry ke;
int i, j, fd;
uint16_t ibuff[NR_KEYS];
u_short ibuff[NR_KEYS];
char flags[MAX_NR_KEYMAPS];
char buff[7];
if (argc != 1)
bb_show_usage();
fd = xopen(CURRENT_VC, O_RDWR);
fd = bb_xopen(CURRENT_VC, O_RDWR);
xread(0, buff, 7);
if (strncmp(buff, BINARY_KEYMAP_MAGIC, 7))
bb_error_msg_and_die("this is not a valid binary keymap");
bb_error_msg_and_die("This is not a valid binary keymap.");
xread(0, flags, MAX_NR_KEYMAPS);
for (i = 0; i < MAX_NR_KEYMAPS; i++) {
if (flags[i] == 1) {
xread(0, ibuff, NR_KEYS * sizeof(uint16_t));
xread(0, ibuff, NR_KEYS * sizeof(u_short));
for (j = 0; j < NR_KEYS; j++) {
ke.kb_index = j;
ke.kb_table = i;
+20 -9
View File
@@ -10,6 +10,14 @@
/* getopt not needed */
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <sys/types.h>
#include <ctype.h>
#include "busybox.h"
int openvt_main(int argc, char **argv)
@@ -17,23 +25,26 @@ int openvt_main(int argc, char **argv)
int fd;
char vtname[sizeof(VC_FORMAT) + 2];
if (argc < 3) {
bb_show_usage();
}
/* check for illegal vt number: < 1 or > 63 */
sprintf(vtname, VC_FORMAT, (int)xatoul_range(argv[1], 1, 63));
/* check for Illegal vt number: < 1 or > 12 */
sprintf(vtname, VC_FORMAT, (int)bb_xgetlarg(argv[1], 10, 1, 12));
if (fork() == 0) {
/* child */
/* leave current vt (controlling tty) */
setsid();
/* leave current vt */
if (setsid() < 0) {
bb_perror_msg_and_die("setsid");
}
close(0); /* so that new vt becomes stdin */
/* and grab new one */
fd = xopen(vtname, O_RDWR);
/* Reassign stdin, stdout and sterr */
dup2(fd, STDIN_FILENO);
fd = bb_xopen(vtname, O_RDWR);
/* Reassign stdout and sterr */
dup2(fd, STDOUT_FILENO);
dup2(fd, STDERR_FILENO);
while (fd > 2) close(fd--);
execvp(argv[2], &argv[2]);
_exit(1);
-38
View File
@@ -1,38 +0,0 @@
/* vi: set sw=4 ts=4: */
/*
* resize - set terminal width and height.
*
* Copyright 2006 Bernhard Fischer
*
* Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
*/
/* no options, no getopt */
#include "busybox.h"
int resize_main(int argc, char **argv)
{
struct termios old, new;
struct winsize w = {0,0,0,0};
int ret;
tcgetattr(STDOUT_FILENO, &old); /* fiddle echo */
new = old;
new.c_cflag |= (CLOCAL | CREAD);
new.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
tcsetattr(STDOUT_FILENO, TCSANOW, &new);
/* save_cursor_pos 7
* scroll_whole_screen [r
* put_cursor_waaaay_off [$x;$yH
* get_cursor_pos [6n
* restore_cursor_pos 8
*/
printf("\0337\033[r\033[999;999H\033[6n");
scanf("\033[%hu;%huR", &w.ws_row, &w.ws_col);
ret = ioctl(STDOUT_FILENO, TIOCSWINSZ, &w);
printf("\0338");
tcsetattr(STDOUT_FILENO, TCSANOW, &old);
if (ENABLE_FEATURE_RESIZE_PRINT)
printf("COLUMNS=%d;LINES=%d;export COLUMNS LINES;\n",
w.ws_col, w.ws_row);
return ret;
}
+10 -3
View File
@@ -7,6 +7,13 @@
* Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
*/
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <stdio.h>
#include <getopt.h> /* struct option */
#include "busybox.h"
#if ENABLE_FEATURE_SETCONSOLE_LONG_OPTIONS
@@ -24,9 +31,9 @@ int setconsole_main(int argc, char **argv)
const char *device = CURRENT_TTY;
#if ENABLE_FEATURE_SETCONSOLE_LONG_OPTIONS
applet_long_options = setconsole_long_options;
bb_applet_long_options = setconsole_long_options;
#endif
flags = getopt32(argc, argv, "r");
flags = bb_getopt_ulflags(argc, argv, "r");
if (argc - optind > 1)
bb_show_usage();
@@ -40,7 +47,7 @@ int setconsole_main(int argc, char **argv)
device = CONSOLE_DEV;
}
if (-1 == ioctl(xopen(device, O_RDONLY), TIOCCONS)) {
if (-1 == ioctl(bb_xopen(device, O_RDONLY), TIOCCONS)) {
bb_perror_msg_and_die("TIOCCONS");
}
return EXIT_SUCCESS;
+24 -16
View File
@@ -27,27 +27,35 @@ enum {
extern int
setkeycodes_main(int argc, char** argv)
{
int fd, sc;
struct kbkeycode a;
char *ep;
int fd, sc;
struct kbkeycode a;
if (argc % 2 != 1 || argc < 2) {
bb_show_usage();
if (argc % 2 != 1 || argc < 2) {
bb_show_usage();
}
fd = get_console_fd();
while (argc > 2) {
a.keycode = xatoul_range(argv[2], 0, 127);
a.scancode = sc = xstrtoul_range(argv[1], 16, 0, 255);
if (a.scancode > 127) {
a.scancode -= 0xe000;
a.scancode += 128;
}
if (ioctl(fd, KDSETKEYCODE, &a)) {
bb_perror_msg_and_die("failed to set SCANCODE %x to KEYCODE %d", sc, a.keycode);
}
argc -= 2;
argv += 2;
while (argc > 2) {
a.keycode = atoi(argv[2]);
a.scancode = sc = strtol(argv[1], &ep, 16);
if (*ep) {
bb_error_msg_and_die("error reading SCANCODE: '%s'", argv[1]);
}
if (a.scancode > 127) {
a.scancode -= 0xe000;
a.scancode += 128;
}
if (a.scancode > 255 || a.keycode > 127) {
bb_error_msg_and_die("SCANCODE or KEYCODE outside bounds");
}
if (ioctl(fd,KDSETKEYCODE,&a)) {
perror("KDSETKEYCODE");
bb_error_msg_and_die("failed to set SCANCODE %x to KEYCODE %d", sc, a.keycode);
}
argc -= 2;
argv += 2;
}
return EXIT_SUCCESS;
}
+8 -4
View File
@@ -1,6 +1,6 @@
/* vi: set sw=4 ts=4: */
/*
* setlogcons: Send kernel messages to the current console or to console N
* setlogcons: Send kernel messages to the current console or to console N
*
* Copyright (C) 2006 by Jan Kiszka <jan.kiszka@web.de>
*
@@ -9,6 +9,10 @@
* Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
*/
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include "busybox.h"
extern int setlogcons_main(int argc, char **argv)
@@ -22,10 +26,10 @@ extern int setlogcons_main(int argc, char **argv)
arg.subarg = 0; /* to specified console (current as default) */
if (argc == 2)
arg.subarg = xatoul_range(argv[1], 0, 63);
arg.subarg = atoi(argv[1]);
if (ioctl(xopen(VC_1, O_RDONLY), TIOCLINUX, &arg))
bb_perror_msg_and_die("TIOCLINUX");
if (ioctl(bb_xopen(VC_1, O_RDONLY), TIOCLINUX, &arg))
bb_perror_msg_and_die("TIOCLINUX");;
return 0;
}
+153 -160
View File
@@ -5,7 +5,7 @@
menu "Coreutils"
config BASENAME
config CONFIG_BASENAME
bool "basename"
default n
help
@@ -13,101 +13,101 @@ config BASENAME
leaving just the filename itself. Enable this option if you wish
to enable the 'basename' utility.
config CAL
config CONFIG_CAL
bool "cal"
default n
help
cal is used to display a monthly calender.
config CAT
config CONFIG_CAT
bool "cat"
default n
help
cat is used to concatenate files and print them to the standard
output. Enable this option if you wish to enable the 'cat' utility.
config CATV
config CONFIG_CATV
bool "catv"
default n
help
Display nonprinting characters as escape sequences (like some
implementations' cat -v option).
config CHGRP
config CONFIG_CHGRP
bool "chgrp"
default n
help
chgrp is used to change the group ownership of files.
config CHMOD
config CONFIG_CHMOD
bool "chmod"
default n
help
chmod is used to change the access permission of files.
config CHOWN
config CONFIG_CHOWN
bool "chown"
default n
help
chown is used to change the user and/or group ownership
of files.
config CHROOT
config CONFIG_CHROOT
bool "chroot"
default n
help
chroot is used to change the root directory and run a command.
The default command is `/bin/sh'.
config CKSUM
config CONFIG_CKSUM
bool "cksum"
default n
help
cksum is used to calculate the CRC32 checksum of a file.
config CMP
config CONFIG_CMP
bool "cmp"
default n
help
cmp is used to compare two files and returns the result
to standard output.
config COMM
config CONFIG_COMM
bool "comm"
default n
help
comm is used to compare two files line by line and return
a three-column output.
config CP
config CONFIG_CP
bool "cp"
default n
help
cp is used to copy files and directories.
config CUT
config CONFIG_CUT
bool "cut"
default n
help
cut is used to print selected parts of lines from
each file to stdout.
config DATE
config CONFIG_DATE
bool "date"
default n
help
date is used to set the system date or display the
current time in the given format.
config FEATURE_DATE_ISOFMT
config CONFIG_FEATURE_DATE_ISOFMT
bool "Enable ISO date format output (-I)"
default y
depends on DATE
depends on CONFIG_DATE
help
Enable option (-I) to output an ISO-8601 compliant
date/time string.
config DD
config CONFIG_DD
bool "dd"
default n
help
@@ -115,34 +115,34 @@ config DD
by default) using specific input and output blocksizes,
while optionally performing conversions on it.
config FEATURE_DD_SIGNAL_HANDLING
config CONFIG_FEATURE_DD_SIGNAL_HANDLING
bool "Enable DD signal handling for status reporting"
default y
depends on DD
depends on CONFIG_DD
help
sending a SIGUSR1 signal to a running `dd' process makes it
print to standard error the number of records read and written
sending a SIGUSR1 signal to a running `dd' process makes it
print to standard error the number of records read and written
so far, then to resume copying.
$ dd if=/dev/zero of=/dev/null& pid=$! $ kill -USR1 $pid; sleep 1; kill $pid
$ dd if=/dev/zero of=/dev/null& pid=$! $ kill -USR1 $pid; sleep 1; kill $pid
10899206+0 records in 10899206+0 records out
config FEATURE_DD_IBS_OBS
config CONFIG_FEATURE_DD_IBS_OBS
bool "Enable ibs, obs and conv options"
default n
depends on DD
depends on CONFIG_DD
help
Enables support for writing a certain number of bytes in and out,
at a time, and performing conversions on the data stream.
config DF
config CONFIG_DF
bool "df"
default n
help
df reports the amount of disk space used and available
on filesystems.
config DIFF
config CONFIG_DIFF
bool "diff"
default n
help
@@ -150,81 +150,81 @@ config DIFF
differences between them in a form that can be given to
the patch command.
config FEATURE_DIFF_BINARY
config CONFIG_FEATURE_DIFF_BINARY
bool "Enable checks for binary files"
default y
depends on DIFF
depends on CONFIG_DIFF
help
This option enables support for checking for binary files
before a comparison is carried out.
config FEATURE_DIFF_DIR
config CONFIG_FEATURE_DIFF_DIR
bool "Enable directory support"
default y
depends on DIFF
depends on CONFIG_DIFF
help
This option enables support for directory and subdirectory
comparison.
config FEATURE_DIFF_MINIMAL
config CONFIG_FEATURE_DIFF_MINIMAL
bool "Enable -d option to find smaller sets of changes"
default n
depends on DIFF
depends on CONFIG_DIFF
help
Enabling this option allows the use of -d to make diff
try hard to find the smallest possible set of changes.
config DIRNAME
config CONFIG_DIRNAME
bool "dirname"
default n
help
dirname is used to strip a non-directory suffix from
a file name.
config DOS2UNIX
config CONFIG_DOS2UNIX
bool "dos2unix/unix2dos"
default n
help
dos2unix is used to convert a text file from DOS format to
UNIX format, and vice versa.
config UNIX2DOS
config CONFIG_UNIX2DOS
bool
default y
depends on DOS2UNIX
depends on CONFIG_DOS2UNIX
help
unix2dos is used to convert a text file from UNIX format to
DOS format, and vice versa.
config DU
config CONFIG_DU
bool "du (default blocksize of 512 bytes)"
default n
help
du is used to report the amount of disk space used
for specified files.
config FEATURE_DU_DEFAULT_BLOCKSIZE_1K
config CONFIG_FEATURE_DU_DEFAULT_BLOCKSIZE_1K
bool "Use a default blocksize of 1024 bytes (1K)"
default y
depends on DU
depends on CONFIG_DU
help
Use a blocksize of (1K) instead of the default 512b.
config ECHO
config CONFIG_ECHO
bool "echo (basic SuSv3 version taking no options)"
default n
help
echo is used to print a specified string to stdout.
# this entry also appears in shell/Config.in, next to the echo builtin
config FEATURE_FANCY_ECHO
config CONFIG_FEATURE_FANCY_ECHO
bool "Enable echo options (-n and -e)"
default y
depends on ECHO
depends on CONFIG_ECHO
help
This adds options (-n and -e) to echo.
config ENV
config CONFIG_ENV
bool "env"
default n
help
@@ -232,158 +232,158 @@ config ENV
a command; without options it displays the current
environment.
config FEATURE_ENV_LONG_OPTIONS
config CONFIG_FEATURE_ENV_LONG_OPTIONS
bool "Enable long options"
default n
depends on ENV && GETOPT_LONG
depends on CONFIG_ENV && CONFIG_GETOPT_LONG
help
Support long options for the env applet.
config EXPR
config CONFIG_EXPR
bool "expr"
default n
help
expr is used to calculate numbers and print the result
to standard output.
config EXPR_MATH_SUPPORT_64
config CONFIG_EXPR_MATH_SUPPORT_64
bool "Extend Posix numbers support to 64 bit"
default n
depends on EXPR
depends on CONFIG_EXPR
help
Enable 64-bit math support in the expr applet. This will make
the applet slightly larger, but will allow computation with very
large numbers.
config FALSE
config CONFIG_FALSE
bool "false"
default n
help
false returns an exit code of FALSE (1).
config FOLD
config CONFIG_FOLD
bool "fold"
default n
help
Wrap text to fit a specific width.
config HEAD
config CONFIG_HEAD
bool "head"
default n
help
head is used to print the first specified number of lines
from files.
config FEATURE_FANCY_HEAD
config CONFIG_FEATURE_FANCY_HEAD
bool "Enable head options (-c, -q, and -v)"
default n
depends on HEAD
depends on CONFIG_HEAD
help
This enables the head options (-c, -q, and -v).
config HOSTID
config CONFIG_HOSTID
bool "hostid"
default n
help
hostid prints the numeric identifier (in hexadecimal) for
the current host.
config ID
config CONFIG_ID
bool "id"
default n
help
id displays the current user and group ID names.
config INSTALL
config CONFIG_INSTALL
bool "install"
default n
help
Copy files and set attributes.
config FEATURE_INSTALL_LONG_OPTIONS
config CONFIG_FEATURE_INSTALL_LONG_OPTIONS
bool "Enable long options"
default n
depends on INSTALL && GETOPT_LONG
depends on CONFIG_INSTALL && CONFIG_GETOPT_LONG
help
Support long options for the install applet.
config LENGTH
config CONFIG_LENGTH
bool "length"
default n
help
length is used to print out the length of a specified string.
config LN
config CONFIG_LN
bool "ln"
default n
help
ln is used to create hard or soft links between files.
config LOGNAME
config CONFIG_LOGNAME
bool "logname"
default n
help
logname is used to print the current user's login name.
config LS
config CONFIG_LS
bool "ls"
default n
help
ls is used to list the contents of directories.
config FEATURE_LS_FILETYPES
config CONFIG_FEATURE_LS_FILETYPES
bool "Enable filetyping options (-p and -F)"
default y
depends on LS
depends on CONFIG_LS
help
Enable the ls options (-p and -F).
config FEATURE_LS_FOLLOWLINKS
config CONFIG_FEATURE_LS_FOLLOWLINKS
bool "Enable symlinks dereferencing (-L)"
default y
depends on LS
depends on CONFIG_LS
help
Enable the ls option (-L).
config FEATURE_LS_RECURSIVE
config CONFIG_FEATURE_LS_RECURSIVE
bool "Enable recursion (-R)"
default y
depends on LS
depends on CONFIG_LS
help
Enable the ls option (-R).
config FEATURE_LS_SORTFILES
config CONFIG_FEATURE_LS_SORTFILES
bool "Sort the file names"
default y
depends on LS
depends on CONFIG_LS
help
Allow ls to sort file names alphabetically.
config FEATURE_LS_TIMESTAMPS
config CONFIG_FEATURE_LS_TIMESTAMPS
bool "Show file timestamps"
default y
depends on LS
depends on CONFIG_LS
help
Allow ls to display timestamps for files.
config FEATURE_LS_USERNAME
config CONFIG_FEATURE_LS_USERNAME
bool "Show username/groupnames"
default y
depends on LS
depends on CONFIG_LS
help
Allow ls to display username/groupname for files.
config FEATURE_LS_COLOR
config CONFIG_FEATURE_LS_COLOR
bool "Allow use of color to identify file types"
default y
depends on LS && GETOPT_LONG
depends on CONFIG_LS && CONFIG_GETOPT_LONG
help
This enables the --color option to ls.
config FEATURE_LS_COLOR_IS_DEFAULT
config CONFIG_FEATURE_LS_COLOR_IS_DEFAULT
bool "Produce colored ls output by default"
default n
depends on FEATURE_LS_COLOR
depends on CONFIG_FEATURE_LS_COLOR
help
Saying yes here will turn coloring on by default,
even if no "--color" option is given to the ls command.
@@ -391,143 +391,143 @@ config FEATURE_LS_COLOR_IS_DEFAULT
configurable, and the output may not be legible on
many output screens.
config MD5SUM
config CONFIG_MD5SUM
bool "md5sum"
default n
help
md5sum is used to print or check MD5 checksums.
config MKDIR
config CONFIG_MKDIR
bool "mkdir"
default n
help
mkdir is used to create directories with the specified names.
config FEATURE_MKDIR_LONG_OPTIONS
config CONFIG_FEATURE_MKDIR_LONG_OPTIONS
bool "Enable long options"
default n
depends on MKDIR && GETOPT_LONG
depends on CONFIG_MKDIR && CONFIG_GETOPT_LONG
help
Support long options for the mkdir applet.
config MKFIFO
config CONFIG_MKFIFO
bool "mkfifo"
default n
help
mkfifo is used to create FIFOs (named pipes).
The `mknod' program can also create FIFOs.
config MKNOD
config CONFIG_MKNOD
bool "mknod"
default n
help
mknod is used to create FIFOs or block/character special
files with the specified names.
config MV
config CONFIG_MV
bool "mv"
default n
help
mv is used to move or rename files or directories.
config FEATURE_MV_LONG_OPTIONS
config CONFIG_FEATURE_MV_LONG_OPTIONS
bool "Enable long options"
default n
depends on MV && GETOPT_LONG
depends on CONFIG_MV && CONFIG_GETOPT_LONG
help
Support long options for the mv applet.
config NICE
config CONFIG_NICE
bool "nice"
default n
help
nice runs a program with modified scheduling priority.
config NOHUP
config CONFIG_NOHUP
bool "nohup"
default n
help
run a command immune to hangups, with output to a non-tty.
config OD
config CONFIG_OD
bool "od"
default n
help
od is used to dump binary files in octal and other formats.
config PRINTENV
config CONFIG_PRINTENV
bool "printenv"
default n
help
printenv is used to print all or part of environment.
config PRINTF
config CONFIG_PRINTF
bool "printf"
default n
help
printf is used to format and print specified strings.
It's similar to `echo' except it has more options.
config PWD
config CONFIG_PWD
bool "pwd"
default n
help
pwd is used to print the current directory.
config REALPATH
config CONFIG_REALPATH
bool "realpath"
default n
help
Return the canonicalized absolute pathname.
This isn't provided by GNU shellutils, but where else does it belong.
config RM
config CONFIG_RM
bool "rm"
default n
help
rm is used to remove files or directories.
config RMDIR
config CONFIG_RMDIR
bool "rmdir"
default n
help
rmdir is used to remove empty directories.
config SEQ
config CONFIG_SEQ
bool "seq"
default n
help
print a sequence of numbers
config SHA1SUM
config CONFIG_SHA1SUM
bool "sha1sum"
default n
help
Compute and check SHA1 message digest
config SLEEP
config CONFIG_SLEEP
bool "sleep (single integer arg with no suffix)"
default n
help
sleep is used to pause for a specified number of seconds,
config FEATURE_FANCY_SLEEP
config CONFIG_FEATURE_FANCY_SLEEP
bool "Enable multiple integer args and optional time suffixes"
default n
depends on SLEEP
depends on CONFIG_SLEEP
help
Allow sleep to pause for specified minutes, hours, and days.
config SORT
config CONFIG_SORT
bool "sort"
default n
help
sort is used to sort lines of text in specified files.
config FEATURE_SORT_BIG
config CONFIG_FEATURE_SORT_BIG
bool "full SuSv3 compliant sort (Support -ktcsbdfiozgM)"
default y
depends on SORT
depends on CONFIG_SORT
help
Without this, sort only supports -r, -u, and an integer version
of -n. Selecting this adds sort keys, floating point support, and
@@ -536,69 +536,69 @@ config FEATURE_SORT_BIG
The SuSv3 sort standard is available at:
http://www.opengroup.org/onlinepubs/007904975/utilities/sort.html
config STAT
config CONFIG_STAT
bool "stat"
default n
help
display file or filesystem status.
config FEATURE_STAT_FORMAT
config CONFIG_FEATURE_STAT_FORMAT
bool "Enable custom formats (-c)"
default n
depends on STAT
depends on CONFIG_STAT
help
Without this, stat will not support the '-c format' option where
users can pass a custom format string for output. This adds about
7k to a nonstatic build on amd64.
config STTY
config CONFIG_STTY
bool "stty"
default n
help
stty is used to change and print terminal line settings.
config SUM
config CONFIG_SUM
bool "sum"
default n
help
checksum and count the blocks in a file
config SYNC
config CONFIG_SYNC
bool "sync"
default n
help
sync is used to flush filesystem buffers.
config TAIL
config CONFIG_TAIL
bool "tail"
default n
help
tail is used to print the last specified number of lines
from files.
config FEATURE_FANCY_TAIL
config CONFIG_FEATURE_FANCY_TAIL
bool "Enable extra tail options (-q, -s, and -v)"
default y
depends on TAIL
depends on CONFIG_TAIL
help
The options (-q, -s, and -v) are provided by GNU tail, but
are not specific in the SUSv3 standard.
config TEE
config CONFIG_TEE
bool "tee"
default n
help
tee is used to read from standard input and write
to standard output and files.
config FEATURE_TEE_USE_BLOCK_IO
config CONFIG_FEATURE_TEE_USE_BLOCK_IO
bool "Enable block i/o (larger/faster) instead of byte i/o."
default n
depends on TEE
depends on CONFIG_TEE
help
Enable this option for a faster tee, at expense of size.
config TEST
config CONFIG_TEST
bool "test"
default n
help
@@ -606,39 +606,39 @@ config TEST
returning an appropriate exit code. The bash shell
has test built in, ash can build it in optionally.
config FEATURE_TEST_64
config CONFIG_FEATURE_TEST_64
bool "Extend test to 64 bit"
default n
depends on TEST
depends on CONFIG_TEST
help
Enable 64-bit support in test.
config TOUCH
config CONFIG_TOUCH
bool "touch"
default n
help
touch is used to create or change the access and/or
modification timestamp of specified files.
config TR
config CONFIG_TR
bool "tr"
default n
help
tr is used to squeeze, and/or delete characters from standard
input, writing to standard output.
config FEATURE_TR_CLASSES
config CONFIG_FEATURE_TR_CLASSES
bool "Enable character classes (such as [:upper:])"
default n
depends on TR
depends on CONFIG_TR
help
Enable character classes, enabling commands such as:
tr [:upper:] [:lower:] to convert input into lowercase.
config FEATURE_TR_EQUIV
config CONFIG_FEATURE_TR_EQUIV
bool "Enable equivalence classes"
default n
depends on TR
depends on CONFIG_TR
help
Enable equivalence classes, which essentially add the enclosed
character to the current set. For instance, tr [=a=] xyz would
@@ -646,86 +646,79 @@ config FEATURE_TR_EQUIV
useful for cases when no other way of expressing a character
is possible.
config TRUE
config CONFIG_TRUE
bool "true"
default n
help
true returns an exit code of TRUE (0).
config TTY
config CONFIG_TTY
bool "tty"
default n
help
tty is used to print the name of the current terminal to
standard output.
config UNAME
config CONFIG_UNAME
bool "uname"
default n
help
uname is used to print system information.
config UNIQ
config CONFIG_UNIQ
bool "uniq"
default n
help
uniq is used to remove duplicate lines from a sorted file.
config USLEEP
config CONFIG_USLEEP
bool "usleep"
default n
help
usleep is used to pause for a specified number of microseconds.
config UUDECODE
config CONFIG_UUDECODE
bool "uudecode"
default n
help
uudecode is used to decode a uuencoded file.
config UUENCODE
config CONFIG_UUENCODE
bool "uuencode"
default n
help
uuencode is used to uuencode a file.
config WATCH
config CONFIG_WATCH
bool "watch"
default n
select DATE
select CONFIG_DATE
help
watch is used to execute a program periodically, showing
output to the screen.
config WC
config CONFIG_WC
bool "wc"
default n
help
wc is used to print the number of bytes, words, and lines,
in specified files.
config FEATURE_WC_LARGE
bool "Support very large files in wc"
default n
depends on WC
help
Use "unsigned long long" in wc for count variables
config WHO
config CONFIG_WHO
bool "who"
default n
select FEATURE_UTMP
select CONFIG_FEATURE_UTMP
help
who is used to show who is logged on.
config WHOAMI
config CONFIG_WHOAMI
bool "whoami"
default n
help
whoami is used to print the username of the current
user id (same as id -un).
config YES
config CONFIG_YES
bool "yes"
default n
help
@@ -733,46 +726,46 @@ config YES
the default string `y'.
comment "Common options for cp and mv"
depends on CP || MV
depends on CONFIG_CP || CONFIG_MV
config FEATURE_PRESERVE_HARDLINKS
config CONFIG_FEATURE_PRESERVE_HARDLINKS
bool "Preserve hard links"
default n
depends on CP || MV
depends on CONFIG_CP || CONFIG_MV
help
Allow cp and mv to preserve hard links.
comment "Common options for ls, more and telnet"
depends on LS || MORE || TELNET
depends on CONFIG_LS || CONFIG_MORE || CONFIG_TELNET
config FEATURE_AUTOWIDTH
config CONFIG_FEATURE_AUTOWIDTH
bool "Calculate terminal & column widths"
default y
depends on LS || MORE || TELNET
depends on CONFIG_LS || CONFIG_MORE || CONFIG_TELNET
help
This option allows utilities such as 'ls', 'more' and 'telnet'
to determine the width of the screen, which can allow them to
to determine the width of the screen, which can allow them to
display additional text or avoid wrapping text onto the next line.
If you leave this disabled, your utilities will be especially
If you leave this disabled, your utilities will be especially
primitive and will be unable to determine the current screen width.
comment "Common options for df, du, ls"
depends on DF || DU || LS
depends on CONFIG_DF || CONFIG_DU || CONFIG_LS
config FEATURE_HUMAN_READABLE
config CONFIG_FEATURE_HUMAN_READABLE
bool "Support for human readable output (example 13k, 23M, 235G)"
default n
depends on DF || DU || LS
depends on CONFIG_DF || CONFIG_DU || CONFIG_LS
help
Allow df, du, and ls to have human readable output.
comment "Common options for md5sum, sha1sum"
depends on MD5SUM || SHA1SUM
depends on CONFIG_MD5SUM || CONFIG_SHA1SUM
config FEATURE_MD5_SHA1_SUM_CHECK
config CONFIG_FEATURE_MD5_SHA1_SUM_CHECK
bool "Enable -c, -s and -w options"
default n
depends on MD5SUM || SHA1SUM
depends on CONFIG_MD5SUM || CONFIG_SHA1SUM
help
Enabling the -c options allows files to be checked
against pre-calculated hash values.
-84
View File
@@ -1,84 +0,0 @@
# Makefile for busybox
#
# Copyright (C) 1999-2005 by Erik Andersen <andersen@codepoet.org>
#
# Licensed under the GPL v2, see the file LICENSE in this tarball.
libs-y += libcoreutils/
lib-y:=
lib-$(CONFIG_BASENAME) += basename.o
lib-$(CONFIG_CAL) += cal.o
lib-$(CONFIG_CAT) += cat.o
lib-$(CONFIG_LESS) += cat.o # less uses it if stdout isn't a tty
lib-$(CONFIG_CATV) += catv.o
lib-$(CONFIG_CHGRP) += chgrp.o chown.o
lib-$(CONFIG_CHMOD) += chmod.o
lib-$(CONFIG_CHOWN) += chown.o
lib-$(CONFIG_CHROOT) += chroot.o
lib-$(CONFIG_CKSUM) += cksum.o
lib-$(CONFIG_CMP) += cmp.o
lib-$(CONFIG_COMM) += comm.o
lib-$(CONFIG_CP) += cp.o
lib-$(CONFIG_CUT) += cut.o
lib-$(CONFIG_DATE) += date.o
lib-$(CONFIG_DD) += dd.o
lib-$(CONFIG_DF) += df.o
lib-$(CONFIG_DIFF) += diff.o
lib-$(CONFIG_DIRNAME) += dirname.o
lib-$(CONFIG_DOS2UNIX) += dos2unix.o
lib-$(CONFIG_DU) += du.o
lib-$(CONFIG_ECHO) += echo.o
lib-$(CONFIG_ASH) += echo.o # used by ash
lib-$(CONFIG_ENV) += env.o
lib-$(CONFIG_EXPR) += expr.o
lib-$(CONFIG_FALSE) += false.o
lib-$(CONFIG_FOLD) += fold.o
lib-$(CONFIG_HEAD) += head.o
lib-$(CONFIG_HOSTID) += hostid.o
lib-$(CONFIG_ID) += id.o
lib-$(CONFIG_INSTALL) += install.o
lib-$(CONFIG_LENGTH) += length.o
lib-$(CONFIG_LN) += ln.o
lib-$(CONFIG_LOGNAME) += logname.o
lib-$(CONFIG_LS) += ls.o
lib-$(CONFIG_MD5SUM) += md5_sha1_sum.o
lib-$(CONFIG_MKDIR) += mkdir.o
lib-$(CONFIG_MKFIFO) += mkfifo.o
lib-$(CONFIG_MKNOD) += mknod.o
lib-$(CONFIG_MV) += mv.o
lib-$(CONFIG_NICE) += nice.o
lib-$(CONFIG_NOHUP) += nohup.o
lib-$(CONFIG_OD) += od.o
lib-$(CONFIG_PRINTENV) += printenv.o
lib-$(CONFIG_PRINTF) += printf.o
lib-$(CONFIG_PWD) += pwd.o
lib-$(CONFIG_REALPATH) += realpath.o
lib-$(CONFIG_RM) += rm.o
lib-$(CONFIG_RMDIR) += rmdir.o
lib-$(CONFIG_SEQ) += seq.o
lib-$(CONFIG_SHA1SUM) += md5_sha1_sum.o
lib-$(CONFIG_SLEEP) += sleep.o
lib-$(CONFIG_SORT) += sort.o
lib-$(CONFIG_STAT) += stat.o
lib-$(CONFIG_STTY) += stty.o
lib-$(CONFIG_SUM) += sum.o
lib-$(CONFIG_SYNC) += sync.o
lib-$(CONFIG_TAIL) += tail.o
lib-$(CONFIG_TEE) += tee.o
lib-$(CONFIG_TEST) += test.o
lib-$(CONFIG_ASH) += test.o # used by ash
lib-$(CONFIG_TOUCH) += touch.o
lib-$(CONFIG_TR) += tr.o
lib-$(CONFIG_TRUE) += true.o
lib-$(CONFIG_TTY) += tty.o
lib-$(CONFIG_UNAME) += uname.o
lib-$(CONFIG_UNIQ) += uniq.o
lib-$(CONFIG_USLEEP) += usleep.o
lib-$(CONFIG_UUDECODE) += uudecode.o
lib-$(CONFIG_UUENCODE) += uuencode.o
lib-$(CONFIG_WATCH) += watch.o
lib-$(CONFIG_WC) += wc.o
lib-$(CONFIG_WHO) += who.o
lib-$(CONFIG_WHOAMI) += whoami.o
lib-$(CONFIG_YES) += yes.o
+23
View File
@@ -0,0 +1,23 @@
# Makefile for busybox
#
# Copyright (C) 1999-2005 by Erik Andersen <andersen@codepoet.org>
#
# Licensed under the GPL v2, see the file LICENSE in this tarball.
ifndef top_srcdir
top_srcdir=..
endif
ifndef top_builddir
top_builddir=..
endif
srcdir=$(top_srcdir)/coreutils
SHELLUTILS_DIR:=./
include $(top_srcdir)/Rules.mak
include $(top_builddir)/.config
include $(srcdir)/Makefile.in
all: $(libraries-y)
-include $(top_builddir)/.depend
clean:
rm -f *.o *.a $(AR_TARGET)
+102
View File
@@ -0,0 +1,102 @@
# Makefile for busybox
#
# Copyright (C) 1999-2005 by Erik Andersen <andersen@codepoet.org>
#
# Licensed under the GPL v2, see the file LICENSE in this tarball.
COREUTILS_AR:=coreutils.a
ifndef $(COREUTILS_DIR)
COREUTILS_DIR:=$(top_builddir)/coreutils/
endif
srcdir=$(top_srcdir)/coreutils
COREUTILS-y:=
COREUTILS-$(CONFIG_BASENAME) += basename.o
COREUTILS-$(CONFIG_CAL) += cal.o
COREUTILS-$(CONFIG_CAT) += cat.o
COREUTILS-$(CONFIG_CATV) += catv.o
COREUTILS-$(CONFIG_CHGRP) += chgrp.o
COREUTILS-$(CONFIG_CHMOD) += chmod.o
COREUTILS-$(CONFIG_CHOWN) += chown.o
COREUTILS-$(CONFIG_CHROOT) += chroot.o
COREUTILS-$(CONFIG_CKSUM) += cksum.o
COREUTILS-$(CONFIG_CMP) += cmp.o
COREUTILS-$(CONFIG_COMM) += comm.o
COREUTILS-$(CONFIG_CP) += cp.o
COREUTILS-$(CONFIG_CUT) += cut.o
COREUTILS-$(CONFIG_DATE) += date.o
COREUTILS-$(CONFIG_DD) += dd.o
COREUTILS-$(CONFIG_DF) += df.o
COREUTILS-$(CONFIG_DIFF) += diff.o
COREUTILS-$(CONFIG_DIRNAME) += dirname.o
COREUTILS-$(CONFIG_DOS2UNIX) += dos2unix.o
COREUTILS-$(CONFIG_DU) += du.o
COREUTILS-$(CONFIG_ECHO) += echo.o
COREUTILS-$(CONFIG_ENV) += env.o
COREUTILS-$(CONFIG_EXPR) += expr.o
COREUTILS-$(CONFIG_FALSE) += false.o
COREUTILS-$(CONFIG_FOLD) += fold.o
COREUTILS-$(CONFIG_HEAD) += head.o
COREUTILS-$(CONFIG_HOSTID) += hostid.o
COREUTILS-$(CONFIG_ID) += id.o
COREUTILS-$(CONFIG_INSTALL) += install.o
COREUTILS-$(CONFIG_LENGTH) += length.o
COREUTILS-$(CONFIG_LN) += ln.o
COREUTILS-$(CONFIG_LOGNAME) += logname.o
COREUTILS-$(CONFIG_LS) += ls.o
COREUTILS-$(CONFIG_MD5SUM) += md5_sha1_sum.o
COREUTILS-$(CONFIG_MKDIR) += mkdir.o
COREUTILS-$(CONFIG_MKFIFO) += mkfifo.o
COREUTILS-$(CONFIG_MKNOD) += mknod.o
COREUTILS-$(CONFIG_MV) += mv.o
COREUTILS-$(CONFIG_NICE) += nice.o
COREUTILS-$(CONFIG_NOHUP) += nohup.o
COREUTILS-$(CONFIG_OD) += od.o
COREUTILS-$(CONFIG_PRINTENV) += printenv.o
COREUTILS-$(CONFIG_PRINTF) += printf.o
COREUTILS-$(CONFIG_PWD) += pwd.o
COREUTILS-$(CONFIG_REALPATH) += realpath.o
COREUTILS-$(CONFIG_RM) += rm.o
COREUTILS-$(CONFIG_RMDIR) += rmdir.o
COREUTILS-$(CONFIG_SEQ) += seq.o
COREUTILS-$(CONFIG_SHA1SUM) += md5_sha1_sum.o
COREUTILS-$(CONFIG_SLEEP) += sleep.o
COREUTILS-$(CONFIG_SORT) += sort.o
COREUTILS-$(CONFIG_STAT) += stat.o
COREUTILS-$(CONFIG_STTY) += stty.o
COREUTILS-$(CONFIG_SUM) += sum.o
COREUTILS-$(CONFIG_SYNC) += sync.o
COREUTILS-$(CONFIG_TAIL) += tail.o
COREUTILS-$(CONFIG_TEE) += tee.o
COREUTILS-$(CONFIG_TEST) += test.o
COREUTILS-$(CONFIG_TOUCH) += touch.o
COREUTILS-$(CONFIG_TR) += tr.o
COREUTILS-$(CONFIG_TRUE) += true.o
COREUTILS-$(CONFIG_TTY) += tty.o
COREUTILS-$(CONFIG_UNAME) += uname.o
COREUTILS-$(CONFIG_UNIQ) += uniq.o
COREUTILS-$(CONFIG_USLEEP) += usleep.o
COREUTILS-$(CONFIG_UUDECODE) += uudecode.o
COREUTILS-$(CONFIG_UUENCODE) += uuencode.o
COREUTILS-$(CONFIG_WATCH) += watch.o
COREUTILS-$(CONFIG_WC) += wc.o
COREUTILS-$(CONFIG_WHO) += who.o
COREUTILS-$(CONFIG_WHOAMI) += whoami.o
COREUTILS-$(CONFIG_YES) += yes.o
COREUTILS-y:=$(sort $(COREUTILS-y))
ifneq ($(strip $(COREUTILS-y)),)
libraries-y+=$(COREUTILS_DIR)$(COREUTILS_AR)
endif
COREUTILS_SRC-y:=$(patsubst %.o,$(srcdir)/%.c,$(COREUTILS-y))
COREUTILS_SRC-a:=$(wildcard $(srcdir)/*.c)
APPLET_SRC-y+=$(COREUTILS_SRC-y)
APPLET_SRC-a+=$(COREUTILS_SRC-a)
$(COREUTILS_DIR)$(COREUTILS_AR): $(patsubst %,$(COREUTILS_DIR)%, $(COREUTILS-y))
$(do_ar)
$(COREUTILS_DIR)%.o: $(srcdir)/%.c
$(compile.c)
+1 -1
View File
@@ -46,5 +46,5 @@ int basename_main(int argc, char **argv)
puts(s);
fflush_stdout_and_exit(EXIT_SUCCESS);
bb_fflush_stdout_and_exit(EXIT_SUCCESS);
}
+27 -11
View File
@@ -17,8 +17,20 @@
* Major size reduction... over 50% (>1.5k) on i386.
*/
#include <sys/types.h>
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include "busybox.h"
#ifdef CONFIG_LOCALE_SUPPORT
#include <locale.h>
#endif
#define THURSDAY 4 /* for reformation */
#define SATURDAY 6 /* 1 Jan 1 was a Saturday */
@@ -33,7 +45,7 @@ static const char days_in_month[] = {
};
static const char sep1752[] = {
1, 2, 14, 15, 16,
1, 2, 14, 15, 16,
17, 18, 19, 20, 21, 22, 23,
24, 25, 26, 27, 28, 29, 30
};
@@ -87,7 +99,11 @@ int cal_main(int argc, char **argv)
char day_headings[28]; /* 28 for julian, 21 for nonjulian */
char buf[40];
flags = getopt32(argc, argv, "jy");
#ifdef CONFIG_LOCALE_SUPPORT
setlocale(LC_TIME, "");
#endif
flags = bb_getopt_ulflags(argc, argv, "jy");
julian = flags & 1;
@@ -108,9 +124,9 @@ int cal_main(int argc, char **argv)
}
} else {
if (argc == 2) {
month = xatoul_range(*argv++, 1, 12);
month = bb_xgetularg10_bnd(*argv++, 1, 12);
}
year = xatoul_range(*argv, 1, 9999);
year = bb_xgetularg10_bnd(*argv, 1, 9999);
}
blank_string(day_headings, sizeof(day_headings) - 7 + 7*julian);
@@ -119,7 +135,7 @@ int cal_main(int argc, char **argv)
do {
zero_tm.tm_mon = i;
strftime(buf, sizeof(buf), "%B", &zero_tm);
month_names[i] = xstrdup(buf);
month_names[i] = bb_xstrdup(buf);
if (i < 7) {
zero_tm.tm_wday = i;
@@ -135,7 +151,7 @@ int cal_main(int argc, char **argv)
day_array(month, year, dp);
len = sprintf(lineout, "%s %d", month_names[month - 1], year);
printf("%*s%s\n%s\n",
bb_printf("%*s%s\n%s\n",
((7*julian + WEEK_LEN) - len) / 2, "",
lineout, day_headings);
for (row = 0; row < 6; row++) {
@@ -166,9 +182,9 @@ int cal_main(int argc, char **argv)
center(month_names[month + 1], week_len, HEAD_SEP);
}
center(month_names[month + 2 - julian], week_len, 0);
printf("\n%s%*s%s", day_headings, HEAD_SEP, "", day_headings);
bb_printf("\n%s%*s%s", day_headings, HEAD_SEP, "", day_headings);
if (!julian) {
printf("%*s%s", HEAD_SEP, "", day_headings);
bb_printf("%*s%s", HEAD_SEP, "", day_headings);
}
putchar('\n');
for (row = 0; row < (6*7); row += 7) {
@@ -182,7 +198,7 @@ int cal_main(int argc, char **argv)
}
}
fflush_stdout_and_exit(0);
bb_fflush_stdout_and_exit(0);
}
/*
@@ -203,7 +219,7 @@ static void day_array(int month, int year, int *days)
if ((month == 9) && (year == 1752)) {
size_t oday = 0;
j_offset = julian * 244;
do {
days[oday+2] = sep1752[oday] + j_offset;
@@ -277,7 +293,7 @@ static void center(char *str, int len, int separate)
{
int n = strlen(str);
len -= n;
printf("%*s%*s", (len/2) + n, str, (len/2) + (len % 2) + separate, "");
bb_printf("%*s%*s", (len/2) + n, str, (len/2) + (len % 2) + separate, "");
}
static void blank_string(char *buf, size_t buflen)
+14 -16
View File
@@ -4,39 +4,37 @@
*
* Copyright (C) 2003 Manuel Novoa III <mjn3@codepoet.org>
*
* Licensed under GPLv2, see file License in this tarball for details.
* Licensed under GPLv2 or later, see file License in this tarball for details.
*/
/* BB_AUDIT SUSv3 compliant */
/* http://www.opengroup.org/onlinepubs/007904975/utilities/cat.html */
#include "busybox.h"
#include <unistd.h>
int bb_cat(char **argv)
int cat_main(int argc, char **argv)
{
static char *const argv_dash[] = { "-", NULL };
FILE *f;
int retval = EXIT_SUCCESS;
if (!*argv) argv = (char**) &argv_dash;
bb_getopt_ulflags(argc, argv, "u");
argv += optind;
if (!*argv) {
*--argv = "-";
}
do {
f = fopen_or_warn_stdin(*argv);
if (f) {
off_t r = bb_copyfd_eof(fileno(f), STDOUT_FILENO);
fclose_if_not_stdin(f);
if (r >= 0)
if ((f = bb_wfopen_input(*argv)) != NULL) {
int r = bb_copyfd_eof(fileno(f), STDOUT_FILENO);
bb_fclose_nonstdin(f);
if (r >= 0) {
continue;
}
}
retval = EXIT_FAILURE;
} while (*++argv);
return retval;
}
int cat_main(int argc, char **argv)
{
getopt32(argc, argv, "u");
argv += optind;
return bb_cat(argv);
}
+20 -24
View File
@@ -11,36 +11,34 @@
* http://cm.bell-labs.com/cm/cs/doc/84/kp.ps.gz */
#include "busybox.h"
#include <unistd.h>
#include <fcntl.h>
int catv_main(int argc, char **argv)
{
int retval = EXIT_SUCCESS, fd;
unsigned flags;
int retval = EXIT_SUCCESS, fd, flags;
flags = getopt32(argc, argv, "etv");
#define CATV_OPT_e (1<<0)
#define CATV_OPT_t (1<<1)
#define CATV_OPT_v (1<<2)
flags ^= CATV_OPT_v;
flags = bb_getopt_ulflags(argc, argv, "etv");
flags ^= 4;
// Loop through files.
argv += optind;
do {
/* Read from stdin if there's nothing else to do. */
// Read from stdin if there's nothing else to do.
fd = 0;
if (*argv && 0 > (fd = xopen(*argv, O_RDONLY)))
retval = EXIT_FAILURE;
else for (;;) {
if (*argv && 0>(fd = bb_xopen(*argv, O_RDONLY))) retval = EXIT_FAILURE;
else for(;;) {
int i, res;
res = read(fd, bb_common_bufsiz1, sizeof(bb_common_bufsiz1));
if (res < 0)
retval = EXIT_FAILURE;
if (res < 1)
break;
for (i = 0; i < res; i++) {
char c = bb_common_bufsiz1[i];
if (res < 0) retval = EXIT_FAILURE;
if (res <1) break;
for (i=0; i<res; i++) {
char c=bb_common_bufsiz1[i];
if (c > 126 && (flags & CATV_OPT_v)) {
if (c > 126 && (flags & 4)) {
if (c == 127) {
printf("^?");
continue;
@@ -51,9 +49,8 @@ int catv_main(int argc, char **argv)
}
if (c < 32) {
if (c == 10) {
if (flags & CATV_OPT_e)
putchar('$');
} else if (flags & (c==9 ? CATV_OPT_t : CATV_OPT_v)) {
if (flags & 1) putchar('$');
} else if (flags & (c==9 ? 2 : 4)) {
printf("^%c", c+'@');
continue;
}
@@ -61,9 +58,8 @@ int catv_main(int argc, char **argv)
putchar(c);
}
}
if (ENABLE_FEATURE_CLEAN_UP && fd)
close(fd);
if (ENABLE_FEATURE_CLEAN_UP && fd) close(fd);
} while (*++argv);
fflush_stdout_and_exit(retval);
return retval;
}
+42 -12
View File
@@ -7,24 +7,54 @@
* Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
*/
/* BB_AUDIT SUSv3 defects - unsupported options -H, -L, and -P. */
/* BB_AUDIT GNU defects - unsupported long options. */
/* 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 <unistd.h>
#include "busybox.h"
/* FIXME - move to .h */
extern int chown_main(int argc, char **argv);
/* Don't use lchown glibc older then 2.1.x */
#if (__GLIBC__ <= 2) && (__GLIBC_MINOR__ < 1)
#define lchown chown
#endif
static int fileAction(const char *fileName, struct stat *statbuf, void* junk)
{
if (lchown(fileName, statbuf->st_uid, *((long *) junk)) == 0) {
return (TRUE);
}
bb_perror_msg("%s", fileName); /* Avoid multibyte problems. */
return (FALSE);
}
int chgrp_main(int argc, char **argv)
{
/* "chgrp [opts] abc file(s)" == "chown [opts] :abc file(s)" */
char **p = argv;
while (*++p) {
if (p[0][0] != '-') {
p[0] = xasprintf(":%s", p[0]);
break;
}
long gid;
int recursiveFlag;
int retval = EXIT_SUCCESS;
recursiveFlag = bb_getopt_ulflags(argc, argv, "R");
if (argc - optind < 2) {
bb_show_usage();
}
return chown_main(argc, argv);
argv += optind;
/* Find the selected group */
gid = get_ug_id(*argv, bb_xgetgrnam);
++argv;
/* Ok, ready to do the deed now */
do {
if (! recursive_action (*argv, recursiveFlag, FALSE, FALSE,
fileAction, fileAction, &gid)) {
retval = EXIT_FAILURE;
}
} while (*++argv);
return retval;
}
+54 -120
View File
@@ -11,147 +11,81 @@
*/
/* BB_AUDIT SUSv3 compliant */
/* BB_AUDIT GNU defects - unsupported long options. */
/* 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 <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/stat.h>
#include "busybox.h"
#define OPT_RECURSE (option_mask32 & 1)
#define OPT_VERBOSE (USE_DESKTOP(option_mask32 & 2) SKIP_DESKTOP(0))
#define OPT_CHANGED (USE_DESKTOP(option_mask32 & 4) SKIP_DESKTOP(0))
#define OPT_QUIET (USE_DESKTOP(option_mask32 & 8) SKIP_DESKTOP(0))
#define OPT_STR "R" USE_DESKTOP("vcf")
/* coreutils:
* chmod never changes the permissions of symbolic links; the chmod
* system call cannot change their permissions. This is not a problem
* since the permissions of symbolic links are never used.
* However, for each symbolic link listed on the command line, chmod changes
* the permissions of the pointed-to file. In contrast, chmod ignores
* symbolic links encountered during recursive directory traversals.
*/
static int fileAction(const char *fileName, struct stat *statbuf, void* junk, int depth)
static int fileAction(const char *fileName, struct stat *statbuf, void* junk)
{
mode_t newmode;
/* match coreutils behavior */
if (depth == 0) {
/* statbuf holds lstat result, but we need stat (follow link) */
if (stat(fileName, statbuf))
goto err;
} else { /* depth > 0: skip links */
if (S_ISLNK(statbuf->st_mode))
return TRUE;
}
newmode = statbuf->st_mode;
if (!bb_parse_mode((char *)junk, &newmode))
bb_error_msg_and_die("invalid mode: %s", (char *)junk);
if (chmod(fileName, newmode) == 0) {
if (OPT_VERBOSE
|| (OPT_CHANGED && statbuf->st_mode != newmode)
) {
printf("mode of '%s' changed to %04o (%s)\n", fileName,
newmode & 07777, bb_mode_string(newmode)+1);
}
return TRUE;
}
err:
if (!OPT_QUIET)
bb_perror_msg("%s", fileName);
return FALSE;
if (!bb_parse_mode((char *)junk, &(statbuf->st_mode)))
bb_error_msg_and_die( "invalid mode: %s", (char *)junk);
if (chmod(fileName, statbuf->st_mode) == 0)
return (TRUE);
bb_perror_msg("%s", fileName); /* Avoid multibyte problems. */
return (FALSE);
}
int chmod_main(int argc, char **argv)
int chmod_main(int ATTRIBUTE_UNUSED argc, char **argv)
{
int retval = EXIT_SUCCESS;
char *arg, **argp;
int recursiveFlag = FALSE;
int count;
char *smode;
char **p;
char *p0;
char opt = '-';
/* Convert first encountered -r into ar, -w into aw etc
* so that getopt would not eat it */
argp = argv;
while ((arg = *++argp)) {
/* Mode spec must be the first arg (sans -R etc) */
/* (protect against mishandling e.g. "chmod 644 -r") */
if (arg[0] != '-') {
arg = NULL;
break;
}
/* An option. Not a -- or valid option? */
if (arg[1] && !strchr("-"OPT_STR, arg[1])) {
arg[0] = 'a';
break;
++argv;
count = 0;
for (p = argv ; *p ; p++) {
p0 = p[0];
if (p0[0] == opt) {
if ((p0[1] == '-') && !p0[2]) {
opt = 0; /* Disable further option processing. */
continue;
}
if (p0[1] == 'R') {
char *s = p0 + 2;
while (*s == 'R') {
++s;
}
if (*s) {
bb_show_usage();
}
recursiveFlag = TRUE;
continue;
}
if (count) {
bb_show_usage();
}
}
argv[count] = p0;
++count;
}
/* Parse options */
opt_complementary = "-2";
getopt32(argc, argv, ("-"OPT_STR) + 1); /* Reuse string */
argv += optind;
argv[count] = NULL;
/* Restore option-like mode if needed */
if (arg) arg[0] = '-';
if (count < 2) {
bb_show_usage();
}
smode = *argv;
++argv;
/* Ok, ready to do the deed now */
smode = *argv++;
do {
if (!recursive_action(*argv,
OPT_RECURSE, // recurse
FALSE, // follow links: coreutils doesn't
FALSE, // depth first
fileAction, // file action
fileAction, // dir action
smode, // user data
0) // depth
) {
if (! recursive_action (*argv, recursiveFlag, TRUE, FALSE,
fileAction, fileAction, smode)) {
retval = EXIT_FAILURE;
}
} while (*++argv);
return retval;
}
/*
Security: chmod is too important and too subtle.
This is a test script (busybox chmod versus coreutils).
Run it in empty dir. Probably requires bash.
#!/bin/sh
function create() {
rm -rf $1; mkdir $1
(
cd $1 || exit 1
mkdir dir
>up
>file
>dir/file
ln -s dir linkdir
ln -s file linkfile
ln -s ../up dir/up
)
}
function tst() {
(cd test1; $t1 $1)
(cd test2; $t2 $1)
(cd test1; ls -lR) >out1
(cd test2; ls -lR) >out2
echo "chmod $1" >out.diff
if ! diff -u out1 out2 >>out.diff; then exit 1; fi
mv out.diff out1.diff
}
t1="/tmp/busybox chmod"
t2="/usr/bin/chmod"
create test1; create test2
tst "a+w file"
tst "a-w dir"
tst "a+w linkfile"
tst "a-w linkdir"
tst "-R a+w file"
tst "-R a-w dir"
tst "-R a+w linkfile"
tst "-R a-w linkdir"
tst "a-r,a+x linkfile"
*/
+38 -63
View File
@@ -7,94 +7,69 @@
* Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
*/
/* BB_AUDIT SUSv3 defects - unsupported options -H, -L, and -P. */
/* BB_AUDIT GNU defects - unsupported long options. */
/* 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 <unistd.h>
#include <string.h>
#include "busybox.h"
static struct bb_uidgid_t ugid = { -1, -1 };
static uid_t uid = -1;
static gid_t gid = -1;
static int (*chown_func)(const char *, uid_t, gid_t) = chown;
#define OPT_RECURSE (option_mask32 & 1)
#define OPT_NODEREF (option_mask32 & 2)
#define OPT_VERBOSE (USE_DESKTOP(option_mask32 & 4) SKIP_DESKTOP(0))
#define OPT_CHANGED (USE_DESKTOP(option_mask32 & 8) SKIP_DESKTOP(0))
#define OPT_QUIET (USE_DESKTOP(option_mask32 & 0x10) SKIP_DESKTOP(0))
#define OPT_STR ("Rh" USE_DESKTOP("vcf"))
/* TODO:
* -H if a command line argument is a symbolic link to a directory, traverse it
* -L traverse every symbolic link to a directory encountered
* -P do not traverse any symbolic links (default)
*/
static int fileAction(const char *fileName, struct stat *statbuf,
void ATTRIBUTE_UNUSED *junk, int depth)
void ATTRIBUTE_UNUSED *junk)
{
// TODO: -H/-L/-P
// if (depth ... && S_ISLNK(statbuf->st_mode)) ....
if (!chown_func(fileName,
(ugid.uid == (uid_t)-1) ? statbuf->st_uid : ugid.uid,
(ugid.gid == (gid_t)-1) ? statbuf->st_gid : ugid.gid)
) {
if (OPT_VERBOSE
|| (OPT_CHANGED && (statbuf->st_uid != ugid.uid || statbuf->st_gid != ugid.gid))
) {
printf("changed ownership of '%s' to %u:%u\n",
fileName, ugid.uid, ugid.gid);
}
(uid == (uid_t)-1) ? statbuf->st_uid : uid,
(gid == (gid_t)-1) ? statbuf->st_gid : gid)) {
return TRUE;
}
if (!OPT_QUIET)
bb_perror_msg("%s", fileName); /* A filename can have % in it... */
bb_perror_msg("%s", fileName); /* A filename could have % in it... */
return FALSE;
}
#define FLAG_R 1
#define FLAG_h 2
int chown_main(int argc, char **argv)
{
char *groupName;
int flags;
int retval = EXIT_SUCCESS;
char *groupName;
opt_complementary = "-2";
getopt32(argc, argv, OPT_STR);
argv += optind;
flags = bb_getopt_ulflags(argc, argv, "Rh");
if (OPT_NODEREF) chown_func = lchown;
if (flags & FLAG_h) chown_func = lchown;
/* First, check if there is a group name here */
groupName = strchr(*argv, '.'); /* deprecated? */
if (!groupName)
groupName = strchr(*argv, ':');
else
*groupName = ':'; /* replace '.' with ':' */
/* First, try parsing "user[:[group]]" */
if (!groupName) { /* "user" */
ugid.uid = get_ug_id(*argv, xuname2uid);
} else if (groupName == *argv) { /* ":group" */
ugid.gid = get_ug_id(groupName + 1, xgroup2gid);
} else {
if (!groupName[1]) /* "user:" */
*groupName = '\0';
if (!get_uidgid(&ugid, *argv, 1))
bb_error_msg_and_die("unknown user/group %s", *argv);
if (argc - optind < 2) {
bb_show_usage();
}
argv += optind;
/* First, check if there is a group name here */
if ((groupName = strchr(*argv, '.')) == NULL) {
groupName = strchr(*argv, ':');
}
/* Check for the username and groupname */
if (groupName) {
*groupName++ = '\0';
gid = get_ug_id(groupName, bb_xgetgrnam);
}
if (--groupName != *argv) uid = get_ug_id(*argv, bb_xgetpwnam);
++argv;
/* Ok, ready to do the deed now */
argv++;
do {
if (!recursive_action(*argv,
OPT_RECURSE, // recurse
FALSE, // follow links: TODO: -H/-L/-P
FALSE, // depth first
fileAction, // file action
fileAction, // dir action
NULL, // user data
0) // depth
) {
if (! recursive_action (*argv, (flags & FLAG_R), FALSE, FALSE,
fileAction, fileAction, NULL)) {
retval = EXIT_FAILURE;
}
} while (*++argv);
+5 -1
View File
@@ -9,6 +9,10 @@
/* BB_AUDIT SUSv3 N/A -- Matches GNU behavior. */
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include "busybox.h"
int chroot_main(int argc, char **argv)
@@ -21,7 +25,7 @@ int chroot_main(int argc, char **argv)
if (chroot(*argv)) {
bb_perror_msg_and_die("cannot change root directory to %s", *argv);
}
xchdir("/");
bb_xchdir("/");
++argv;
if (argc == 2) {
+22 -20
View File
@@ -3,51 +3,53 @@
* cksum - calculate the CRC32 checksum of a file
*
* Copyright (C) 2006 by Rob Sullivan, with ideas from code by Walter Harms
*
*
* Licensed under GPLv2 or later, see file LICENSE in this tarball for details. */
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include "busybox.h"
int cksum_main(int argc, char **argv)
{
uint32_t *crc32_table = crc32_filltable(1);
int cksum_main(int argc, char **argv) {
uint32_t *crc32_table = bb_crc32_filltable(1);
FILE *fp;
uint32_t crc;
long length, filesize;
int bytes_read;
char *cp;
RESERVE_CONFIG_BUFFER(buf, BUFSIZ);
int inp_stdin = (argc == optind) ? 1 : 0;
do {
fp = fopen_or_warn_stdin((inp_stdin) ? bb_msg_standard_input : *++argv);
fp = bb_wfopen_input((inp_stdin) ? bb_msg_standard_input : *++argv);
crc = 0;
length = 0;
while ((bytes_read = fread(bb_common_bufsiz1, 1, BUFSIZ, fp)) > 0) {
cp = bb_common_bufsiz1;
while ((bytes_read = fread(buf, 1, BUFSIZ, fp)) > 0) {
cp = buf;
length += bytes_read;
while (bytes_read--)
crc = (crc << 8) ^ crc32_table[((crc >> 24) ^ (*cp++)) & 0xffL];
}
filesize = length;
for (; length; length >>= 8)
crc = (crc << 8) ^ crc32_table[((crc >> 24) ^ length) & 0xffL];
crc ^= 0xffffffffL;
if (inp_stdin) {
printf("%" PRIu32 " %li\n", crc, filesize);
printf("%"PRIu32" %li\n", crc, filesize);
break;
}
printf("%" PRIu32 " %li %s\n", crc, filesize, *argv);
printf("%"PRIu32" %li %s\n", crc, filesize, *argv);
fclose(fp);
} while (*(argv + 1));
fflush_stdout_and_exit(EXIT_SUCCESS);
} while (*(argv+1));
return EXIT_SUCCESS;
}
+39 -30
View File
@@ -21,16 +21,20 @@
* in the '-l' case.
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include "busybox.h"
static FILE *cmp_xfopen_input(const char * const filename)
static FILE *cmp_xfopen_input(const char *filename)
{
FILE *fp;
fp = fopen_or_warn_stdin(filename);
if (fp)
if ((fp = bb_wfopen_input(filename)) != NULL) {
return fp;
exit(xfunc_error_retval); /* We already output an error message. */
}
exit(bb_default_error_retval); /* We already output an error message. */
}
static const char fmt_eof[] = "cmp: EOF on %s\n";
@@ -39,28 +43,32 @@ static const char fmt_differ[] = "%s %s differ: char %d, line %d\n";
static const char fmt_l_opt[] = "%.0s%.0s%d %3o %3o\n";
static const char opt_chars[] = "sl";
#define CMP_OPT_s (1<<0)
#define CMP_OPT_l (1<<1)
enum {
OPT_s = 1,
OPT_l = 2
};
int cmp_main(int argc, char **argv)
{
FILE *fp1, *fp2, *outfile = stdout;
const char *filename1, *filename2 = "-";
const char *filename1, *filename2;
const char *fmt;
int c1, c2, char_pos = 0, line_pos = 1;
unsigned opt;
int retval = 0;
int c1, c2, char_pos, line_pos;
int opt_flags;
int exit_val = 0;
xfunc_error_retval = 2; /* 1 is returned if files are different. */
bb_default_error_retval = 2; /* 1 is returned if files are different. */
opt = getopt32(argc, argv, opt_chars);
opt_flags = bb_getopt_ulflags(argc, argv, opt_chars);
if (((opt & (CMP_OPT_s|CMP_OPT_l)) == (CMP_OPT_s|CMP_OPT_l))
|| (((unsigned int)(--argc - optind)) > 1))
if ((opt_flags == 3) || (((unsigned int)(--argc - optind)) > 1)) {
bb_show_usage();
}
fp1 = cmp_xfopen_input(filename1 = *(argv += optind));
filename2 = "-";
if (*++argv) {
filename2 = *argv;
}
@@ -74,17 +82,19 @@ int cmp_main(int argc, char **argv)
return 0;
}
if (opt & CMP_OPT_l)
fmt = fmt_differ;
if (opt_flags == OPT_l) {
fmt = fmt_l_opt;
else
fmt = fmt_differ;
}
char_pos = 0;
line_pos = 1;
do {
c1 = getc(fp1);
c2 = getc(fp2);
++char_pos;
if (c1 != c2) { /* Remember: a read error may have occurred. */
retval = 1; /* But assume the files are different for now. */
if (c1 != c2) { /* Remember -- a read error may have occurred. */
exit_val = 1; /* But assume the files are different for now. */
if (c2 == EOF) {
/* We know that fp1 isn't at EOF or in an error state. But to
* save space below, things are setup to expect an EOF in fp1
@@ -95,21 +105,20 @@ int cmp_main(int argc, char **argv)
c1 = c2;
}
if (c1 == EOF) {
die_if_ferror(fp1, filename1);
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. */
xfflush_stdout();
bb_xfflush_stdout();
}
if (!(opt & CMP_OPT_s)) {
if (opt & CMP_OPT_l) {
if (opt_flags != OPT_s) {
if (opt_flags == OPT_l) {
line_pos = c1; /* line_pos is unused in the -l case. */
}
fprintf(outfile, fmt, filename1, filename2, char_pos, line_pos, c2);
if (opt) { /* This must be -l since not -s. */
/* If we encountered an EOF,
* the while check will catch it. */
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;
}
}
@@ -120,8 +129,8 @@ int cmp_main(int argc, char **argv)
}
} while (c1 != EOF);
die_if_ferror(fp1, filename1);
die_if_ferror(fp2, filename2);
bb_xferror(fp1, filename1);
bb_xferror(fp2, filename2);
fflush_stdout_and_exit(retval);
bb_fflush_stdout_and_exit(exit_val);
}
+6 -2
View File
@@ -7,6 +7,10 @@
* Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "busybox.h"
#define COMM_OPT_1 0x01
@@ -53,7 +57,7 @@ static void cmp_files(char **infiles)
int i;
for (i = 0; i < 2; ++i) {
streams[i] = ((infiles[i][0] == '=' && infiles[i][1]) ? stdin : xfopen(infiles[i], "r"));
streams[i] = ((infiles[i][0] == '=' && infiles[i][1]) ? stdin : bb_xfopen(infiles[i], "r"));
fgets(thisline[i], LINE_LEN, streams[i]);
}
@@ -112,7 +116,7 @@ int comm_main(int argc, char **argv)
{
unsigned long flags;
flags = getopt32(argc, argv, "123");
flags = bb_getopt_ulflags(argc, argv, "123");
if (optind + 2 != argc)
bb_show_usage();
+46 -28
View File
@@ -7,6 +7,8 @@
* Licensed under GPL v2 or later, see file LICENSE in this tarball for details.
*/
/* 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)
@@ -14,6 +16,15 @@
* Size reduction.
*/
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <utime.h>
#include <errno.h>
#include <dirent.h>
#include <stdlib.h>
#include <assert.h>
#include "busybox.h"
#include "libcoreutils/coreutils.h"
@@ -27,26 +38,31 @@ int cp_main(int argc, char **argv)
int d_flags;
int flags;
int status = 0;
enum {
OPT_a = 1 << (sizeof(FILEUTILS_CP_OPTSTR)-1),
OPT_r = 1 << (sizeof(FILEUTILS_CP_OPTSTR)),
OPT_P = 1 << (sizeof(FILEUTILS_CP_OPTSTR)+1),
OPT_H = 1 << (sizeof(FILEUTILS_CP_OPTSTR)+2),
OPT_L = 1 << (sizeof(FILEUTILS_CP_OPTSTR)+3),
};
// Soft- and hardlinking don't mix
// -P and -d are the same (-P is POSIX, -d is GNU)
// -r and -R are the same
// -a = -pdR
opt_complementary = "?:l--s:s--l:Pd:rR:apdR";
flags = getopt32(argc, argv, FILEUTILS_CP_OPTSTR "arPHL");
flags = bb_getopt_ulflags(argc, argv, "pdRfiarPHL");
if (flags & 32) {
flags |= (FILEUTILS_PRESERVE_STATUS | FILEUTILS_RECUR | FILEUTILS_DEREFERENCE);
}
if (flags & 64) {
/* Make -r a synonym for -R,
* -r was marked as obsolete in SUSv3, but is included for compatibility
*/
flags |= FILEUTILS_RECUR;
}
if (flags & 128) {
/* Make -P a synonym for -d,
* -d is the GNU option while -P is the POSIX 2003 option
*/
flags |= FILEUTILS_DEREFERENCE;
}
/* Default behavior of cp is to dereference, so we don't have to do
* anything special when we are given -L.
* The behavior of -H is *almost* like -L, but not quite, so let's
* just ignore it too for fun.
if (flags & OPT_L) ...
if (flags & OPT_H) ... // deref command-line params only
if (flags & 256 || flags & 512) {
;
}
*/
flags ^= FILEUTILS_DEREFERENCE; /* The sense of this flag was reversed. */
@@ -61,32 +77,34 @@ int cp_main(int argc, char **argv)
/* If there are only two arguments and... */
if (optind + 2 == argc) {
s_flags = cp_mv_stat2(*argv, &source_stat,
(flags & FILEUTILS_DEREFERENCE) ? stat : lstat);
if (s_flags < 0)
return EXIT_FAILURE;
d_flags = cp_mv_stat(last, &dest_stat);
if (d_flags < 0)
return EXIT_FAILURE;
(flags & FILEUTILS_DEREFERENCE) ? stat : lstat);
if ((s_flags < 0) || ((d_flags = cp_mv_stat(last, &dest_stat)) < 0)) {
exit(EXIT_FAILURE);
}
/* ...if neither is a directory or... */
if ( !((s_flags | d_flags) & 2) ||
/* ...recursing, the 1st is a directory, and the 2nd doesn't exist... */
((flags & FILEUTILS_RECUR) && (s_flags & 2) && !d_flags)
/* ((flags & FILEUTILS_RECUR) && (s_flags & 2) && !d_flags) */
/* Simplify the above since FILEUTILS_RECUR >> 1 == 2. */
((((flags & FILEUTILS_RECUR) >> 1) & s_flags) && !d_flags)
) {
/* ...do a simple copy. */
dest = xstrdup(last);
dest = last;
goto DO_COPY; /* Note: optind+2==argc implies argv[1]==last below. */
}
}
do {
dest = concat_path_file(last, bb_get_last_path_component(*argv));
DO_COPY:
DO_COPY:
if (copy_file(*argv, dest, flags) < 0) {
status = 1;
}
free((void*)dest);
} while (*++argv != last);
if (*++argv == last) {
break;
}
free((void *) dest);
} while (1);
return status;
exit(status);
}
+262 -216
View File
@@ -4,22 +4,28 @@
*
* Copyright (C) 1999,2000,2001 by Lineo, inc.
* Written by Mark Whitley <markw@codepoet.org>
* debloated by Bernhard Fischer
*
* Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <limits.h>
#include "busybox.h"
/* option vars */
static const char optstring[] = "b:c:f:d:sn";
#define CUT_OPT_BYTE_FLGS (1<<0)
#define CUT_OPT_CHAR_FLGS (1<<1)
#define CUT_OPT_FIELDS_FLGS (1<<2)
#define CUT_OPT_DELIM_FLGS (1<<3)
#define CUT_OPT_SUPPRESS_FLGS (1<<4)
static char delim = '\t'; /* delimiter, default is tab */
#define OPT_BYTE_FLGS 1
#define OPT_CHAR_FLGS 2
#define OPT_FIELDS_FLGS 4
#define OPT_DELIM_FLGS 8
#define OPT_SUPRESS_FLGS 16
static char part; /* (b)yte, (c)har, (f)ields */
static unsigned int supress_non_delimited_lines;
static char delim = '\t'; /* delimiter, default is tab */
struct cut_list {
int startpos;
@@ -32,255 +38,295 @@ enum {
NON_RANGE = -1
};
/* growable array holding a series of lists */
static struct cut_list *cut_lists;
static unsigned int nlists; /* number of elements in above list */
static struct cut_list *cut_lists = NULL; /* growable array holding a series of lists */
static unsigned int nlists = 0; /* number of elements in above list */
static int cmpfunc(const void *a, const void *b)
{
return (((struct cut_list *) a)->startpos -
((struct cut_list *) b)->startpos);
struct cut_list *la = (struct cut_list *)a;
struct cut_list *lb = (struct cut_list *)b;
if (la->startpos > lb->startpos)
return 1;
if (la->startpos < lb->startpos)
return -1;
return 0;
}
/*
* parse_lists() - parses a list and puts values into startpos and endpos.
* valid list formats: N, N-, N-M, -M
* more than one list can be separated by commas
*/
static void parse_lists(char *lists)
{
char *ltok = NULL;
char *ntok = NULL;
char *junk;
int s = 0, e = 0;
/* take apart the lists, one by one (they are separated with commas */
while ((ltok = strsep(&lists, ",")) != NULL) {
/* it's actually legal to pass an empty list */
if (strlen(ltok) == 0)
continue;
/* get the start pos */
ntok = strsep(&ltok, "-");
if (ntok == NULL) {
fprintf(stderr, "Help ntok is null for starting position! What do I do?\n");
} else if (strlen(ntok) == 0) {
s = BOL;
} else {
s = strtoul(ntok, &junk, 10);
if(*junk != '\0' || s < 0)
bb_error_msg_and_die("invalid byte or field list");
/* account for the fact that arrays are zero based, while the user
* expects the first char on the line to be char # 1 */
if (s != 0)
s--;
}
/* get the end pos */
ntok = strsep(&ltok, "-");
if (ntok == NULL) {
e = NON_RANGE;
} else if (strlen(ntok) == 0) {
e = EOL;
} else {
e = strtoul(ntok, &junk, 10);
if(*junk != '\0' || e < 0)
bb_error_msg_and_die("invalid byte or field list");
/* if the user specified and end position of 0, that means "til the
* end of the line */
if (e == 0)
e = INT_MAX;
e--; /* again, arrays are zero based, lines are 1 based */
if (e == s)
e = NON_RANGE;
}
/* if there's something left to tokenize, the user past an invalid list */
if (ltok)
bb_error_msg_and_die("invalid byte or field list");
/* add the new list */
cut_lists = xrealloc(cut_lists, sizeof(struct cut_list) * (++nlists));
cut_lists[nlists-1].startpos = s;
cut_lists[nlists-1].endpos = e;
}
/* make sure we got some cut positions out of all that */
if (nlists == 0)
bb_error_msg_and_die("missing list of positions");
/* 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 */
qsort(cut_lists, nlists, sizeof(struct cut_list), cmpfunc);
}
static void cut_file(FILE * file)
static void cut_line_by_chars(const char *line)
{
int c, l;
/* set up a list so we can keep track of what's been printed */
char *printed = xcalloc(strlen(line), sizeof(char));
/* print the chars specified in each cut list */
for (c = 0; c < nlists; c++) {
l = cut_lists[c].startpos;
while (l < strlen(line)) {
if (!printed[l]) {
putchar(line[l]);
printed[l] = 'X';
}
l++;
if (cut_lists[c].endpos == NON_RANGE || l > cut_lists[c].endpos)
break;
}
}
putchar('\n'); /* cuz we were handed a chomped line */
free(printed);
}
static void cut_line_by_fields(char *line)
{
int c, f;
int ndelim = -1; /* zero-based / one-based problem */
int nfields_printed = 0;
char *field = NULL;
char d[2] = { delim, 0 };
char *printed;
/* test the easy case first: does this line contain any delimiters? */
if (strchr(line, delim) == NULL) {
if (!supress_non_delimited_lines)
puts(line);
return;
}
/* set up a list so we can keep track of what's been printed */
printed = xcalloc(strlen(line), sizeof(char));
/* process each list on this line, for as long as we've got a line to process */
for (c = 0; c < nlists && line; c++) {
f = cut_lists[c].startpos;
do {
/* find the field we're looking for */
while (line && ndelim < f) {
field = strsep(&line, d);
ndelim++;
}
/* we found it, and it hasn't been printed yet */
if (field && ndelim == f && !printed[ndelim]) {
/* if this isn't our first time through, we need to print the
* delimiter after the last field that was printed */
if (nfields_printed > 0)
putchar(delim);
fputs(field, stdout);
printed[ndelim] = 'X';
nfields_printed++;
}
f++;
/* keep going as long as we have a line to work with, this is a
* list, and we're not at the end of that list */
} while (line && cut_lists[c].endpos != NON_RANGE && f <= cut_lists[c].endpos);
}
/* if we printed anything at all, we need to finish it with a newline cuz
* we were handed a chomped line */
putchar('\n');
free(printed);
}
static void cut_file_by_lines(const char *line, unsigned int linenum)
{
static int c = 0;
static int l = -1;
/* I can't initialize this above cuz the "initializer isn't
* constant" *sigh* */
if (l == -1)
l = cut_lists[c].startpos;
/* get out if we have no more lists to process or if the lines are lower
* than what we're interested in */
if (c >= nlists || linenum < l)
return;
/* if the line we're looking for is lower than the one we were passed, it
* means we displayed it already, so move on */
while (l < linenum) {
l++;
/* move on to the next list if we're at the end of this one */
if (cut_lists[c].endpos == NON_RANGE || l > cut_lists[c].endpos) {
c++;
/* get out if there's no more lists to process */
if (c >= nlists)
return;
l = cut_lists[c].startpos;
/* get out if the current line is lower than the one we just became
* interested in */
if (linenum < l)
return;
}
}
/* If we made it here, it means we've found the line we're looking for, so print it */
puts(line);
}
/*
* snippy-snip
*/
static void cut_file(FILE *file)
{
char *line = NULL;
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 */
while ((line = xmalloc_getline(file)) != NULL) {
/* set up a list so we can keep track of what's been printed */
char * printed = xzalloc(strlen(line) * sizeof(char));
char * orig_line = line;
unsigned int cl_pos = 0;
int spos;
while ((line = bb_get_chomped_line_from_file(file)) != NULL) {
/* cut based on chars/bytes XXX: only works when sizeof(char) == byte */
if (option_mask32 & (CUT_OPT_CHAR_FLGS | CUT_OPT_BYTE_FLGS)) {
/* print the chars specified in each cut list */
for (; cl_pos < nlists; cl_pos++) {
spos = cut_lists[cl_pos].startpos;
while (spos < strlen(line)) {
if (!printed[spos]) {
printed[spos] = 'X';
putchar(line[spos]);
}
spos++;
if (spos > cut_lists[cl_pos].endpos
|| cut_lists[cl_pos].endpos == NON_RANGE)
break;
}
}
} else if (delim == '\n') { /* cut by lines */
spos = cut_lists[cl_pos].startpos;
if ((part & (OPT_CHAR_FLGS | OPT_BYTE_FLGS)))
cut_line_by_chars(line);
/* get out if we have no more lists to process or if the lines
* are lower than what we're interested in */
if (linenum < spos || cl_pos >= nlists)
goto next_line;
/* if the line we're looking for is lower than the one we were
* passed, it means we displayed it already, so move on */
while (spos < linenum) {
spos++;
/* go to the next list if we're at the end of this one */
if (spos > cut_lists[cl_pos].endpos
|| cut_lists[cl_pos].endpos == NON_RANGE) {
cl_pos++;
/* get out if there's no more lists to process */
if (cl_pos >= nlists)
goto next_line;
spos = cut_lists[cl_pos].startpos;
/* get out if the current line is lower than the one
* we just became interested in */
if (linenum < spos)
goto next_line;
}
}
/* If we made it here, it means we've found the line we're
* looking for, so print it */
puts(line);
goto next_line;
} else { /* cut by fields */
int ndelim = -1; /* zero-based / one-based problem */
int nfields_printed = 0;
char *field = NULL;
const char delimiter[2] = { delim, 0 };
/* does this line contain any delimiters? */
if (strchr(line, delim) == NULL) {
if (!(option_mask32 & CUT_OPT_SUPPRESS_FLGS))
puts(line);
goto next_line;
}
/* process each list on this line, for as long as we've got
* a line to process */
for (; cl_pos < nlists && line; cl_pos++) {
spos = cut_lists[cl_pos].startpos;
do {
/* find the field we're looking for */
while (line && ndelim < spos) {
field = strsep(&line, delimiter);
ndelim++;
}
/* we found it, and it hasn't been printed yet */
if (field && ndelim == spos && !printed[ndelim]) {
/* if this isn't our first time through, we need to
* print the delimiter after the last field that was
* printed */
if (nfields_printed > 0)
putchar(delim);
fputs(field, stdout);
printed[ndelim] = 'X';
nfields_printed++; /* shouldn't overflow.. */
}
spos++;
/* keep going as long as we have a line to work with,
* this is a list, and we're not at the end of that
* list */
} while (spos <= cut_lists[cl_pos].endpos && line
&& cut_lists[cl_pos].endpos != NON_RANGE);
}
/* cut based on fields */
else {
if (delim == '\n')
cut_file_by_lines(line, linenum);
else
cut_line_by_fields(line);
}
/* if we printed anything at all, we need to finish it with a
* newline cuz we were handed a chomped line */
putchar('\n');
next_line:
linenum++;
free(printed);
free(orig_line);
free(line);
}
}
static const char _op_on_field[] = " only when operating on fields";
int cut_main(int argc, char **argv)
{
char *sopt, *ltok;
unsigned long opt;
char *sopt, *sdopt;
opt_complementary = "b--bcf:c--bcf:f--bcf";
getopt32(argc, argv, optstring, &sopt, &sopt, &sopt, &ltok);
// argc -= optind;
argv += optind;
if (!(option_mask32 & (CUT_OPT_BYTE_FLGS | CUT_OPT_CHAR_FLGS | CUT_OPT_FIELDS_FLGS)))
bb_error_msg_and_die("expected a list of bytes, characters, or fields");
if (option_mask32 & BB_GETOPT_ERROR)
bb_opt_complementally = "b--bcf:c--bcf:f--bcf";
opt = bb_getopt_ulflags(argc, argv, optstring, &sopt, &sopt, &sopt, &sdopt);
part = opt & (OPT_BYTE_FLGS|OPT_CHAR_FLGS|OPT_FIELDS_FLGS);
if(part == 0)
bb_error_msg_and_die("you must specify a list of bytes, characters, or fields");
if(opt & BB_GETOPT_ERROR)
bb_error_msg_and_die("only one type of list may be specified");
if (option_mask32 & CUT_OPT_DELIM_FLGS) {
if (strlen(ltok) > 1) {
parse_lists(sopt);
if((opt & (OPT_DELIM_FLGS))) {
if (strlen(sdopt) > 1) {
bb_error_msg_and_die("the delimiter must be a single character");
}
delim = ltok[0];
delim = sdopt[0];
}
supress_non_delimited_lines = opt & OPT_SUPRESS_FLGS;
/* non-field (char or byte) cutting has some special handling */
if (!(option_mask32 & CUT_OPT_FIELDS_FLGS)) {
if (option_mask32 & CUT_OPT_SUPPRESS_FLGS) {
bb_error_msg_and_die
("suppressing non-delimited lines makes sense%s",
_op_on_field);
if (part != OPT_FIELDS_FLGS) {
if (supress_non_delimited_lines) {
bb_error_msg_and_die("suppressing non-delimited lines makes sense"
" only when operating on fields");
}
if (delim != '\t') {
bb_error_msg_and_die
("a delimiter may be specified%s", _op_on_field);
bb_error_msg_and_die("a delimiter may be specified only when operating on fields");
}
}
/*
* parse list and put values into startpos and endpos.
* valid list formats: N, N-, N-M, -M
* more than one list can be separated by commas
*/
{
char *ntok;
int s = 0, e = 0;
/* take apart the lists, one by one (they are separated with commas */
while ((ltok = strsep(&sopt, ",")) != NULL) {
/* it's actually legal to pass an empty list */
if (strlen(ltok) == 0)
continue;
/* get the start pos */
ntok = strsep(&ltok, "-");
if (ntok == NULL) {
bb_error_msg
("internal error: ntok is null for start pos!?\n");
} else if (strlen(ntok) == 0) {
s = BOL;
} else {
s = xatoi_u(ntok);
/* account for the fact that arrays are zero based, while
* the user expects the first char on the line to be char #1 */
if (s != 0)
s--;
}
/* get the end pos */
ntok = strsep(&ltok, "-");
if (ntok == NULL) {
e = NON_RANGE;
} else if (strlen(ntok) == 0) {
e = EOL;
} else {
e = xatoi_u(ntok);
/* if the user specified and end position of 0, that means "til the
* end of the line */
if (e == 0)
e = EOL;
e--; /* again, arrays are zero based, lines are 1 based */
if (e == s)
e = NON_RANGE;
}
/* if there's something left to tokenize, the user passed
* an invalid list */
if (ltok)
bb_error_msg_and_die("invalid byte or field list");
/* add the new list */
cut_lists = xrealloc(cut_lists, sizeof(struct cut_list) * (++nlists));
cut_lists[nlists-1].startpos = s;
cut_lists[nlists-1].endpos = e;
}
/* make sure we got some cut positions out of all that */
if (nlists == 0)
bb_error_msg_and_die("missing list of positions");
/* 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
*/
qsort(cut_lists, nlists, sizeof(struct cut_list), cmpfunc);
}
/* argv[0..argc-1] should be names of file to process. If no
/* argv[(optind)..(argc-1)] should be names of file to process. If no
* files were specified or '-' was specified, take input from stdin.
* Otherwise, we process all the files specified. */
if (argv[0] == NULL || LONE_DASH(argv[0])) {
if (argv[optind] == NULL || (strcmp(argv[optind], "-") == 0)) {
cut_file(stdin);
} else {
}
else {
int i;
FILE *file;
do {
file = fopen_or_warn(argv[0], "r");
if (file) {
for (i = optind; i < argc; i++) {
file = bb_wfopen(argv[i], "r");
if(file) {
cut_file(file);
fclose(file);
}
} while (*++argv);
}
}
if (ENABLE_FEATURE_CLEAN_UP)
free(cut_lists);
return EXIT_SUCCESS;
}
+137 -132
View File
@@ -5,17 +5,14 @@
* by Matthew Grant <grantma@anathoth.gen.nz>
*
* iso-format handling added by Robert Griebl <griebl@gmx.de>
* bugfixes and cleanup by Bernhard Fischer
*
* Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
*/
#include "busybox.h"
/* This 'date' command supports only 2 time setting formats,
all the GNU strftime stuff (its in libc, lets use it),
setting time using UTC and displaying it, as well as
an RFC 2822 compliant date output for shell scripting
setting time using UTC and displaying int, as well as
an RFC 822 complient date output for shell scripting
mail commands */
/* Input parsing code is always bulky - used heavy duty libc stuff as
@@ -23,6 +20,13 @@
/* Default input handling to save surprising some people */
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>
#include <time.h>
#include <stdio.h>
#include <string.h>
#include "busybox.h"
#define DATE_OPT_RFC2822 0x01
#define DATE_OPT_SET 0x02
@@ -32,51 +36,119 @@
#define DATE_OPT_TIMESPEC 0x20
#define DATE_OPT_HINT 0x40
static void xputenv(char *s)
static struct tm *date_conv_time(struct tm *tm_time, const char *t_string)
{
if (putenv(s) != 0)
bb_error_msg_and_die(bb_msg_memory_exhausted);
int nr;
char *cp;
nr = sscanf(t_string, "%2d%2d%2d%2d%d", &(tm_time->tm_mon),
&(tm_time->tm_mday), &(tm_time->tm_hour), &(tm_time->tm_min),
&(tm_time->tm_year));
if (nr < 4 || nr > 5) {
bb_error_msg_and_die(bb_msg_invalid_date, t_string);
}
cp = strchr(t_string, '.');
if (cp) {
nr = sscanf(cp + 1, "%2d", &(tm_time->tm_sec));
if (nr != 1) {
bb_error_msg_and_die(bb_msg_invalid_date, t_string);
}
}
/* correct for century - minor Y2K problem here? */
if (tm_time->tm_year >= 1900) {
tm_time->tm_year -= 1900;
}
/* adjust date */
tm_time->tm_mon -= 1;
return (tm_time);
}
static void maybe_set_utc(int opt)
/* The new stuff for LRP */
static struct tm *date_conv_ftime(struct tm *tm_time, const char *t_string)
{
if (opt & DATE_OPT_UTC)
xputenv("TZ=UTC0");
struct tm t;
/* Parse input and assign appropriately to tm_time */
if (t = *tm_time, sscanf(t_string, "%d:%d:%d", &t.tm_hour, &t.tm_min,
&t.tm_sec) == 3) {
/* no adjustments needed */
} else if (t = *tm_time, sscanf(t_string, "%d:%d", &t.tm_hour,
&t.tm_min) == 2) {
/* no adjustments needed */
} else if (t = *tm_time, sscanf(t_string, "%d.%d-%d:%d:%d", &t.tm_mon,
&t.tm_mday, &t.tm_hour,
&t.tm_min, &t.tm_sec) == 5) {
/* Adjust dates from 1-12 to 0-11 */
t.tm_mon -= 1;
} else if (t = *tm_time, sscanf(t_string, "%d.%d-%d:%d", &t.tm_mon,
&t.tm_mday,
&t.tm_hour, &t.tm_min) == 4) {
/* Adjust dates from 1-12 to 0-11 */
t.tm_mon -= 1;
} else if (t = *tm_time, sscanf(t_string, "%d.%d.%d-%d:%d:%d", &t.tm_year,
&t.tm_mon, &t.tm_mday,
&t.tm_hour, &t.tm_min,
&t.tm_sec) == 6) {
t.tm_year -= 1900; /* Adjust years */
t.tm_mon -= 1; /* Adjust dates from 1-12 to 0-11 */
} else if (t = *tm_time, sscanf(t_string, "%d.%d.%d-%d:%d", &t.tm_year,
&t.tm_mon, &t.tm_mday,
&t.tm_hour, &t.tm_min) == 5) {
t.tm_year -= 1900; /* Adjust years */
t.tm_mon -= 1; /* Adjust dates from 1-12 to 0-11 */
} else {
bb_error_msg_and_die(bb_msg_invalid_date, t_string);
}
*tm_time = t;
return (tm_time);
}
int date_main(int argc, char **argv)
{
time_t tm;
struct tm tm_time;
unsigned opt;
int ifmt = -1;
char *date_str = NULL;
char *date_fmt = NULL;
int set_time;
int utc;
time_t tm;
unsigned long opt;
struct tm tm_time;
char *filename = NULL;
int ifmt = 0;
char *isofmt_arg;
char *hintfmt_arg;
opt_complementary = "?:d--s:s--d"
USE_FEATURE_DATE_ISOFMT(":R--I:I--R");
opt = getopt32(argc, argv, "Rs:ud:r:"
USE_FEATURE_DATE_ISOFMT("I::D:"),
&date_str, &date_str, &filename
USE_FEATURE_DATE_ISOFMT(, &isofmt_arg, &hintfmt_arg));
maybe_set_utc(opt);
bb_opt_complementally = "?:d--s:s--d";
opt = bb_getopt_ulflags(argc, argv, "Rs:ud:r:"
USE_FEATURE_DATE_ISOFMT("I::D:"),
&date_str, &date_str, &filename
USE_FEATURE_DATE_ISOFMT(, &isofmt_arg, &hintfmt_arg));
set_time = opt & DATE_OPT_SET;
utc = opt & DATE_OPT_UTC;
if (utc && putenv("TZ=UTC0") != 0) {
bb_error_msg_and_die(bb_msg_memory_exhausted);
}
if (ENABLE_FEATURE_DATE_ISOFMT && (opt & DATE_OPT_TIMESPEC)) {
if(ENABLE_FEATURE_DATE_ISOFMT && (opt & DATE_OPT_TIMESPEC)) {
if (!isofmt_arg) {
ifmt = 0; /* default is date */
ifmt = 1;
} else {
const char * const isoformats[] =
{"date", "hours", "minutes", "seconds"};
for (ifmt = 0; ifmt < 4; ifmt++)
if (!strcmp(isofmt_arg, isoformats[ifmt])) {
char *isoformats[]={"date","hours","minutes","seconds"};
for(ifmt = 4; ifmt;)
if(!strcmp(isofmt_arg,isoformats[--ifmt]))
break;
}
if (ifmt == 4) /* parse error */
bb_show_usage();
}
if (!ifmt) {
bb_show_usage();
}
}
@@ -84,19 +156,18 @@ int date_main(int argc, char **argv)
if ((date_fmt == NULL) && (optind < argc) && (argv[optind][0] == '+')) {
date_fmt = &argv[optind][1]; /* Skip over the '+' */
} else if (date_str == NULL) {
opt |= DATE_OPT_SET;
set_time = 1;
date_str = argv[optind];
}
/* Now we have parsed all the information except the date format
which depends on whether the clock is being set or read */
if (filename) {
if(filename) {
struct stat statbuf;
xstat(filename, &statbuf);
tm = statbuf.st_mtime;
} else
time(&tm);
xstat(filename,&statbuf);
tm=statbuf.st_mtime;
} else time(&tm);
memcpy(&tm_time, localtime(&tm), sizeof(tm_time));
/* Zero out fields - take her back to midnight! */
if (date_str != NULL) {
@@ -108,64 +179,9 @@ int date_main(int argc, char **argv)
if (ENABLE_FEATURE_DATE_ISOFMT && (opt & DATE_OPT_HINT)) {
strptime(date_str, hintfmt_arg, &tm_time);
} else if (strchr(date_str, ':') != NULL) {
/* Parse input and assign appropriately to tm_time */
if (sscanf(date_str, "%d:%d:%d", &tm_time.tm_hour, &tm_time.tm_min,
&tm_time.tm_sec) == 3) {
/* no adjustments needed */
} else if (sscanf(date_str, "%d:%d", &tm_time.tm_hour,
&tm_time.tm_min) == 2) {
/* no adjustments needed */
} else if (sscanf(date_str, "%d.%d-%d:%d:%d", &tm_time.tm_mon,
&tm_time.tm_mday, &tm_time.tm_hour,
&tm_time.tm_min, &tm_time.tm_sec) == 5) {
/* Adjust dates from 1-12 to 0-11 */
tm_time.tm_mon -= 1;
} else if (sscanf(date_str, "%d.%d-%d:%d", &tm_time.tm_mon,
&tm_time.tm_mday,
&tm_time.tm_hour, &tm_time.tm_min) == 4) {
/* Adjust dates from 1-12 to 0-11 */
tm_time.tm_mon -= 1;
} else if (sscanf(date_str, "%d.%d.%d-%d:%d:%d", &tm_time.tm_year,
&tm_time.tm_mon, &tm_time.tm_mday,
&tm_time.tm_hour, &tm_time.tm_min,
&tm_time.tm_sec) == 6) {
tm_time.tm_year -= 1900; /* Adjust years */
tm_time.tm_mon -= 1; /* Adjust dates from 1-12 to 0-11 */
} else if (sscanf(date_str, "%d.%d.%d-%d:%d", &tm_time.tm_year,
&tm_time.tm_mon, &tm_time.tm_mday,
&tm_time.tm_hour, &tm_time.tm_min) == 5) {
tm_time.tm_year -= 1900; /* Adjust years */
tm_time.tm_mon -= 1; /* Adjust dates from 1-12 to 0-11 */
} else {
bb_error_msg_and_die(bb_msg_invalid_date, date_str);
}
date_conv_ftime(&tm_time, date_str);
} else {
int nr;
char *cp;
nr = sscanf(date_str, "%2d%2d%2d%2d%d", &tm_time.tm_mon,
&tm_time.tm_mday, &tm_time.tm_hour, &tm_time.tm_min,
&tm_time.tm_year);
if (nr < 4 || nr > 5) {
bb_error_msg_and_die(bb_msg_invalid_date, date_str);
}
cp = strchr(date_str, '.');
if (cp) {
nr = sscanf(cp + 1, "%2d", &tm_time.tm_sec);
if (nr != 1) {
bb_error_msg_and_die(bb_msg_invalid_date, date_str);
}
}
/* correct for century - minor Y2K problem here? */
if (tm_time.tm_year >= 1900) {
tm_time.tm_year -= 1900;
}
/* adjust date */
tm_time.tm_mon -= 1;
date_conv_time(&tm_time, date_str);
}
/* Correct any day of week and day of year etc. fields */
@@ -174,10 +190,12 @@ int date_main(int argc, char **argv)
if (tm < 0) {
bb_error_msg_and_die(bb_msg_invalid_date, date_str);
}
maybe_set_utc(opt);
if (utc && putenv("TZ=UTC0") != 0) {
bb_error_msg_and_die(bb_msg_memory_exhausted);
}
/* if setting time, set it */
if ((opt & DATE_OPT_SET) && stime(&tm) < 0) {
if (set_time && stime(&tm) < 0) {
bb_perror_msg("cannot set date");
}
}
@@ -185,46 +203,33 @@ int date_main(int argc, char **argv)
/* Display output */
/* Deal with format string */
if (date_fmt == NULL) {
int i;
date_fmt = xzalloc(32);
if (ENABLE_FEATURE_DATE_ISOFMT && ifmt >= 0) {
strcpy(date_fmt, "%Y-%m-%d");
if (ifmt > 0) {
i = 8;
date_fmt[i++] = 'T';
date_fmt[i++] = '%';
date_fmt[i++] = 'H';
if (ifmt > 1) {
date_fmt[i++] = ':';
date_fmt[i++] = '%';
date_fmt[i++] = 'M';
}
if (ifmt > 2) {
date_fmt[i++] = ':';
date_fmt[i++] = '%';
date_fmt[i++] = 'S';
}
format_utc:
date_fmt[i++] = '%';
date_fmt[i] = (opt & DATE_OPT_UTC) ? 'Z' : 'z';
}
} else if (opt & DATE_OPT_RFC2822) {
/* Undo busybox.c for date -R */
if (ENABLE_LOCALE_SUPPORT)
setlocale(LC_TIME, "C");
strcpy(date_fmt, "%a, %d %b %Y %H:%M:%S ");
i = 22;
goto format_utc;
} else /* default case */
date_fmt = "%a %b %e %H:%M:%S %Z %Y";
}
/* Start with the default case */
date_fmt = (opt & DATE_OPT_RFC2822 ?
(utc ? "%a, %d %b %Y %H:%M:%S GMT" :
"%a, %d %b %Y %H:%M:%S %z") :
"%a %b %e %H:%M:%S %Z %Y");
if (ENABLE_FEATURE_DATE_ISOFMT) {
if (ifmt == 4)
date_fmt = utc ? "%Y-%m-%dT%H:%M:%SZ" : "%Y-%m-%dT%H:%M:%S%z";
else if (ifmt == 3)
date_fmt = utc ? "%Y-%m-%dT%H:%MZ" : "%Y-%m-%dT%H:%M%z";
else if (ifmt == 2)
date_fmt = utc ? "%Y-%m-%dT%HZ" : "%Y-%m-%dT%H%z";
else if (ifmt == 1)
date_fmt = "%Y-%m-%d";
}
}
if (*date_fmt == '\0') {
/* With no format string, just print a blank line */
*bb_common_bufsiz1 = 0;
*bb_common_bufsiz1=0;
} else {
/* Handle special conversions */
if (strncmp(date_fmt, "%f", 2) == 0) {
+97 -119
View File
@@ -8,8 +8,15 @@
* Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
*/
#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#include <signal.h> // For FEATURE_DD_SIGNAL_HANDLING
#include "busybox.h"
#include <signal.h> /* For FEATURE_DD_SIGNAL_HANDLING */
static const struct suffix_mult dd_suffixes[] = {
{ "c", 1 },
@@ -17,7 +24,6 @@ static const struct suffix_mult dd_suffixes[] = {
{ "b", 512 },
{ "kD", 1000 },
{ "k", 1024 },
{ "K", 1024 }, // compat with coreutils dd
{ "MD", 1000000 },
{ "M", 1048576 },
{ "GD", 1000000000 },
@@ -25,109 +31,87 @@ static const struct suffix_mult dd_suffixes[] = {
{ NULL, 0 }
};
static off_t out_full, out_part, in_full, in_part;
static size_t out_full;
static size_t out_part;
static size_t in_full;
static size_t in_part;
static void dd_output_status(int ATTRIBUTE_UNUSED cur_signal)
static void dd_output_status(int cur_signal)
{
fprintf(stderr, "%"OFF_FMT"d+%"OFF_FMT"d records in\n"
"%"OFF_FMT"d+%"OFF_FMT"d records out\n",
in_full, in_part,
out_full, out_part);
fprintf(stderr, "%ld+%ld records in\n%ld+%ld records out\n",
(long)in_full, (long)in_part,
(long)out_full, (long)out_part);
}
static ssize_t full_write_or_warn(int fd, const void *buf, size_t len,
const char* filename)
{
ssize_t n = full_write(fd, buf, len);
if (n < 0)
bb_perror_msg("writing '%s'", filename);
return n;
}
#if ENABLE_LFS
#define XATOU_SFX xatoull_sfx
#else
#define XATOU_SFX xatoul_sfx
#endif
int dd_main(int argc, char **argv)
{
enum {
sync_flag = 1 << 0,
noerror = 1 << 1,
trunc_flag = 1 << 2,
twobufs_flag = 1 << 3,
};
int flags = trunc_flag;
size_t oc = 0, ibs = 512, obs = 512;
ssize_t n, w;
off_t seek = 0, skip = 0, count = OFF_T_MAX;
int oflag, ifd, ofd;
size_t count = -1, oc = 0, ibs = 512, obs = 512;
ssize_t n;
off_t seek = 0, skip = 0;
int sync_flag = FALSE, noerror = FALSE, trunc_flag = TRUE, twobufs_flag = 0,
oflag, ifd, ofd, i;
const char *infile = NULL, *outfile = NULL;
char *ibuf, *obuf;
if (ENABLE_FEATURE_DD_SIGNAL_HANDLING) {
if (ENABLE_FEATURE_DD_SIGNAL_HANDLING)
{
struct sigaction sa;
memset(&sa, 0, sizeof(sa));
sa.sa_handler = dd_output_status;
sa.sa_handler = dd_output_status;
sa.sa_flags = SA_RESTART;
sigemptyset(&sa.sa_mask);
sigaction(SIGUSR1, &sa, 0);
sigaction(SIGUSR1, &sa, 0);
}
for (n = 1; n < argc; n++) {
char *arg = argv[n];
/* Must fit into positive ssize_t */
if (ENABLE_FEATURE_DD_IBS_OBS && !strncmp("ibs=", arg, 4))
ibs = xatoul_range_sfx(arg+4, 0, ((size_t)-1L)/2, dd_suffixes);
else if (ENABLE_FEATURE_DD_IBS_OBS && !strncmp("obs=", arg, 4))
obs = xatoul_range_sfx(arg+4, 0, ((size_t)-1L)/2, dd_suffixes);
else if (!strncmp("bs=", arg, 3))
ibs = obs = xatoul_range_sfx(arg+3, 0, ((size_t)-1L)/2, dd_suffixes);
/* These can be large: */
else if (!strncmp("count=", arg, 6))
count = XATOU_SFX(arg+6, dd_suffixes);
else if (!strncmp("seek=", arg, 5))
seek = XATOU_SFX(arg+5, dd_suffixes);
else if (!strncmp("skip=", arg, 5))
skip = XATOU_SFX(arg+5, dd_suffixes);
else if (!strncmp("if=", arg, 3))
infile = arg+3;
else if (!strncmp("of=", arg, 3))
outfile = arg+3;
else if (ENABLE_FEATURE_DD_IBS_OBS && !strncmp("conv=", arg, 5)) {
arg += 5;
for (i = 1; i < argc; i++) {
if (ENABLE_FEATURE_DD_IBS_OBS && !strncmp("ibs=", argv[i], 4)) {
ibs = bb_xparse_number(argv[i]+4, dd_suffixes);
twobufs_flag++;
} else if (ENABLE_FEATURE_DD_IBS_OBS && !strncmp("obs=", argv[i], 4)) {
obs = bb_xparse_number(argv[i]+4, dd_suffixes);
twobufs_flag++;
} else if (!strncmp("bs=", argv[i], 3)) {
ibs = obs = bb_xparse_number(argv[i]+3, dd_suffixes);
} else if (!strncmp("count=", argv[i], 6))
count = bb_xparse_number(argv[i]+6, dd_suffixes);
else if (!strncmp("seek=", argv[i], 5))
seek = bb_xparse_number(argv[i]+5, dd_suffixes);
else if (!strncmp("skip=", argv[i], 5))
skip = bb_xparse_number(argv[i]+5, dd_suffixes);
else if (!strncmp("if=", argv[i], 3))
infile = argv[i]+3;
else if (!strncmp("of=", argv[i], 3))
outfile = argv[i]+3;
else if (ENABLE_FEATURE_DD_IBS_OBS && !strncmp("conv=", argv[i], 5)) {
ibuf = argv[i]+5;
while (1) {
if (!strncmp("notrunc", arg, 7)) {
flags &= ~trunc_flag;
arg += 7;
} else if (!strncmp("sync", arg, 4)) {
flags |= sync_flag;
arg += 4;
} else if (!strncmp("noerror", arg, 7)) {
flags |= noerror;
arg += 7;
if (!strncmp("notrunc", ibuf, 7)) {
trunc_flag = FALSE;
ibuf += 7;
} else if (!strncmp("sync", ibuf, 4)) {
sync_flag = TRUE;
ibuf += 4;
} else if (!strncmp("noerror", ibuf, 7)) {
noerror = TRUE;
ibuf += 7;
} else {
bb_error_msg_and_die(bb_msg_invalid_arg, arg, "conv");
bb_error_msg_and_die(bb_msg_invalid_arg, argv[i]+5, "conv");
}
if (arg[0] == '\0') break;
if (*arg++ != ',') bb_show_usage();
if (ibuf[0] == '\0') break;
if (ibuf[0] == ',') ibuf++;
}
} else
bb_show_usage();
}
ibuf = xmalloc(ibs);
ibuf = obuf = xmalloc(ibs);
if (ibs != obs) {
flags |= twobufs_flag;
obuf = xmalloc(obs);
}
if (twobufs_flag) obuf = xmalloc(obs);
else obuf = ibuf;
if (infile != NULL)
ifd = xopen(infile, O_RDONLY);
else {
if (infile != NULL) {
ifd = bb_xopen(infile, O_RDONLY);
} else {
ifd = STDIN_FILENO;
infile = bb_msg_standard_input;
}
@@ -135,18 +119,20 @@ int dd_main(int argc, char **argv)
if (outfile != NULL) {
oflag = O_WRONLY | O_CREAT;
if (!seek && (flags & trunc_flag))
if (!seek && trunc_flag) {
oflag |= O_TRUNC;
}
ofd = xopen(outfile, oflag);
ofd = bb_xopen3(outfile, oflag, 0666);
if (seek && (flags & trunc_flag)) {
if (seek && trunc_flag) {
if (ftruncate(ofd, seek * obs) < 0) {
struct stat st;
if (fstat(ofd, &st) < 0 || S_ISREG(st.st_mode) ||
S_ISDIR(st.st_mode))
goto die_outfile;
if (fstat (ofd, &st) < 0 || S_ISREG (st.st_mode) ||
S_ISDIR (st.st_mode)) {
bb_perror_msg_and_die("%s", outfile);
}
}
}
} else {
@@ -167,81 +153,73 @@ int dd_main(int argc, char **argv)
}
if (seek) {
if (lseek(ofd, seek * obs, SEEK_CUR) < 0)
goto die_outfile;
if (lseek(ofd, seek * obs, SEEK_CUR) < 0) {
bb_perror_msg_and_die("%s", outfile);
}
}
while (in_full + in_part != count) {
if (flags & noerror) {
if (noerror) {
/* Pre-zero the buffer when doing the noerror thing */
memset(ibuf, '\0', ibs);
}
n = safe_read(ifd, ibuf, ibs);
if (n == 0)
if (n == 0) {
break;
}
if (n < 0) {
if (flags & noerror) {
if (noerror) {
n = ibs;
bb_perror_msg("%s", infile);
} else
} else {
bb_perror_msg_and_die("%s", infile);
}
}
if ((size_t)n == ibs)
if ((size_t)n == ibs) {
in_full++;
else {
} else {
in_part++;
if (flags & sync_flag) {
if (sync_flag) {
memset(ibuf + n, '\0', ibs - n);
n = ibs;
}
}
if (flags & twobufs_flag) {
if (twobufs_flag) {
char *tmp = ibuf;
while (n) {
size_t d = obs - oc;
if (d > n)
d = n;
if (d > n) d = n;
memcpy(obuf + oc, tmp, d);
n -= d;
tmp += d;
oc += d;
if (oc == obs) {
w = full_write_or_warn(ofd, obuf, obs, outfile);
if (w < 0) goto out_status;
if (w == obs)
out_full++;
else if (w > 0)
out_part++;
xwrite(ofd, obuf, obs);
out_full++;
oc = 0;
}
}
} else {
w = full_write_or_warn(ofd, ibuf, n, outfile);
if (w < 0) goto out_status;
if (w == obs)
out_full++;
else if (w > 0)
out_part++;
xwrite(ofd, ibuf, n);
if (n == ibs) out_full++;
else out_part++;
}
}
if (ENABLE_FEATURE_DD_IBS_OBS && oc) {
w = full_write_or_warn(ofd, obuf, oc, outfile);
if (w < 0) goto out_status;
if (w > 0)
out_part++;
xwrite(ofd, obuf, oc);
out_part++;
}
if (close(ifd) < 0) {
if (close (ifd) < 0) {
bb_perror_msg_and_die("%s", infile);
}
if (close(ofd) < 0) {
die_outfile:
if (close (ofd) < 0) {
bb_perror_msg_and_die("%s", outfile);
}
out_status:
dd_output_status(0);
return EXIT_SUCCESS;
Loaded 100 of 783 files, more files were not shown because too many files have changed in this diff. Show more